semantics/SOURCE_ANALYSIS.md
- Repository
- guillermomolina/protos
- Commit
2723a55555e7beecee0816bf99d16e3c8c1ae635- Tree
c36054e4e5abd7fc29a039b4e096cac2e8706492- Blob
27e405090345bf405051fa4121ac9ce69989c604- Source
- View exact source on GitHub
Standard Library source analysis
Language version: 0.1 Status: Draft Decision: D272-C1
This document is the primary normative owner of the independently importable
ordinary Standard Library MODULEs std:source/lexer, std:source/highlight and
std:source/parser. Core lexical structure and syntax remain owned by
the grammar; module semantics remain owned by
MODULES.md and Error behavior by ERRORS.md.
No Core type, grammar construct, Prelude binding or ambient authority is added.
Public surface and lifecycle
The exact public own exports are:
| MODULE | Exports |
|---|---|
std:source/lexer | lex, LexicalError, LexerLimitError |
std:source/highlight | runs |
std:source/parser | parse, ParseError, ParserLimitError |
There is no aggregate std:source initializer, uppercase alias, or public
private-SOURCE route. Private implementation files are not public modules.
Core bootstrap initializes none of these public modules. Lexer initializes
neither Highlight nor Parser. Highlight initializes Lexer and itself, never
Parser; Parser initializes Lexer and itself, never Highlight. Ordinary imports
share the same Actor-local Lexer instance; different Actors share no mutable
module instances or module-local Error prototypes. Compiler-private frontend
initialization is separate from application-visible module initialization and
must not expose compiler-owned mutable frontend objects to applications.
All four module-local Error prototypes are ordinary direct descendants of Error and are absent from the Prelude. Errors propagated from Lexer retain their original occurrence identity; consumers neither wrap nor recreate them.
Analysis treats source as data and never executes it or acquires I/O, Process, Network, Filesystem, Clock, Timing, Entropy or execution authority. Public analysis limits do not define production language admission limits. The Surface AST describes written syntax; it is not the canonical semantic AST.
Lexer
Lexer.lex(source, recover: false, maxScalars: 262144, maxPieces: 262145)
Answers a fresh record:
{ pieces: pieces; diagnostics: diagnostics }
Each piece is a fresh record:
{ kind: kind; start: start; end: end; rawText: rawText; lexeme: lexeme; escapeSpans: escapeSpans }
Positions are zero-based, half-open Unicode scalar offsets into source
(a supplementary character counts as one position).
Identifier recognition uses the Unicode Character Database version 17.0.0, including its XID_Start and XID_Continue properties and NFC validation, according to the lexical rules owned by the Core grammar.
kind is one of the Core grammar token kinds — IDENTIFIER, NUMBER,
STRING, THIS, CONTEXT, NULL, TRUE, FALSE, SUPER, LPAREN,
RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, DOT, COMMA, COLON,
SEMICOLON, EQUALS, FAT_ARROW, PLUS, MINUS, STAR, SLASH,
PERCENT, BANG, LESS, LESS_EQUAL, GREATER, GREATER_EQUAL,
DOUBLE_EQUALS, TRIPLE_EQUALS, NOT_EQUALS, NOT_EQUALS_2, AND, OR,
AMPERSAND, PIPE, TILDE, SHIFT_LEFT, SHIFT_RIGHT, ELLIPSIS,
CARET, NEWLINE, EOF — or one of the tool pieces
HORIZONTAL_WHITESPACE, LINE_COMMENT, BLOCK_COMMENT and ERROR, which
are not grammar tokens.
Only the six reserved spellings this, context, super, true, false
and null get reserved kinds. Contextual spellings such as if, while,
for, match, return and args are IDENTIFIER, and a reserved spelling
after . keeps its reserved kind: deciding member names is a parser concern.
| Piece | rawText | lexeme |
|---|---|---|
ordinary token, NUMBER | original spelling | original spelling |
STRING | original literal with delimiters and escapes | decoded String value |
NEWLINE | LF, CR or CRLF as written | "\n" |
EOF | "" | "" |
trivia, ERROR | original text | null |
escapeSpans holds one { start: start; end: end } record per escape of a
valid STRING, in absolute source positions (also for triple-double-quoted
literals whose indentation was removed). It is empty for every other piece.
The pieces form an exact partition of the source: the first piece starts at
0, every non-EOF piece has positive length and starts where the previous one
ended, and exactly one EOF piece ends the Array at
[source.size(), source.size()). Concatenating every rawText reproduces the
source exactly, including U+0000, a leading or embedded U+FEFF,
supplementary characters and every LF, CR and CRLF. An empty source
answers one EOF piece.
Strict and recovering operation
Both modes share one recognition. Every malformed region is the same in both modes:
- strict (
recover: false): the first malformed region signals a freshLexicalErroroccurrence withcode,startandend; a successful result has no diagnostics; - recovering (
recover: true): each malformed region becomes oneERRORpiece and one{ code: code; start: start; end: end }diagnostic with the same span, and recognition continues. NoSTRINGis ever fabricated from a malformed literal.
Diagnostic codes: UNEXPECTED_SCALAR, NON_NFC_IDENTIFIER,
INVALID_NUMERIC_LITERAL, INVALID_SYMBOLIC_OPERATOR,
INVALID_STRING_ESCAPE, UNTERMINATED_STRING, STRING_NEWLINE,
INVALID_TRIPLE_INDENTATION and UNTERMINATED_BLOCK_COMMENT. Regions:
- an unknown scalar is exactly one scalar;
- a malformed numeric literal covers the attempted literal, an attempted radix fraction and its adjacent identifier-like continuation, never following punctuation;
- an unsupported maximal symbolic run covers the whole run;
- an ordinary String runs through its closing quote, or stops before a
logical newline or at the end of the source; a triple-double String runs
through its closing
"""or to the end of the source; - an unterminated block comment runs to the end of the source.
Arguments, limits and errors
source must be a String, recover a Boolean, maxScalars an Integer of at
least 0 and maxPieces an Integer of at least 1. Arguments are never
coerced; an argument outside its domain signals a fresh ordinary Error.
Limits are inclusive. A source longer than maxScalars scalars, or a
partition that needs more than maxPieces pieces including EOF, signals a
fresh LexerLimitError occurrence with limit ("maxScalars" or
"maxPieces") and maximum, and no partial result is answered. Room for
EOF is always reserved, so Lexer.lex("", maxScalars: 0, maxPieces: 1)
succeeds and Lexer.lex("a", maxPieces: 1) fails.
The module publishes both Error prototypes on the Lexer MODULE:
Lexer.LexicalError.handle(() => { Lexer.lex(text) }, (error) => { error.code })
Lexer.LexerLimitError.handle(() => { Lexer.lex(text) }, (error) => { error.limit })
Results are fresh: no piece, Array or record is shared with another call or with module state.
Highlight
Highlight.runs(source, maxScalars: 262144, maxPieces: 262145)
Lexes source once with recovery and answers:
{ runs: runs; diagnostics: diagnostics }
Each run is { role: role; start: start; end: end; text: text } with a
positive scalar span and the original source text. Concatenating every
text reproduces the source exactly; an empty source answers no runs.
Adjacent runs never share a role. Roles:
| Role | Pieces |
|---|---|
plain | IDENTIFIER, HORIZONTAL_WHITESPACE, NEWLINE, and a reserved spelling right after . |
comment | LINE_COMMENT, BLOCK_COMMENT |
string / escape | STRING, split at its escape spans |
number | NUMBER |
languageVariable | THIS, CONTEXT |
control | SUPER |
literal | TRUE, FALSE, NULL |
operator | symbolic operators and COLON |
punctuation | parentheses, braces, brackets, DOT, COMMA, SEMICOLON, ELLIPSIS |
invalid | ERROR |
Highlighting produces no colors, markup or HTML. Argument errors and
LexerLimitError failures propagate unchanged.
Parser
Parser: import("std:source/parser")
parsed: Parser.parse(source)
root: parsed.root
kept: Parser.parse(source, retainSource: true)
The module exports exactly parse, ParseError and ParserLimitError.
The complete signature is:
Parser.parse(source, retainSource: false, maxScalars: 262144,
maxPieces: 262145, maxRecords: 524290, maxDepth: 1024)
source must be a semantic String, retainSource canonical true or false,
and all limits semantic Integers. maxScalars admits zero; the other limits
must be at least one. Invalid arguments signal a fresh ordinary Error.
No argument is coerced. Parsing requires no authority and never executes source,
resolves imports or names, or acquires execution authority.
Each successful invocation answers exactly { root, source, pieces }. root
is a Program covering the entire input, including exterior trivia. With
retention disabled, source and pieces are null. With retention enabled,
source is the original String and pieces the original unaltered lexer Array.
Retention does not change the tree. Disabling retention removes those result
references; it does not eliminate the lexer's temporary materialization cost.
The parser calls the existing lexer once in strict mode before recognizing
syntax. LexicalError, LexerLimitError and unrelated runtime errors propagate
unchanged. Syntax failures signal fresh module-local ParseError occurrences
with exactly { code, start, end } payload slots. Codes are:
UNEXPECTED_TOKENUNEXPECTED_EOFINVALID_SLOT_TARGETINVALID_ASSIGNMENT_TARGETDUPLICATE_PARAMETERDUPLICATE_ARGUMENT_LABEL
Intervals identify the unexpected token, offending write operator, or second
duplicate identifier. EOF is the empty interval at source.size(). No partial
Program or recovery result is returned.
All coordinates are zero-based, half-open Unicode scalar offsets, including
for supplementary characters and mixed CR/LF/CRLF input. Every labeled record
has exactly kind, start, end plus its fields below. Span fields are ordinary
records with exactly start and end. Other records cover their actual written
syntax, including their delimiters and excluding unrelated exterior trivia.
| Kind | Additional own fields |
|---|---|
| Program | expressions |
| Literal | literalKind, value |
| Name | name |
| Intrinsic | name |
| Group | expression |
| Member | receiver, name, nameSpan |
| Call | receiver, arguments, argumentSpan, trailingBody |
| SuperSend | name, nameSpan, arguments, argumentSpan |
| Index | receiver, index, bracketSpan |
| ArrayConstruction | arguments |
| MapConstruction | table |
| Object | parentExpression, items, bodySpan |
| Closure | parameters, parameterForm, parameterSpan, arrowSpan, body |
| Unary | operator, operatorSpan, operand |
| Binary | operator, operatorSpan, left, right |
| SlotCreation | target, operatorSpan, value |
| MultipleSlotCreation | targets, targetSpan, operatorSpan, value |
| Assignment | target, operatorSpan, value |
| NonLocalReturn | spelling, keywordSpan, expression |
| ContextualIf | condition, headerSpan, trueBody, elseSpan, falseBody |
| ContextualWhile | condition, headerSpan, body |
| ContextualUntil | body, keywordSpan, condition, headerSpan |
| ContextualFor | form, binder, binderSpan, headerSpan, iterable, initial, terminal, step, body |
| ContextualMatch | subject, headerSpan, table |
| BracedBody | expressions |
| Argument | form, name, nameSpan, expression |
| Parameter | form, name, nameSpan, defaultValue |
| ObjectItem | form, expression |
| MapTable | entries |
| MapEntry | key, value |
Sequences are ordered ordinary Arrays; empty sequences are fresh Arrays. Optional fields always exist and use null for absence. Records and structural Arrays are mutable ordinary objects, independent between invocations. There is no node prototype hierarchy, hidden public accounting field, cursor, parent pointer, execution Context or visitor protocol.
Literal.literalKind is NUMBER, STRING, TRUE, FALSE or NULL.
NUMBER preserves the original spelling String without numeric conversion;
STRING reuses the lexer's decoded String; the other values are canonical
true, false and null. Intrinsic.name is this or context; args
is an ordinary Name. Member names and unary/binary operator spellings remain
as written. Groups are preserved.
Closure.parameterForm is BARE or PARENTHESIZED. Its body is the actual
expression or BracedBody. Parameter.form is PLAIN, DEFAULT or REST;
only DEFAULT has a non-null defaultValue. Argument.form is POSITIONAL,
NAMED or SPREAD; only NAMED has non-null name and nameSpan.
Call.trailingBody is a separate BracedBody or null, never a synthetic Argument.
ObjectItem.form distinguishes EXPRESSION and COMPOSITION.
Object.parentExpression is null when no parent is written.
Contextual forms preserve their written headers and bodies rather than creating
synthetic closures or protocol calls. NonLocalReturn.spelling is ^ or
return. The optional elseSpan and falseBody of ContextualIf are both null
or both present. ContextualFor.form is GENERIC or NUMERIC; its binder is
the written identifier String with binderSpan. GENERIC uses iterable and
null numeric fields; NUMERIC uses initial, terminal, an optional step and
null iterable. MapConstruction and ContextualMatch contain a MapTable covering
the written braces. MultipleSlotCreation contains ordered Name targets.
This representation precedes canonicalization; no written operation is lowered.
Limits are inclusive. maxPieces includes EOF. maxRecords counts all labeled
records, including Program and auxiliary Argument, Parameter, ObjectItem,
MapTable and MapEntry records, but excludes spans, Arrays, pieces and the result
wrapper. Before nested recognition or record allocation, admission also counts
committed enclosing records still awaiting construction and the next child,
without counting the reserved Program twice or recounting completed operands.
maxDepth counts record nesting, with Program at depth one and
child-bearing auxiliary records participating. Empty input fits (1, 1), x
needs (2, 2) and (x) needs (3, 3). Structural failures signal a fresh
ParserLimitError with { limit, maximum }, where limit is maxRecords or
maxDepth. Contextual lookahead builds no abandoned records.