From ce48e6ff3077da19549d1e44c01a10cb6b565c08 Mon Sep 17 00:00:00 2001 From: devin Date: Wed, 2 Dec 2026 22:41:25 +0000 Subject: [PATCH] Move template expression brace depth scan to Lean KUU-4825 Co-Authored-By: sushi@mercari.com --- .../Lexer/KotlinLexer+Strings.swift | 120 ++++++++++++++++ .../LeanParser+TemplateScan.swift | 38 ++++++ Sources/LeanParser/Bridge/TemplateScan.c | 44 ++++++ .../ParserProofs/Runtime/TemplateScanFFI.lean | 56 ++++++++ .../LeanParser/ParserProofs/TemplateScan.lean | 127 +++++++++++++++++ .../ParserProofs/Tests/TemplateScan.lean | 66 +++++++++ .../Lexer/TemplateScanLeanTests.swift | 129 ++++++++++++++++++ 7 files changed, 580 insertions(+) create mode 100644 Sources/CompilerCore/Parser/LeanFeatures/LeanParser+TemplateScan.swift create mode 100644 Sources/LeanParser/Bridge/TemplateScan.c create mode 100644 Sources/LeanParser/ParserProofs/Runtime/TemplateScanFFI.lean create mode 100644 Sources/LeanParser/ParserProofs/TemplateScan.lean create mode 100644 Sources/LeanParser/ParserProofs/Tests/TemplateScan.lean create mode 100644 Tests/CompilerCoreFrontendTests/Lexer/TemplateScanLeanTests.swift diff --git a/Sources/CompilerCore/Lexer/KotlinLexer+Strings.swift b/Sources/CompilerCore/Lexer/KotlinLexer+Strings.swift index f1769655415..2368a685977 100644 --- a/Sources/CompilerCore/Lexer/KotlinLexer+Strings.swift +++ b/Sources/CompilerCore/Lexer/KotlinLexer+Strings.swift @@ -145,6 +145,122 @@ extension KotlinLexer { return true } + /// Replays the Lean template-scan event stream: gaps between events are + /// lexed with the original trivia/`scanNextTokens` loop, brace events emit + /// brace tokens, and pause events delegate to the recursive string/char/ + /// template scans before the Lean scan is resumed. Returns nil when the + /// Lean runtime is unavailable or the input window exceeds the scan cap. + private func leanScanTemplateExpression(expressionStart: Int) -> (tokens: [Token], closeRange: SourceRange)? { + let scanCap = 65536 + var scanPos = offset + var depth = 1 + var tokens: [Token] = [] + + while true { + guard byteCount() - scanPos <= scanCap else { return nil } + var input: [UInt64] = [UInt64(byteCount() - scanPos), UInt64(scanPos), UInt64(depth)] + input.reserveCapacity(3 + (byteCount() - scanPos)) + for index in scanPos ..< byteCount() { + input.append(UInt64(byte(at: index))) + } + guard let outcome = LeanParser.templateScan(input) else { return nil } + guard !outcome.events.isEmpty else { return nil } + + var completed: (tokens: [Token], closeRange: SourceRange)? + var resume = false + var eventIndex = 0 + for event in outcome.events { + eventIndex += 1 + let isLast = eventIndex == outcome.events.count + // Gap processing: lex opaque content between the current offset + // and the event position exactly like the original loop. + var pendingTrivia: [TriviaPiece] = [] + while offset < event.start { + let trivia = consumeTrivia() + if offset >= event.start { + pendingTrivia = trivia + break + } + let scanned = scanNextTokens(leadingTrivia: trivia) + if scanned.isEmpty { + diagnostics.error( + "KSWIFTK-LEX-0001", + "Invalid character in template expression.", + range: makeRange(start: offset, end: min(offset + 1, byteCount())) + ) + offset += 1 + continue + } + tokens.append(contentsOf: scanned) + } + guard offset == event.start else { return nil } + + switch event.type { + case 1: + tokens.append(Token(kind: .symbol(.lBrace), range: makeRange(start: event.start, end: event.end), leadingTrivia: pendingTrivia)) + offset = event.end + case 2: + tokens.append(Token(kind: .symbol(.rBrace), range: makeRange(start: event.start, end: event.end), leadingTrivia: pendingTrivia)) + offset = event.end + case 3: + guard isLast, outcome.terminal else { return nil } + offset = event.end + completed = (tokens, makeRange(start: event.start, end: event.end)) + case 4: + guard isLast, outcome.terminal else { return nil } + diagnostics.error( + "KSWIFTK-LEX-0002", + "Unterminated template expression.", + range: SourceRange( + start: SourceLocation(file: file, offset: expressionStart), + end: SourceLocation(file: file, offset: byteCount()) + ) + ) + completed = (tokens, SourceRange( + start: SourceLocation(file: file, offset: expressionStart), + end: SourceLocation(file: file, offset: byteCount()) + )) + case 5, 6: + guard isLast, !outcome.terminal else { return nil } + offset = event.start + if event.type == 6 { + tokens.append(contentsOf: scanRawString(leadingTrivia: pendingTrivia, start: event.start)) + } else { + tokens.append(contentsOf: scanString(leadingTrivia: pendingTrivia, start: event.start)) + } + resume = true + case 7: + guard isLast, !outcome.terminal else { return nil } + offset = event.start + tokens.append(scanCharLiteral(leadingTrivia: pendingTrivia, start: event.start)) + resume = true + case 8: + guard isLast, !outcome.terminal else { return nil } + offset = event.start + let templateRange = makeRange(start: event.start, end: event.end) + offset = event.end + var nestedTokens: [Token] = [] + nestedTokens.append(Token(kind: .templateExprStart, range: templateRange, leadingTrivia: pendingTrivia)) + let nested = scanTemplateExpression() + nestedTokens.append(contentsOf: nested.tokens) + nestedTokens.append(Token(kind: .templateExprEnd, range: nested.closeRange, leadingTrivia: [])) + tokens.append(contentsOf: nestedTokens) + resume = true + default: + return nil + } + if completed != nil || resume { break } + } + + if let completed { + return completed + } + guard resume else { return nil } + scanPos = offset + depth = outcome.depthAtStop + } + } + func scanTemplateExpression() -> (tokens: [Token], closeRange: SourceRange) { let expressionStart = offset guard templateExpressionNestingDepth < Self.maximumTemplateExpressionNestingDepth else { @@ -159,6 +275,10 @@ extension KotlinLexer { templateExpressionNestingDepth += 1 defer { templateExpressionNestingDepth -= 1 } + if let lean = leanScanTemplateExpression(expressionStart: expressionStart) { + return lean + } + var depth = 1 var tokens: [Token] = [] diff --git a/Sources/CompilerCore/Parser/LeanFeatures/LeanParser+TemplateScan.swift b/Sources/CompilerCore/Parser/LeanFeatures/LeanParser+TemplateScan.swift new file mode 100644 index 00000000000..b8fa181b1e1 --- /dev/null +++ b/Sources/CompilerCore/Parser/LeanFeatures/LeanParser+TemplateScan.swift @@ -0,0 +1,38 @@ +import Foundation + +struct TemplateScanOutcome { + let terminal: Bool + let depthAtStop: Int + let events: [(type: Int, start: Int, end: Int)] +} + +extension LeanParser { + private static let templateScanEntry = featureSymbol("kswiftk_lean_parser_template_scan", as: TemplateScanPlan.self) + + private typealias TemplateScanPlan = @convention(c) (UnsafePointer, Int, UnsafeMutablePointer, Int) -> UInt64 + + /// Runs the Lean template-expression brace-depth scan. + /// Input words: `[count, pos, depth, byte...]`. + static func templateScan(_ input: [UInt64]) -> TemplateScanOutcome? { + guard let templateScanCall = templateScanEntry, input.count >= 3 else { return nil } + let byteCount = Int(input[0]) + let capacity = 3 + 3 * (byteCount + 2) + var output = Array(repeating: UInt64.max, count: capacity) + let count = input.withUnsafeBufferPointer { inputBuffer in + output.withUnsafeMutableBufferPointer { outputBuffer in + templateScanCall( + inputBuffer.baseAddress!, inputBuffer.count, outputBuffer.baseAddress!, outputBuffer.count + ) + } + } + guard count >= 3, count <= UInt64(capacity), (count - 3) % 3 == 0 else { return nil } + let eventCount = Int(output[2]) + guard 3 + 3 * eventCount == Int(count) else { return nil } + var events: [(type: Int, start: Int, end: Int)] = [] + events.reserveCapacity(eventCount) + for index in 0 ..< eventCount { + events.append((Int(output[3 + index * 3]), Int(output[4 + index * 3]), Int(output[5 + index * 3]))) + } + return TemplateScanOutcome(terminal: output[0] == 1, depthAtStop: Int(output[1]), events: events) + } +} diff --git a/Sources/LeanParser/Bridge/TemplateScan.c b/Sources/LeanParser/Bridge/TemplateScan.c new file mode 100644 index 00000000000..c579f474284 --- /dev/null +++ b/Sources/LeanParser/Bridge/TemplateScan.c @@ -0,0 +1,44 @@ +#include "../BridgeSupport.h" + +extern lean_object *kswiftk_lean_template_scan_compute(size_t context, uint64_t input_count, lean_object *world); + +typedef struct { + const uint64_t *input; + size_t input_count; + uint64_t *output; + size_t capacity; + size_t written; + int invalid; +} template_scan_io; + +uint64_t kswiftk_lean_template_scan_read(size_t context, uint64_t index) { + template_scan_io *io = (template_scan_io *)context; + if (index >= io->input_count) { + io->invalid = 1; + return UINT64_MAX; + } + return io->input[index]; +} + +lean_object *kswiftk_lean_template_scan_write(size_t context, uint64_t value, lean_object *world) { + (void)world; + template_scan_io *io = (template_scan_io *)context; + if (io->written >= io->capacity) { + io->invalid = 1; + } else { + io->output[io->written++] = value; + } + return lean_io_result_mk_ok(lean_box(0)); +} + +uint64_t kswiftk_lean_parser_template_scan(const uint64_t *input, size_t input_count, + uint64_t *output, size_t capacity) { + if (!kswiftk_lean_bridge_prepare_thread()) { + return UINT64_MAX; + } + template_scan_io io = {.input = input, .input_count = input_count, .output = output, + .capacity = capacity, .written = 0, .invalid = 0}; + lean_object *result = kswiftk_lean_template_scan_compute((size_t)&io, input_count, lean_io_mk_world()); + uint64_t count = kswiftk_lean_bridge_unpack_uint64(result); + return io.invalid || io.written != count ? UINT64_MAX : count; +} diff --git a/Sources/LeanParser/ParserProofs/Runtime/TemplateScanFFI.lean b/Sources/LeanParser/ParserProofs/Runtime/TemplateScanFFI.lean new file mode 100644 index 00000000000..59707bfdd51 --- /dev/null +++ b/Sources/LeanParser/ParserProofs/Runtime/TemplateScanFFI.lean @@ -0,0 +1,56 @@ +import ParserProofs.TemplateScan + +/-! +FFI wrapper for the template-expression brace-depth scan. + +Input words: `[count, pos, depth, byte(0), ..., byte(count-1)]` — the raw bytes +of the remaining input starting at `pos`, with the current brace `depth`. +Output words: `[stopReason, depthAtStop, eventCount, per event (type, start, end)]` +where stopReason 0 = pause, 1 = terminal. +-/ +namespace ParserProofs.Runtime.TemplateScanFFI + +open ParserProofs + +@[extern "kswiftk_lean_template_scan_read"] +opaque readWord (context : USize) (index : UInt64) : UInt64 + +@[extern "kswiftk_lean_template_scan_write"] +opaque writeWord (context : USize) (word : UInt64) : IO Unit + +@[export kswiftk_lean_template_scan_compute] +def compute (context : USize) (inputCount : UInt64) : IO UInt64 := do + let failure : UInt64 := 18446744073709551615 + if inputCount < 3 then + return failure + let count := (readWord context 0).toNat + let pos := (readWord context 1).toNat + let depth := (readWord context 2).toNat + if inputCount < UInt64.ofNat (3 + count) then + return failure + let mut bytes : List UInt8 := [] + for i in [0:count] do + let w := readWord context (UInt64.ofNat (3 + i)) + bytes := UInt8.ofNat (w.toNat % 256) :: bytes + let outcome := tsScanBody bytes.reverse pos depth + match outcome with + | .pause d events => + writeWord context 0 + writeWord context (UInt64.ofNat d) + writeWord context (UInt64.ofNat events.length) + for (ty, s, e) in events do + writeWord context (UInt64.ofNat ty) + writeWord context (UInt64.ofNat s) + writeWord context (UInt64.ofNat e) + return UInt64.ofNat (3 + 3 * events.length) + | .terminal events => + writeWord context 1 + writeWord context 0 + writeWord context (UInt64.ofNat events.length) + for (ty, s, e) in events do + writeWord context (UInt64.ofNat ty) + writeWord context (UInt64.ofNat s) + writeWord context (UInt64.ofNat e) + return UInt64.ofNat (3 + 3 * events.length) + +end ParserProofs.Runtime.TemplateScanFFI diff --git a/Sources/LeanParser/ParserProofs/TemplateScan.lean b/Sources/LeanParser/ParserProofs/TemplateScan.lean new file mode 100644 index 00000000000..5a4319d27b7 --- /dev/null +++ b/Sources/LeanParser/ParserProofs/TemplateScan.lean @@ -0,0 +1,127 @@ +/- + TemplateScan.lean — Lean model of the brace-depth scan inside string template + expressions (`scanTemplateExpression` in KotlinLexer+Strings.swift). + + Byte-level state machine walking the template body tracking `{`/`}` depth + while skipping trivia (whitespace, line comments, nested block comments) and + backticked identifiers. Quotes and nested template starts are *pause* + events: the scan stops there and the host lexer performs the recursive scan + before resuming, so the model never needs string-internal rules. A `}` + inside a string, char literal, comment or backticked identifier can never be + observed as a closing brace — the central property proved in the test module. + + Modes: 0 = normal, 1 = line comment, 2 = block comment, 3 = backtick. + + Event triples (type, start, end): + 1 openBrace / 2 midCloseBrace / 3 finalCloseBrace / 4 unterminated / + 5 stringNormal / 6 stringRaw / 7 charLiteral / 8 nestedTemplate +-/ + +namespace ParserProofs + +inductive TSResult where + | pause (depth : Nat) (events : List (Nat × Nat × Nat)) + | terminal (events : List (Nat × Nat × Nat)) + deriving Repr, DecidableEq + +/-- The scan. `tsScan mode bcDepth depth pos input acc` — structurally + recursive on `input`; every call site consumes at least one byte or + terminates. Normal-mode byte dispatch is inlined in each branch so the + recursion stays visibly structural. -/ +def tsScan : Nat → Nat → Nat → Nat → List UInt8 → List (Nat × Nat × Nat) → TSResult + -- normal mode, EOF + | 0, _, _, pos, [], acc => + TSResult.terminal (acc.reverse ++ [(4, pos, pos)]) + -- normal mode, at least two lookahead bytes after the head + | 0, bcDepth, depth, pos, b1 :: b2 :: b3 :: rest, acc => + if b1 == 0x2F && b2 == 0x2F then + tsScan 1 bcDepth depth (pos + 2) (b3 :: rest) acc + else if b1 == 0x2F && b2 == 0x2A then + tsScan 2 1 depth (pos + 2) (b3 :: rest) acc + else if b1 == 0x24 && b2 == 0x7B then + TSResult.pause depth (acc.reverse ++ [(8, pos, pos + 2)]) + else if b1 == 0x22 && b2 == 0x22 && b3 == 0x22 then + TSResult.pause depth (acc.reverse ++ [(6, pos, pos + 3)]) + else if b1 == 0x22 then + TSResult.pause depth (acc.reverse ++ [(5, pos, pos + 1)]) + else if b1 == 0x27 then + TSResult.pause depth (acc.reverse ++ [(7, pos, pos + 1)]) + else if b1 == 0x60 then + tsScan 3 bcDepth depth (pos + 1) (b2 :: b3 :: rest) acc + else if b1 == 0x7B then + tsScan 0 bcDepth (depth + 1) (pos + 1) (b2 :: b3 :: rest) ((1, pos, pos + 1) :: acc) + else if b1 == 0x7D then + if depth == 1 then TSResult.terminal (acc.reverse ++ [(3, pos, pos + 1)]) + else tsScan 0 bcDepth (depth - 1) (pos + 1) (b2 :: b3 :: rest) ((2, pos, pos + 1) :: acc) + else + tsScan 0 bcDepth depth (pos + 1) (b2 :: b3 :: rest) acc + -- normal mode, exactly one lookahead byte + | 0, bcDepth, depth, pos, [b1, b2], acc => + if b1 == 0x2F && b2 == 0x2F then + tsScan 1 bcDepth depth (pos + 2) [] acc + else if b1 == 0x2F && b2 == 0x2A then + tsScan 2 1 depth (pos + 2) [] acc + else if b1 == 0x24 && b2 == 0x7B then + TSResult.pause depth (acc.reverse ++ [(8, pos, pos + 2)]) + else if b1 == 0x22 then + TSResult.pause depth (acc.reverse ++ [(5, pos, pos + 1)]) + else if b1 == 0x27 then + TSResult.pause depth (acc.reverse ++ [(7, pos, pos + 1)]) + else if b1 == 0x60 then + tsScan 3 bcDepth depth (pos + 1) [b2] acc + else if b1 == 0x7B then + tsScan 0 bcDepth (depth + 1) (pos + 1) [b2] ((1, pos, pos + 1) :: acc) + else if b1 == 0x7D then + if depth == 1 then TSResult.terminal (acc.reverse ++ [(3, pos, pos + 1)]) + else tsScan 0 bcDepth (depth - 1) (pos + 1) [b2] ((2, pos, pos + 1) :: acc) + else + tsScan 0 bcDepth depth (pos + 1) [b2] acc + -- normal mode, last byte + | 0, bcDepth, depth, pos, [b1], acc => + if b1 == 0x22 then + TSResult.pause depth (acc.reverse ++ [(5, pos, pos + 1)]) + else if b1 == 0x27 then + TSResult.pause depth (acc.reverse ++ [(7, pos, pos + 1)]) + else if b1 == 0x60 then + tsScan 3 bcDepth depth (pos + 1) [] acc + else if b1 == 0x7B then + tsScan 0 bcDepth (depth + 1) (pos + 1) [] ((1, pos, pos + 1) :: acc) + else if b1 == 0x7D then + if depth == 1 then TSResult.terminal (acc.reverse ++ [(3, pos, pos + 1)]) + else tsScan 0 bcDepth (depth - 1) (pos + 1) [] ((2, pos, pos + 1) :: acc) + else + tsScan 0 bcDepth depth (pos + 1) [] acc + -- line comment mode: runs until 0x0A (exclusive), then normal handles it + | 1, _, _, pos, [], acc => + TSResult.terminal (acc.reverse ++ [(4, pos, pos)]) + | 1, bcDepth, depth, pos, b :: rest, acc => + if b == 0x0A then tsScan 0 bcDepth depth (pos + 1) rest acc + else tsScan 1 bcDepth depth (pos + 1) rest acc + -- block comment mode: bcDepth counts nested `/*` + | 2, _, _, pos, [], acc => + TSResult.terminal (acc.reverse ++ [(4, pos, pos)]) + | 2, bcDepth, depth, pos, b1 :: b2 :: rest, acc => + if b1 == 0x2F && b2 == 0x2A then + tsScan 2 (bcDepth + 1) depth (pos + 2) rest acc + else if b1 == 0x2A && b2 == 0x2F then + if bcDepth == 1 then tsScan 0 0 depth (pos + 2) rest acc + else tsScan 2 (bcDepth - 1) depth (pos + 2) rest acc + else + tsScan 2 bcDepth depth (pos + 1) (b2 :: rest) acc + | 2, bcDepth, depth, pos, [_], acc => + tsScan 2 bcDepth depth (pos + 1) [] acc + -- backtick mode: runs to closing backtick (inclusive) + | 3, _, _, pos, [], acc => + TSResult.terminal (acc.reverse ++ [(4, pos, pos)]) + | 3, bcDepth, depth, pos, b :: rest, acc => + if b == 0x60 then tsScan 0 bcDepth depth (pos + 1) rest acc + else tsScan 3 bcDepth depth (pos + 1) rest acc + -- unreachable mode fallback for totality + | _, _, _, _, _, acc => TSResult.terminal acc.reverse + +/-- Entry point: scan a template expression body starting at `pos` with brace + depth `depth` (1 for a fresh template body). -/ +def tsScanBody (input : List UInt8) (pos depth : Nat) : TSResult := + tsScan 0 0 depth pos input [] + +end ParserProofs diff --git a/Sources/LeanParser/ParserProofs/Tests/TemplateScan.lean b/Sources/LeanParser/ParserProofs/Tests/TemplateScan.lean new file mode 100644 index 00000000000..68ef615a091 --- /dev/null +++ b/Sources/LeanParser/ParserProofs/Tests/TemplateScan.lean @@ -0,0 +1,66 @@ +import ParserProofs.TemplateScan + +namespace ParserProofs.Tests.TemplateScan + +open ParserProofs + +private def bytes (s : String) : List UInt8 := s.toUTF8.toList + +-- A lone `}` at depth 1 closes the template body at its exact position. +example : tsScanBody (bytes "}") 0 1 = .terminal [(3, 0, 1)] := by native_decide + +-- Nested braces produce open/mid-close/final-close in order with exact ranges. +example : tsScanBody (bytes "{}}") 0 1 = + .terminal [(1, 0, 1), (2, 1, 2), (3, 2, 3)] := by native_decide + +-- A `}` inside a line comment never closes the template; scanning stops at the +-- real closing brace after the newline. +example : tsScanBody (bytes "// }\n}") 0 1 = .terminal [(3, 5, 6)] := by native_decide + +-- A `}` inside a block comment never closes the template. +example : tsScanBody (bytes "/* } */ }") 0 1 = .terminal [(3, 8, 9)] := by native_decide + +-- Nested block comments: the close inside the inner comment is inert and the +-- outer comment must close before scanning resumes. +example : tsScanBody (bytes "/* /* } */ } */ }") 0 1 = .terminal [(3, 16, 17)] := by native_decide + +-- An unterminated block comment consumes to EOF; the template is unterminated +-- and stops exactly at the end of input. +example : tsScanBody (bytes "/* }") 0 1 = .terminal [(4, 4, 4)] := by native_decide + +-- A `}` inside a backticked identifier never closes the template. +example : tsScanBody (bytes "`}` }") 0 1 = .terminal [(3, 4, 5)] := by native_decide + +-- Quotes pause the scan *before* any byte inside the string is examined, so a +-- `}` inside a string can never be observed as a closing brace. +example : tsScanBody (bytes "\"}") 0 1 = .pause 1 [(5, 0, 1)] := by native_decide + +-- Three quotes open a raw string pause of width 3. +example : tsScanBody (bytes "\"\"\"x") 0 1 = .pause 1 [(6, 0, 3)] := by native_decide + +-- Exactly two quotes are still a normal string pause of width 1. +example : tsScanBody (bytes "\"\"x") 0 1 = .pause 1 [(5, 0, 1)] := by native_decide + +-- A char literal quote pauses with width 1. +example : tsScanBody (bytes "'") 0 1 = .pause 1 [(7, 0, 1)] := by native_decide + +-- `${` pauses for the nested template recursion. +example : tsScanBody (bytes "${") 0 1 = .pause 1 [(8, 0, 2)] := by native_decide + +-- `$` not followed by `{` is plain content; scanning continues past it. +example : tsScanBody (bytes "$x}") 0 1 = .terminal [(3, 2, 3)] := by native_decide + +-- EOF in normal mode is an unterminated stop exactly at the end of input. +example : tsScanBody (bytes "abc") 0 1 = .terminal [(4, 3, 3)] := by native_decide + +-- Braces opened before a pause are reported in the paused depth so the host +-- can resume the scan with the correct depth. +example : tsScanBody (bytes "{ \"") 0 1 = .pause 2 [(1, 0, 1), (5, 2, 3)] := by native_decide + +-- Resuming at depth 2: the first `}` is a mid-close, the second the final close. +example : tsScanBody (bytes "}}") 0 2 = .terminal [(2, 0, 1), (3, 1, 2)] := by native_decide + +-- Content bytes including operator characters never close. +example : tsScanBody (bytes "a + b}") 0 1 = .terminal [(3, 5, 6)] := by native_decide + +end ParserProofs.Tests.TemplateScan diff --git a/Tests/CompilerCoreFrontendTests/Lexer/TemplateScanLeanTests.swift b/Tests/CompilerCoreFrontendTests/Lexer/TemplateScanLeanTests.swift new file mode 100644 index 00000000000..e86a634522d --- /dev/null +++ b/Tests/CompilerCoreFrontendTests/Lexer/TemplateScanLeanTests.swift @@ -0,0 +1,129 @@ +@testable import CompilerCore +import Foundation +import Testing + +@Suite +struct TemplateScanLeanTests { + private let file = FileID(rawValue: 15) + private let interner = StringInterner() + + private func lex(_ source: String) -> (tokens: [Token], diagnostics: DiagnosticEngine) { + let diagnostics = DiagnosticEngine() + let tokens = KotlinLexer(file: file, source: Data(source.utf8), interner: interner, diagnostics: diagnostics).lexAll() + return (tokens, diagnostics) + } + + private func range(_ start: Int, _ end: Int) -> SourceRange { + SourceRange(start: SourceLocation(file: file, offset: start), end: SourceLocation(file: file, offset: end)) + } + + private func kinds(_ tokens: [Token]) -> [String] { + tokens.map { "\($0.kind)" } + } + + @Test + func simpleTemplateExpression() throws { + let (tokens, diagnostics) = lex("\"a${x}b\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(tokens.contains { $0.kind == .templateExprStart }) + #expect(tokens.contains { $0.kind == .templateExprEnd }) + #expect(tokens.contains { $0.kind == .identifier(interner.intern("x")) }) + guard let exprEnd = tokens.first(where: { $0.kind == .templateExprEnd }) else { + Issue.record("missing templateExprEnd") + return + } + #expect(exprEnd.range == range(5, 6)) + } + + @Test + func braceInsideInnerStringDoesNotCloseTemplate() throws { + let (tokens, diagnostics) = lex("\"${ \"}\" }\"") + #expect(diagnostics.diagnostics.isEmpty) + // The `}` inside the inner string is a string segment, not a brace token. + #expect(tokens.contains { $0.kind == .stringSegment(interner.intern("}")) }) + #expect(!tokens.contains { $0.kind == .symbol(.rBrace) }) + guard let exprEnd = tokens.first(where: { $0.kind == .templateExprEnd }) else { + Issue.record("missing templateExprEnd") + return + } + #expect(exprEnd.range == range(8, 9)) + } + + @Test + func braceInsideCommentDoesNotCloseTemplate() throws { + let (tokens, diagnostics) = lex("\"${ /* } */ x }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(!tokens.contains { $0.kind == .symbol(.rBrace) }) + #expect(tokens.contains { $0.kind == .identifier(interner.intern("x")) }) + guard let exprEnd = tokens.first(where: { $0.kind == .templateExprEnd }) else { + Issue.record("missing templateExprEnd") + return + } + #expect(exprEnd.range == range(14, 15)) + } + + @Test + func braceInsideLineCommentDoesNotCloseTemplate() throws { + let (tokens, diagnostics) = lex("\"${ // }\n x }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(!tokens.contains { $0.kind == .symbol(.rBrace) }) + #expect(tokens.contains { $0.kind == .identifier(interner.intern("x")) }) + } + + @Test + func braceInsideBacktickedIdentifierDoesNotCloseTemplate() throws { + let (tokens, diagnostics) = lex("\"${ `}` }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(!tokens.contains { $0.kind == .symbol(.rBrace) }) + #expect(tokens.contains { $0.kind == .backtickedIdentifier(interner.intern("}")) }) + } + + @Test + func braceInsideCharLiteralDoesNotCloseTemplate() throws { + let (tokens, diagnostics) = lex("\"${ '}' }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(!tokens.contains { $0.kind == .symbol(.rBrace) }) + } + + @Test + func nestedTemplateExpressionScans() throws { + let (tokens, diagnostics) = lex("\"${ \"${x}\" }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(tokens.filter { $0.kind == .templateExprStart }.count == 2) + #expect(tokens.filter { $0.kind == .templateExprEnd }.count == 2) + #expect(tokens.contains { $0.kind == .identifier(interner.intern("x")) }) + } + + @Test + func nestedBracesProduceBraceTokens() throws { + let (tokens, diagnostics) = lex("\"${ { } }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(tokens.contains { $0.kind == .symbol(.lBrace) }) + #expect(tokens.contains { $0.kind == .symbol(.rBrace) }) + guard let lbrace = tokens.first(where: { $0.kind == .symbol(.lBrace) }) else { + Issue.record("missing lBrace") + return + } + #expect(lbrace.range == range(4, 5)) + } + + @Test + func unterminatedTemplateExpressionDiagnostic() throws { + let (tokens, diagnostics) = lex("\"${ x") + #expect(tokens.contains { $0.kind == .identifier(interner.intern("x")) }) + #expect(diagnostics.diagnostics.contains { $0.code == "KSWIFTK-LEX-0002" }) + } + + @Test + func rawStringInsideTemplate() throws { + let (tokens, diagnostics) = lex("\"${ \"\"\"}\"\"\" }\"") + #expect(diagnostics.diagnostics.isEmpty) + #expect(!tokens.contains { $0.kind == .symbol(.rBrace) }) + } + + @Test + func unterminatedBlockCommentStopsAtEOF() throws { + let (_, diagnostics) = lex("\"${ /* ") + #expect(diagnostics.diagnostics.contains { $0.code == "KSWIFTK-LEX-0002" }) + } +}