PeaBox Lab › PeaLang › Learn › Chapter 2 › Lesson 1

Part I — Foundations · Chapter 2 · Lesson 1 of 5 · 10 min read

Lesson 1: Source Files, Lexical Structure, Comments, Identifiers, and Literals

Lesson level: Foundation

Purpose: Understand how PeaLang turns source text into meaningful tokens before parsing statements and expressions.

Learning objectives

By the end of this lesson, you should be able to:

1.1 From text to tokens

A PeaLang program begins as plain UTF-8 text. Before the parser can understand declarations or expressions, the lexer scans that text from left to right and groups characters into tokens. A token records a kind, a value, and its source line and column.

Consider this source:

let total = 12.5

The characters form four meaningful tokens: the keyword let, the identifier total, the assignment symbol =, and the numeric literal 12.5. The newline that follows is also significant to the lexer.

A lexeme is the exact source text that forms a token. A token kind classifies it. For example, total is a lexeme classified as an identifier, while let is classified as a keyword.

1.2 Source files and encoding

PeaLang source files conventionally use the .pea extension. The command-line tools discover files by that extension, and the runtime reads source as UTF-8 text. Use a plain-text editor; rich-text formatting does not belong in source code.

A source filename should communicate purpose, such as pricing_rules.pea or case_priority.pea. Avoid names that depend on spaces, temporary labels, or ambiguous versions when a stable project layout can provide that context.

1.3 Whitespace

Spaces, tabs, and carriage returns separate tokens but are otherwise skipped by the lexer. This means these two declarations have the same token structure:

let count=3
let count = 3

The formatter chooses a consistent presentation even when the lexer could accept several spacing styles. Write for readers, not merely for token recognition.

Indentation improves block readability, but braces define the block. Do not rely on indentation alone to determine program structure.

1.4 Newlines and semicolons

Unlike ordinary spaces, each newline becomes a NEWLINE token. Newlines therefore help separate statements and preserve useful source positions.

A semicolon is also recognized as punctuation. The safest foundational style is one clear statement per line. This keeps formatting, diagnostics, code review, and debugging straightforward.

1.5 Comments

PeaLang supports two line-comment markers:

# explain the next declaration
// an alternative line comment

After either marker, the lexer ignores characters until the newline or end of file. The newline itself remains available as a separator.

Use comments to explain intent, constraints, policy reasons, unusual boundaries, or security assumptions. Do not narrate obvious syntax.

# Escalation threshold comes from the approved support policy.
const high_impact_threshold = 8

A line comment begins wherever the marker appears outside a string. The same characters inside a quoted string are text, not a comment marker.

1.6 Identifiers

An identifier names a value, function, module binding, parameter, or other program element. An identifier begins with a letter or underscore. Remaining characters may be letters, digits, or underscores.

ExampleValid?Reason
totalYesBegins with a letter.
unit_price2YesDigits are allowed after the first character.
_internal_valueYesAn underscore may begin a name.
2nd_valueNoAn identifier cannot begin with a digit.
unit-priceNo as one nameThe hyphen is tokenized as subtraction.
customer tierNo as one nameWhitespace separates tokens.

Identifiers are case-sensitive. total, Total, and TOTAL are different names. Prefer a consistent convention so capitalization does not hide defects.

1.7 Reserved keywords

The lexer recognizes the following reserved words:

let, const, print, if, else, while, for, in, function, return, true, false, null, and, or, not, break, continue, import, assert, parallel, try, catch, finally, throw, export, as, async, await

A reserved keyword has a language role and should not be used as an ordinary identifier. For example, let if = 3 cannot treat if as a variable name because the lexer already classifies it as the conditional keyword.

Choose descriptive alternatives such as condition_met, return_value, or awaiting_result.

1.8 Naming guidance

1.9 Literal values

A literal writes a value directly in source code. PeaLang recognizes strings, numbers, booleans, and null at the lexical level. List and map forms combine literals with punctuation and are parsed as collection expressions.

1.10 String literals

Strings may use double or single quotation marks:

"PeaLang"
'gold'

The opening and closing quote must match. A string can contain escape sequences introduced by a backslash:

EscapeMeaning
\nNewline character
\tTab character
\rCarriage return
\"Double quote
\'Single quote
\\Backslash

Examples:

let message = "First line\nSecond line"
let quote = "She said \"ready\""

If the lexer reaches the end of the file before finding the matching quote, it reports an unterminated string at the source location where the literal began.

