diff --git a/src/v2.5/01_tokenize.dag b/src/v2.5/01_tokenize.dag new file mode 100644 index 00000000000..3837e9a2b66 --- /dev/null +++ b/src/v2.5/01_tokenize.dag @@ -0,0 +1,651 @@ +module v2_5.compiler.tokenize + +import v2_5.std.node { Symbol } +import v2_5.std.identity { SourceSpan } +import v2_5.std.diagnostic { + ByteRange, + Diagnostic, + Outcome, + Textual, + Unavailable, + UserInputBoundary +} +import v2_5.std.token { Token, TokenShape, TokenStream } +import v2_5.std.stage_types { TokenizeStageOut } + +type Source { + file: String + file_symbol: Symbol + text: String +} + +type CharacterClass + = DigitClass + | IdentStartClass + | IdentContinueClass + | WhitespaceClass + +type IndexedChar { + index: Int + char: String +} + +type SourceFold { + init: R + step: fn(R, IndexedChar) -> R +} + +type LexerFrame { + cursor: Int + tokens: List + interpolation_depth: List + eof_emitted: Bool +} + +type LexerState + = Lexing { frame: LexerFrame } + | LexFailed { diagnostic: Diagnostic } + +type ClassScanState + = ClassOpen { end: Int } + | ClassClosed { end: Int } + +type LineScanState + = LineOpen { end: Int } + | LineClosed { end: Int } + +type StringBodyState + = StringOpen { cursor: Int, acc: String, escaped: Bool } + | StringClosed { content: String, end_pos: Int } + | StringInterpolation { content: String, end_pos: Int } + +type StringTokenRole + = WholeString + | InterpolationBegin + | InterpolationMiddle + | InterpolationEnd + +type ScanStep { + cursor: Int + token: Token + interpolation_depth: List +} + +type ScanOutcome + = Scanned { step: ScanStep } + | ScanRejected { diagnostic: Diagnostic } + +type TokenizeExpectation + = ExpectProduced + | ExpectRejected { reason: Symbol } + +type TokenizeRegression { + name: Symbol + source: Source + expected: TokenizeExpectation +} + +data unexpected_character: Symbol = unexpected_character +data unterminated_string: Symbol = unterminated_string +data unterminated_interpolation: Symbol = unterminated_interpolation +data lexical_progress_exhausted: Symbol = lexical_progress_exhausted + +data keyword_table: Map = { + "module": true, "import": true, + "type": true, "fn": true, "func": true, + "resource": true, "service": true, "data": true, + "interface": true, "pipeline": true, "profile": true, + "pattern": true, + "let": true, "return": true, "match": true, + "if": true, "then": true, "else": true, + "for": true, "in": true, "where": true, "with": true, + "true": true, "false": true, "none": true, "null": true, + "acquire": true, "release": true, + "capability": true, "operation": true, + "input": true, "output": true, + "idempotent": true, "readonly": true, "hermetic": true +} + +data single_punct: Map = { + "(": ShLParen, ")": ShRParen, + "[": ShLBracket, "]": ShRBracket, + ":": ShColon, ",": ShComma, ".": ShDot, + "+": ShPlus, "*": ShStar, "%": ShPercent, "/": ShSlash, + "=": ShEq, "<": ShLt, ">": ShGt, "-": ShMinus, + "!": ShBang, "?": ShQuestion, "|": ShPipe +} + +data double_punct: Map = { + "=>": ShFatArrow, "->": ShArrow, + "==": ShEqEq, "!=": ShNe, + "<=": ShLe, ">=": ShGe, + "&&": ShAnd, "||": ShOr, + "|>": ShPipeArrow, "??": ShNullCoalesce, + "..": ShDotDot +} + +fn span(source: Source, start: Int, end: Int) -> SourceSpan { + SourceSpan { file: source.file, start: start, end: end } +} + +fn diagnostic(source: Source, reason: Symbol, start: Int, end: Int) -> Diagnostic { + Diagnostic { + reason: reason, + at: Textual { file: source.file_symbol, extent: ByteRange { start: start, end: end } }, + correction: Unavailable { reason: UserInputBoundary } + } +} + +fn make_token(source: Source, start: Int, end: Int, lexeme: String, shape: TokenShape) -> Token { + Token { text: lexeme, span: span(source: source, start: start, end: end), shape: shape } +} + +fn fold_source_chars(source: Source, algebra: SourceFold) -> R { + fold(enumerate(chars(source.text)), init: algebra.init, f: fn(acc, pair) { + algebra.step(acc, IndexedChar { index: pair.first, char: from_code_point(cp: pair.second) }) + }) +} + +fn source_len(source: Source) -> Int { + count(chars(source.text)) +} + +fn source_char(source: Source, index: Int) -> String { + from_code_point(cp: chars(source.text)[index]) +} + +fn source_slice(source: Source, start: Int, end: Int) -> String { + chars_to_string(chars: chars(source.text), start: start, end: end) +} + +fn char_in_class(ch: String, class: CharacterClass) -> Bool { + match class { + DigitClass => ch >= "0" && ch <= "9" + IdentStartClass => (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch == "_" + IdentContinueClass => + (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch == "_" || + (ch >= "0" && ch <= "9") + WhitespaceClass => ch == " " || ch == "\t" + } +} + +fn scan_class(source: Source, start: Int, class: CharacterClass) -> Int { + let result = fold_source_chars( + source: source, + algebra: SourceFold { + init: ClassOpen { end: start }, + step: fn(state, item) { + match state { + ClassClosed { end } => ClassClosed { end: end } + ClassOpen { end } => + if item.index < start { ClassOpen { end: end } } + else if item.index != end { ClassOpen { end: end } } + else if char_in_class(ch: item.char, class: class) { ClassOpen { end: end + 1 } } + else { ClassClosed { end: end } } + } + } + } + ) + match result { + ClassOpen { end } => end + ClassClosed { end } => end + } +} + +fn scan_to_eol(source: Source, start: Int) -> Int { + let result = fold_source_chars( + source: source, + algebra: SourceFold { + init: LineOpen { end: start }, + step: fn(state, item) { + match state { + LineClosed { end } => LineClosed { end: end } + LineOpen { end } => + if item.index < start { LineOpen { end: end } } + else if item.index != end { LineOpen { end: end } } + else if item.char == "\n" { LineClosed { end: end } } + else { LineOpen { end: end + 1 } } + } + } + } + ) + match result { + LineOpen { end } => end + LineClosed { end } => end + } +} + +fn skip_trivia(source: Source, cursor: Int) -> Int { + let after_ws = scan_class(source: source, start: cursor, class: WhitespaceClass) + if after_ws + 1 < source_len(source: source) && + source_char(source: source, index: after_ws) == "/" && + source_char(source: source, index: after_ws + 1) == "/" { + scan_to_eol(source: source, start: after_ws) + } else { + after_ws + } +} + +fn classify_identifier(text: String) -> TokenShape { + match lookup(keyword_table, key: text) { + Some { value: _ } => ShKeyword + None => ShIdent + } +} + +fn scan_identifier(source: Source, frame: LexerFrame) -> ScanOutcome { + let end = scan_class(source: source, start: frame.cursor, class: IdentContinueClass) + let text = source_slice(source: source, start: frame.cursor, end: end) + Scanned { + step: ScanStep { + cursor: end, + token: make_token(source: source, start: frame.cursor, end: end, lexeme: text, shape: classify_identifier(text: text)), + interpolation_depth: frame.interpolation_depth + } + } +} + +fn scan_number(source: Source, frame: LexerFrame) -> ScanOutcome { + let int_end = scan_class(source: source, start: frame.cursor, class: DigitClass) + if int_end + 1 < source_len(source: source) && + source_char(source: source, index: int_end) == "." && + char_in_class(ch: source_char(source: source, index: int_end + 1), class: DigitClass) { + let frac_end = scan_class(source: source, start: int_end + 1, class: DigitClass) + let text = source_slice(source: source, start: frame.cursor, end: frac_end) + Scanned { + step: ScanStep { + cursor: frac_end, + token: make_token(source: source, start: frame.cursor, end: frac_end, lexeme: text, shape: ShLitFloat), + interpolation_depth: frame.interpolation_depth + } + } + } else { + let text = source_slice(source: source, start: frame.cursor, end: int_end) + Scanned { + step: ScanStep { + cursor: int_end, + token: make_token(source: source, start: frame.cursor, end: int_end, lexeme: text, shape: ShLitInt), + interpolation_depth: frame.interpolation_depth + } + } + } +} + +fn should_start_interpolation(source: Source, pos: Int) -> Bool { + if pos + 1 >= source_len(source: source) { + false + } else { + let next = source_char(source: source, index: pos + 1) + char_in_class(ch: next, class: IdentStartClass) || next == "(" || next == "!" || next == "-" + } +} + +fn escaped_char(ch: String) -> String { + if ch == "\"" { "\"" } + else if ch == "\\" { "\\" } + else if ch == "n" { "\n" } + else if ch == "t" { "\t" } + else if ch == "{" { "{" } + else if ch == "}" { "}" } + else { concat("\\", ch) } +} + +fn scan_string_body(source: Source, start: Int) -> StringBodyState { + fold_source_chars( + source: source, + algebra: SourceFold { + init: StringOpen { cursor: start, acc: "", escaped: false }, + step: fn(state, item) { + match state { + StringClosed { content, end_pos } => StringClosed { content: content, end_pos: end_pos } + StringInterpolation { content, end_pos } => StringInterpolation { content: content, end_pos: end_pos } + StringOpen { cursor, acc, escaped } => + if item.index < start { StringOpen { cursor: cursor, acc: acc, escaped: escaped } } + else if item.index != cursor { StringOpen { cursor: cursor, acc: acc, escaped: escaped } } + else if escaped { StringOpen { cursor: cursor + 1, acc: concat(acc, escaped_char(ch: item.char)), escaped: false } } + else if item.char == "\\" { StringOpen { cursor: cursor + 1, acc: acc, escaped: true } } + else if item.char == "\"" { StringClosed { content: acc, end_pos: cursor } } + else if item.char == "{" && should_start_interpolation(source: source, pos: cursor) { + StringInterpolation { content: acc, end_pos: cursor } + } + else { StringOpen { cursor: cursor + 1, acc: concat(acc, item.char), escaped: false } } + } + } + } + ) +} + +fn string_token_shape(role: StringTokenRole) -> TokenShape { + match role { + WholeString => ShLitStr + InterpolationBegin => ShStrBegin + InterpolationMiddle => ShStrMid + InterpolationEnd => ShStrEnd + } +} + +fn push_interpolation(stack: List) -> List { + list_push(stack, 0) +} + +fn drop_last(stack: List) -> List { + let len = count(stack) + fold(enumerate(stack), init: [], f: fn(result, pair) { + if pair.first < len - 1 { list_push(result, pair.second) } else { result } + }) +} + +fn replace_last(stack: List, value: Int) -> List { + list_push(drop_last(stack: stack), value) +} + +fn scan_string_with_role(source: Source, frame: LexerFrame, role: StringTokenRole, body_start: Int, span_start: Int) -> ScanOutcome { + let body = scan_string_body(source: source, start: body_start) + match body { + StringClosed { content, end_pos } => { + Scanned { + step: ScanStep { + cursor: end_pos + 1, + token: make_token(source: source, start: span_start, end: end_pos + 1, lexeme: content, shape: string_token_shape(role: role)), + interpolation_depth: frame.interpolation_depth + } + } + } + StringInterpolation { content, end_pos } => { + let token_shape = match role { + WholeString => ShStrBegin + InterpolationBegin => ShStrBegin + InterpolationMiddle => ShStrMid + InterpolationEnd => ShStrMid + } + Scanned { + step: ScanStep { + cursor: end_pos + 1, + token: make_token(source: source, start: span_start, end: end_pos + 1, lexeme: content, shape: token_shape), + interpolation_depth: push_interpolation(stack: frame.interpolation_depth) + } + } + } + StringOpen { cursor, acc, escaped: _ } => { + ScanRejected { + diagnostic: diagnostic( + source: source, + reason: unterminated_string, + start: span_start, + end: cursor + ) + } + } + } +} + +fn scan_string(source: Source, frame: LexerFrame) -> ScanOutcome { + scan_string_with_role(source: source, frame: frame, role: WholeString, body_start: frame.cursor + 1, span_start: frame.cursor) +} + +fn scan_string_continuation(source: Source, frame: LexerFrame) -> ScanOutcome { + scan_string_with_role(source: source, frame: frame, role: InterpolationEnd, body_start: frame.cursor + 1, span_start: frame.cursor) +} + +fn emit_punctuation(source: Source, frame: LexerFrame, shape: TokenShape, width: Int) -> ScanOutcome { + let text = source_slice(source: source, start: frame.cursor, end: frame.cursor + width) + Scanned { + step: ScanStep { + cursor: frame.cursor + width, + token: make_token(source: source, start: frame.cursor, end: frame.cursor + width, lexeme: text, shape: shape), + interpolation_depth: frame.interpolation_depth + } + } +} + +fn scan_lbrace(source: Source, frame: LexerFrame) -> ScanOutcome { + let new_depth = if count(frame.interpolation_depth) > 0 { + replace_last(stack: frame.interpolation_depth, value: last(frame.interpolation_depth).value + 1) + } else { + frame.interpolation_depth + } + Scanned { + step: ScanStep { + cursor: frame.cursor + 1, + token: make_token(source: source, start: frame.cursor, end: frame.cursor + 1, lexeme: "{", shape: ShLBrace), + interpolation_depth: new_depth + } + } +} + +fn scan_rbrace(source: Source, frame: LexerFrame) -> ScanOutcome { + let new_depth = if count(frame.interpolation_depth) > 0 { + replace_last(stack: frame.interpolation_depth, value: last(frame.interpolation_depth).value - 1) + } else { + frame.interpolation_depth + } + Scanned { + step: ScanStep { + cursor: frame.cursor + 1, + token: make_token(source: source, start: frame.cursor, end: frame.cursor + 1, lexeme: "}", shape: ShRBrace), + interpolation_depth: new_depth + } + } +} + +fn scan_newline(source: Source, frame: LexerFrame) -> ScanOutcome { + Scanned { + step: ScanStep { + cursor: frame.cursor + 1, + token: make_token(source: source, start: frame.cursor, end: frame.cursor + 1, lexeme: "\n", shape: ShNewline), + interpolation_depth: frame.interpolation_depth + } + } +} + +fn scan_token(source: Source, frame: LexerFrame) -> ScanOutcome { + let cursor = skip_trivia(source: source, cursor: frame.cursor) + let active = LexerFrame { + cursor: cursor, + tokens: frame.tokens, + interpolation_depth: frame.interpolation_depth, + eof_emitted: frame.eof_emitted + } + if cursor >= source_len(source: source) && count(active.interpolation_depth) > 0 { + ScanRejected { + diagnostic: diagnostic(source: source, reason: unterminated_interpolation, start: cursor, end: cursor) + } + } else if cursor >= source_len(source: source) { + Scanned { + step: ScanStep { + cursor: cursor + 1, + token: make_token(source: source, start: cursor, end: cursor, lexeme: "", shape: ShEof), + interpolation_depth: active.interpolation_depth + } + } + } else { + let ch = source_char(source: source, index: cursor) + if ch == "\n" { scan_newline(source: source, frame: active) } + else if ch == "}" && count(active.interpolation_depth) > 0 && last(active.interpolation_depth).value == 0 { + let after_pop = LexerFrame { + cursor: cursor, + tokens: active.tokens, + interpolation_depth: drop_last(stack: active.interpolation_depth), + eof_emitted: active.eof_emitted + } + scan_string_continuation(source: source, frame: after_pop) + } + else if ch == "\"" { scan_string(source: source, frame: active) } + else if char_in_class(ch: ch, class: DigitClass) { scan_number(source: source, frame: active) } + else if char_in_class(ch: ch, class: IdentStartClass) { scan_identifier(source: source, frame: active) } + else { + let next = if cursor + 1 < source_len(source: source) { source_char(source: source, index: cursor + 1) } else { "" } + let two = concat(ch, next) + match lookup(double_punct, key: two) { + Some { value: shape } => emit_punctuation(source: source, frame: active, shape: shape, width: 2) + None => + if ch == "{" { scan_lbrace(source: source, frame: active) } + else if ch == "}" { scan_rbrace(source: source, frame: active) } + else { + match lookup(single_punct, key: ch) { + Some { value: shape } => emit_punctuation(source: source, frame: active, shape: shape, width: 1) + None => ScanRejected { + diagnostic: diagnostic(source: source, reason: unexpected_character, start: cursor, end: cursor + 1) + } + } + } + } + } + } +} + +fn append_step(frame: LexerFrame, step: ScanStep) -> LexerFrame { + LexerFrame { + cursor: step.cursor, + tokens: list_push(frame.tokens, step.token), + interpolation_depth: step.interpolation_depth, + eof_emitted: frame.eof_emitted || token_is_eof(token: step.token) + } +} + +fn token_is_eof(token: Token) -> Bool { + match token.shape { + ShEof => true + _ => false + } +} + +fn lex_step(source: Source, state: LexerState, item: IndexedChar) -> LexerState { + match state { + LexFailed { diagnostic } => LexFailed { diagnostic: diagnostic } + Lexing { frame } => + if item.index < frame.cursor { Lexing { frame: frame } } + else { + match scan_token(source: source, frame: frame) { + Scanned { step } => + if step.cursor <= frame.cursor { + LexFailed { + diagnostic: diagnostic( + source: source, + reason: lexical_progress_exhausted, + start: frame.cursor, + end: frame.cursor + ) + } + } else { + Lexing { frame: append_step(frame: frame, step: step) } + } + ScanRejected { diagnostic } => LexFailed { diagnostic: diagnostic } + } + } + } +} + +fn tokenize_outcome(source: Source) -> Outcome { + let initial = Lexing { frame: LexerFrame { cursor: 0, tokens: [], interpolation_depth: [], eof_emitted: false } } + let folded = fold_source_chars( + source: source, + algebra: SourceFold { + init: initial, + step: fn(state, item) { + lex_step(source: source, state: state, item: item) + } + } + ) + match folded { + LexFailed { diagnostic } => Rejected { diagnostic: diagnostic } + Lexing { frame } => + if frame.cursor < source_len(source: source) { + Rejected { + diagnostic: diagnostic( + source: source, + reason: lexical_progress_exhausted, + start: frame.cursor, + end: frame.cursor + ) + } + } else if count(frame.interpolation_depth) > 0 { + Rejected { + diagnostic: diagnostic( + source: source, + reason: unterminated_interpolation, + start: frame.cursor, + end: frame.cursor + ) + } + } else if frame.eof_emitted { + Produced { value: TokenStream { tokens: frame.tokens } } + } else { + let eof = make_token(source: source, start: frame.cursor, end: frame.cursor, lexeme: "", shape: ShEof) + Produced { value: TokenStream { tokens: list_push(frame.tokens, eof) } } + } + } +} + +fn tokenize(source: Source) -> TokenizeStageOut { + TokenizeStageOut { tokens: tokenize_outcome(source: source) } +} + +fn tokenize_expectation_holds(source: Source, expected: TokenizeExpectation) -> Bool { + match tokenize(source: source).tokens { + Produced { value: _ } => + match expected { + ExpectProduced => true + ExpectRejected { reason: _ } => false + } + Rejected { diagnostic: d } => + match expected { + ExpectProduced => false + ExpectRejected { reason } => d.reason == reason + } + } +} + +data nested_brace_interpolation_regression: TokenizeRegression = TokenizeRegression { + name: nested_brace_interpolation_regression, + source: Source { + file: "nested_brace_interpolation_regression", + file_symbol: nested_brace_interpolation_regression, + text: concat( + "\"x ", + concat( + from_code_point(cp: code_point("{")), + concat( + "foo(", + concat( + from_code_point(cp: code_point("{")), + concat( + "bar: 1", + concat( + from_code_point(cp: code_point("}")), + concat( + ")", + concat( + from_code_point(cp: code_point("}")), + concat(" y", "\"") + ) + ) + ) + ) + ) + ) + ) + ) + }, + expected: ExpectProduced +} + +data unterminated_interpolation_regression: TokenizeRegression = TokenizeRegression { + name: unterminated_interpolation_regression, + source: Source { + file: "unterminated_interpolation_regression", + file_symbol: unterminated_interpolation_regression, + text: concat("\"x ", concat(from_code_point(cp: code_point("{")), "name")) + }, + expected: ExpectRejected { reason: unterminated_interpolation } +} + +data nested_brace_interpolation_regression_holds: Bool = tokenize_expectation_holds( + source: nested_brace_interpolation_regression.source, + expected: nested_brace_interpolation_regression.expected + ) + +data unterminated_interpolation_regression_holds: Bool = tokenize_expectation_holds( + source: unterminated_interpolation_regression.source, + expected: unterminated_interpolation_regression.expected + ) diff --git a/src/v2.5/std/stage_types.dag b/src/v2.5/std/stage_types.dag index 3199b0706ee..4bc7ec1ec37 100644 --- a/src/v2.5/std/stage_types.dag +++ b/src/v2.5/std/stage_types.dag @@ -8,13 +8,13 @@ // Reconcile: calm-crane-724 normalize seam (Seam* types). // Lowering: phase AST → Node { kind, children: List } at stage boundaries. // -// Pipeline (type signatures are the contract): -// tokenize : SourceText -> TokenStream -// parse : TokenStream -> Outcome -// resolve : ParseModule -> Outcome -// normalize: ResolvedModule -> Outcome -// infer : NormalizedModule -> Outcome -// emit : (InferredModule, TargetModel) -> Outcome +// Pipeline stage ports (the records below are the contract): +// tokenize : Source -> TokenizeStageOut { tokens: Outcome } +// parse : ParseStageIn -> ParseStageOut { outcome: Outcome } +// resolve : ResolveStageIn -> ResolveStageOut { outcome: Outcome } +// normalize: NormalizeStageIn -> NormalizeStageOut { outcome: Outcome } +// infer : InferStageIn -> InferStageOut { outcome: Outcome } +// emit : EmitStageIn -> EmitStageOut { outcome: Outcome } // Stage boundary failures use Outcome/Rejected + Diagnostic; recovery-shaped // *Error expr variants inside Produced modules are v2 parity only (🟡 gated). @@ -1030,9 +1030,9 @@ type InferredModule { span: SourceSpan } -// ========================================================================= -// Pipeline stage ports — distinct types enforce phase ordering -// ========================================================================= +type TokenizeStageOut { + tokens: Outcome +} type ParseStageIn { tokens: TokenStream