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:
- describe the role of a .pea source file;
- distinguish characters, lexemes, tokens, and syntax;
- explain how whitespace and newlines are treated;
- write both supported forms of line comment;
- create valid identifiers and avoid reserved keywords;
- recognize string, integer, floating-point, boolean, and null literals;
- identify punctuation and operator tokens; and
- interpret lexical errors using line and column information.
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.
| Example | Valid? | Reason |
|---|---|---|
| total | Yes | Begins with a letter. |
| unit_price2 | Yes | Digits are allowed after the first character. |
| _internal_value | Yes | An underscore may begin a name. |
| 2nd_value | No | An identifier cannot begin with a digit. |
| unit-price | No as one name | The hyphen is tokenized as subtraction. |
| customer tier | No as one name | Whitespace 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
- Use names that express domain meaning: affected_users, not n.
- Use lowercase words separated by underscores for ordinary values.
- Keep related names parallel: high_minutes, medium_minutes, low_minutes.
- Avoid misleading type labels in names when the value may evolve.
- Use an initial underscore deliberately for internal-facing names, not as a substitute for clear scope.
- Do not differ only by capitalization.
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:
| Escape | Meaning |
|---|---|
| \n | Newline character |
| \t | Tab character |
| \r | Carriage 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:
- Unterminated string: the source ends before a matching quote is found.
- Unexpected character: a character does not belong to whitespace, comments, strings, numbers, identifiers, recognized operators, or punctuation.
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 fragment | Primary classification |
|---|---|
| const | Keyword |
| response_minutes | Identifier |
| 240 | Integer numeric literal |
| 12.5 | Floating-point numeric literal |
| "gold" | String literal |
| false | Boolean keyword/literal |
| null | Null keyword/literal |
| >= | Two-character operator |
| [ | List-opening delimiter |
| # note | Line comment, skipped by the lexer |
1.19 Common mistakes
- Using a keyword as a name: choose a descriptive non-reserved identifier.
- Starting a name with a digit: move the digit after a letter or underscore.
- Using a hyphen inside a name: use an underscore; the hyphen means subtraction.
- Assuming capitalization is ignored: names are case-sensitive.
- Leaving a string open: add the matching quotation mark.
- Confusing quoted and unquoted values: "true" is text; true is boolean.
- Writing 12. as a float: include a digit after the decimal point.
- Expecting indentation to create blocks: braces define block structure.
- Using an unsupported symbol: replace it with a recognized operator or valid source text.
1.20 Guided practice
- Classify every token in let subtotal = quantity * unit_price.
- Explain why gold-tier is not one identifier.
- Rewrite let 2nd = 2 with a valid descriptive name.
- Explain the difference between null and "null".
- Predict how total+=5 is grouped into tokens.
- Identify which characters are skipped in a line comment and which separator remains.
- Explain why let = 3 is a parsing problem rather than an unexpected-character problem.
1.21 Hands-on lab: Build a lexical showcase
Create lexical_showcase.pea containing:
- both styles of line comment;
- three valid identifiers with different allowed forms;
- one integer and one floating-point literal;
- single-quoted and double-quoted strings;
- a string containing a newline escape and an escaped quote;
- true, false, and null values;
- a list literal and a string-keyed map literal;
- one comparison using a two-character operator; and
- labeled output that proves the valid source runs.
Format, check, and run the valid file. Then make three separate temporary defective copies:
- remove a closing quote to provoke an unterminated-string error;
- insert an unsupported character outside a string to provoke an unexpected-character error; and
- write a declaration with no identifier to provoke a parser error.
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
- Read the exact message and source location.
- Decide whether the scanner rejected a character/string or the parser rejected a token sequence.
- Inspect the reported position and the token immediately before it.
- Make one minimal correction.
- Rerun pea check.
- Only after the check succeeds, run the program.
This process prevents trial-and-error edits from hiding the original cause.
1.23 Review questions
- What information does each token record?
- How are spaces and tabs treated differently from newlines?
- Which two markers begin a line comment?
- What characters may begin an identifier?
- Why can a reserved keyword not serve as an ordinary name?
- How are integer and floating-point literals distinguished lexically?
- Why is -5 composed of an operator and a number token?
- What is the difference between a lexical error and a parsing error?
- Why do source line and column positions matter?
- How does longest valid grouping affect >= and +=?
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.