1.11 Numeric literals

A sequence of digits forms an integer literal, such as 0, 15, or 480. Digits followed by a decimal point and at least one more digit form a floating-point literal, such as 12.5 or 0.25.

The minus sign is an operator rather than part of the numeric token. Thus -5 is understood as the unary minus operator applied to the literal 5.

At this level, write decimal numbers without separators or suffixes. A trailing decimal point without a following digit is not recognized as part of a floating-point literal.

1.12 Boolean and null literals

The keywords true and false represent boolean values. They are lowercase and unquoted:

let security_relevant = false

The keyword null represents the absence of a value:

let assigned_agent = null

Quoted forms such as "false" and "null" are strings, not boolean or null values.

1.13 Collection literal forms

Square brackets delimit list expressions, commas separate items, and braces with colons support map-like structures in the language grammar. Examples include:

let scores = [8, 9, 10]
let case = {"id": "CASE-1042", "impact": 6}

The lexer does not decide that these are valid collections. It emits brackets, braces, commas, colons, strings, numbers, and identifiers as tokens. The parser then determines whether the token sequence follows the grammar.

1.14 Operators and punctuation

The lexer recognizes single-character operators and delimiters including:

+ - * / % ( ) { } [ ] , . : ; < > ! =

It also recognizes these two-character operators:

== != <= >= += -= *= /=

Longest valid grouping matters. In total >= 30, the characters > and = become one >= token rather than two separate tokens.

Word operators and, or, and not are reserved keywords. Their behavior and precedence are covered in the expressions lesson.

1.15 Source locations and lexical errors

Every token records the line and column where it begins. The lexer advances the line number at each newline and resets the column for the next line. Diagnostics can therefore point to the location where scanning failed.

Two important lexical failures are:

When reading a diagnostic, start at the reported location, inspect the surrounding token boundary, and then look immediately before it. A missing quote can cause later characters to be interpreted inside the same string, while an unsupported symbol fails at the symbol itself.

1.16 Lexing versus parsing

Lexing answers, “What tokens are present?” Parsing answers, “Do these tokens form a valid program structure?”

For example, let = 3 contains recognizable tokens: a let keyword, assignment symbol, and number. It can pass character recognition but still fail parsing because a declaration requires a name.

Likewise, an unmatched closing brace is a recognized punctuation token, but the parser reports that it does not fit the surrounding structure.

1.17 Manual token analysis

Analyze this source one line at a time:

# response policy
const target = 60
let urgent = true
print "Target: {target}"

The comment text produces no comment token. Its newline remains. The declaration line produces a const keyword, identifier, assignment symbol, number, and newline. The next line produces a let keyword, identifier, assignment symbol, true keyword, and newline. The print line produces a print keyword, one string token, and newline.

Interpolation braces inside the quoted text remain part of the string token during lexing. Later stages interpret interpolation behavior.

1.18 Classification practice

Source fragmentPrimary classification
constKeyword
response_minutesIdentifier
240Integer numeric literal
12.5Floating-point numeric literal
"gold"String literal
falseBoolean keyword/literal
nullNull keyword/literal
>=Two-character operator
[List-opening delimiter
# noteLine comment, skipped by the lexer

1.19 Common mistakes

1.20 Guided practice

1.21 Hands-on lab: Build a lexical showcase

Create lexical_showcase.pea containing:

Format, check, and run the valid file. Then make three separate temporary defective copies:

Deliverable: The valid source file, its output, and a diagnostic note for each defective copy identifying whether the failure occurs during lexing or parsing and where the reported location points.

1.22 Diagnostic workflow

This process prevents trial-and-error edits from hiding the original cause.

1.23 Review questions

1.24 Applied challenge

Take the Chapter 1 checkpoint source and produce a lexical inventory. List each distinct keyword, identifier, literal category, operator, delimiter, and comment form it uses. Then identify five valid tokens or literal forms it does not yet use and add a small, meaningful demonstration of each without changing the original policy result.

Lesson summary

PeaLang source begins as UTF-8 text and is scanned into positioned tokens. Spaces and tabs separate tokens, newlines remain meaningful separators, and two line-comment forms are supported. Identifiers follow explicit character rules and cannot replace reserved keywords. Strings, numbers, booleans, null, operators, and delimiters each have recognizable lexical forms. Understanding these boundaries makes diagnostics faster and prepares you to study declarations, assignment, and scope.

Lesson status: Approved.

← Previous Next →