Repository navigation
feat(psl-parser): fault-tolerant recursive-descent parser (parse + SourceFile) under ./syntax - #795
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a fault-tolerant PSL parser, a SourceFile position utility, cursor/token-to-green-tree plumbing with diagnostics and recovery, expression/attribute/type annotation parsers, document/declaration parsing, comprehensive tests, and public re-exports for parsing primitives. ChangesPSL Parser Implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/1-framework/2-authoring/psl-parser/src/parse.ts (1)
504-525: 💤 Low valueMinor: Diagnostic code reuse for duplicate
typesblocks is semantically imprecise but acceptable.At line 515,
INVALID_TYPES_MEMBERis used for duplicate top-leveltypesblocks, while the same code is used for invalid entries inside atypesblock (line 600). The message clearly distinguishes the cases, and the PR explicitly notes "no new codes," so this is fine given the constraints.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/1-framework/2-authoring/psl-parser/src/parse.ts` around lines 504 - 525, The current reuse of INVALID_TYPES_MEMBER in parseTypesBlock for duplicate top-level `types` is acceptable; leave as-is if you want no new diagnostic codes. If you prefer semantic precision, add a new diagnostic constant (e.g., INVALID_DUPLICATE_TOP_LEVEL_TYPES) and replace the use of INVALID_TYPES_MEMBER inside the parseTypesBlock branch where state.topLevelTypesSeen is true so the error uniquely identifies duplicate top-level `types` (keep parseTypesBlock, keywordMark, and the existing message handling otherwise).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/1-framework/2-authoring/psl-parser/src/parse.ts`:
- Around line 504-525: The current reuse of INVALID_TYPES_MEMBER in
parseTypesBlock for duplicate top-level `types` is acceptable; leave as-is if
you want no new diagnostic codes. If you prefer semantic precision, add a new
diagnostic constant (e.g., INVALID_DUPLICATE_TOP_LEVEL_TYPES) and replace the
use of INVALID_TYPES_MEMBER inside the parseTypesBlock branch where
state.topLevelTypesSeen is true so the error uniquely identifies duplicate
top-level `types` (keep parseTypesBlock, keywordMark, and the existing message
handling otherwise).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 0bb3b592-746b-486c-9d19-fd1d0f678624
📒 Files selected for processing (2)
packages/1-framework/2-authoring/psl-parser/src/parse.tspackages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.ts
System-design review — PR #795: fault-tolerant recursive-descent PSL parserReviewer lens: architect (system shape, ubiquitous language, bounded contexts, dependency direction, typology integrity). Implementation correctness, test correctness, buildability, scope, and docs prose are out of scope for this pass and are referred to the relevant lenses where they come up. Verdict: Approve with required follow-ups. The module shape is sound and the parser earns its place in the authoring layer. But the change introduces a second diagnostic type and a second position/range type family that duplicate concepts the core layer already owns ( 1. What problem is being solved, and what new concepts enter the systemBefore this change, This PR adds the missing edge: a fault-tolerant recursive-descent New concepts introduced at the type/module/namespace level:
The position-free-CST invariant and the 2. Subsystem fit and conceptual integrity2a. Two parsers now coexist — name the conceptual-integrity costThe package now exposes two functions that both turn PSL source into a tree:
These are not redundant — they target different trees (semantic AST vs lossless CST) for different consumers (contract inference vs tooling). That justifies two functions. But the surface does not tell the reader that. Two functions named 2b. Layer placement of the parser — correctThe parser lives in 2c. Widening a core union from an authoring feature — dependency-direction smell
The import direction (authoring → core) is correct and compiles cleanly; the parser is right to depend on the shared diagnostic-code vocabulary rather than invent its own. The concern is the reverse pressure: an authoring-layer feature is now the reason a core-layer type grows. The core union is meant to be the shared vocabulary of PSL diagnostics across the whole framework; growing it whenever a new authoring parser needs a code is defensible if these codes are genuinely part of the shared PSL diagnostic vocabulary (which 2d. Position/Range duplication — the most significant structural finding
So the system now carries two coordinate-type families and two diagnostic types for the same domain:
Apply the 'reads cold' probe: a fresh contributor handed both This is not automatically wrong — there is a real, defensible reason for two representations:
But that difference is a convention/encoding difference, not a concept difference, and the surface does not say so. The architecturally clean shapes are one of:
Recommendation: do not invent a third name; either reuse the core span vocabulary or rename the new types to 2e. Where
|
| # | Action | Severity |
|---|---|---|
| 1 | Add an ADR covering the two-parser window, the convergence plan, the second coordinate/diagnostic vocabulary, and the rule for what earns a place in the shared PslDiagnosticCode union. |
Required |
| 2 | Rename parse (and ParseResult/ParseDiagnostic) to name the CST output, distinguishing it from parsePslDocument; or, at minimum, document the distinction at the export site. (Operational cost: renames a just-shipped ./syntax export — coordinate with principal-engineer.) |
Recommended |
| 3 | Resolve the Position/Range vs PslPosition/PslSpan duplication: reuse the core vocabulary, or rename the new types to make the LSP convention explicit (LspPosition/LspRange). Do not ship a third unnamed synonym at convergence. |
Recommended |
| 4 | Reconcile BlockDeclaration (node) with parseGenericBlock (producer) — the node name drops the "generic" discriminator the function carries. |
Minor |
| 5 | Decide whether PSL_INVALID_OBJECT_LITERAL (a parse-only grammar feature) belongs in the shared core union or a parser-local one. |
Minor |
Code review — PR #795: fault-tolerant recursive-descent PSL parserPrincipal-engineer pass. Lens: failure modes, operability, blast radius, cost/complexity, constraints-vs-assumptions. SummaryA well-structured, well-tested recursive-descent parser that turns PSL source into the existing green/red tree with a What looks solid
FindingsF01 —
|
| Item | What was fixed | Confirmed on branch | Commit |
|---|---|---|---|
| Q9 — bare top-level identifier routing | A bare non-reserved identifier (oops) now commits a BlockDeclaration + PSL_INVALID_DECLARATION "Expected { to open the oops block"; a stray Invalid char (§) still reports PSL_UNSUPPORTED_TOP_LEVEL_BLOCK. |
Yes — parseGenericBlock lines 561–582; tests parse-diagnostics.test.ts lines 49–96. |
e9b0de4 |
| Q10/Q11 — diagnostic span polish | Missing-brace anchors a zero-width span after the name via markAfterLastToken; reserved-namespace-name underlines the name, not the keyword (mark(1)). |
Yes — markAfterLastToken lines 117–119, parseDeclaration line 492; tests lines 116–129, 301–313. (See F05 for the trailing-trivia gap in the after-name anchor.) |
e9b0de4 |
Q13 — types vs type grammar |
types { is the types block; type Name { the composite type; bare type/type { reports "Expected a name after type". Parser, oracle fixture, tests agree. |
Yes — parseCompositeType/parseTypesBlock lines 589–598, RESERVED_BLOCK_KEYWORDS lines 451–457; fixture buildTypesBlock corrected type→types in ast.test.ts; tests lines 415–459. |
875a937, ca8e760 |
| Refactor — block machinery | parseReservedBlock+finishReservedHeader collapsed into one parseBlock; Cursor.mark generalised to a lookahead index. Snapshot diff empty (tests still green). |
Yes — single parseBlock lines 512–541; mark(lookahead) lines 92–110. |
f9302ef, edc400c |
Acceptance-criteria verification
| AC | Verdict | Detail |
|---|---|---|
| AC1 — Oracle conformance (deep-equality up to Identifier-wrapping) | WEAK | No test feeds parse() output into a deep-equality check against a hand-built oracle fixture (grep for toEqual/toStrictEqual on a parse(...) tree returns nothing). parse tree shape is pinned by author-written printTree inline snapshots; the hand-built fixtures in ast.test.ts exercise the AST accessors, never parse. Behaviour is well-pinned, but the specific "oracle deep-equality" property AC1 names is not what the suite asserts. See F03. |
| AC2 — Lossless round-trip (incl. malformed + unicode) | PASS | greenText(green) === source asserted across well-formed, malformed, CRLF, and unicode cases (parse-document.test.ts lines 72, 471–495; every diagnostic test re-asserts it). Independently re-verified by probe against the built parser for lone-\r, BOM, unterminated-string, and empty source — all round-trip. |
| AC3 — Never throws; per-member recovery | FAIL | Per-member recovery is real and tested (one diagnostic per bad construct, later declarations still parsed — e.g. parse-document.test.ts lines 588–614). But "never throws" is false: a depth probe shows parse throws RangeError at ~5k nested object literals and ~20k nested namespaces. The 'never throws on adversarial input' test (lines 653–657) only covers shallow garbage. See F01. |
| AC4 — Diagnostic fidelity (code + verbatim message + LSP range) | PASS | Every syntactic diagnostic test asserts all three: .code, exact .message, and the range via the highlight underline snapshot (parse-diagnostics.test.ts throughout; parse-leaf.test.ts lines 404–473). The verbatim-parity claim against parsePslDocument is taken on the PR's word for the reconciled set (spec Q-C) but the asserted messages are concrete. |
AC5 — SourceFile mapping |
PASS | 0-based positions, CRLF (\r on preceding line), out-of-range clamp both directions, and positionAt/offsetAt inverse over every offset all asserted (source-file.test.ts lines 5–86). Code matches (binary search, clamp helper). |
AC6 — Public surface (./syntax source + built dist) |
PASS | Source exports/syntax.ts re-exports parse, SourceFile, ParseDiagnostic, ParseResult, Position, Range. Built dist/syntax.d.mts (after pnpm build) contains all six. parse/SourceFile are absent from the root . export — ./syntax-only as required. |
| AC7 — Grammar correction (Q13) | PASS | parseTypesBlock matches types, parseCompositeType matches type; bare type/type { reports "Expected a name after type". Parser (lines 589–598), oracle fixture (buildTypesBlock corrected), and tests (parse-diagnostics.test.ts lines 415–459) agree. |
| AC8 — Malformed-header routing (Q9/Q10/Q11) | PASS | PSL_INVALID_DECLARATION for bare identifiers and malformed reserved headers; PSL_UNSUPPORTED_TOP_LEVEL_BLOCK for stray Invalid chars; after-the-name zero-width span; name-anchored namespace diagnostic — all asserted with code + message + highlight (parse-diagnostics.test.ts lines 49–146, 285–459). (F05 notes an untested trailing-trivia edge in the after-name anchor; the pinned cases pass.) |
| AC9 — Contextual keywords + unicode | PASS | model usable as model/field/enum-value name (parse-document.test.ts lines 498–535); unicode identifiers round-trip and are queryable (lines 482–495). Both assert behaviour, not just round-trip. |
| AC10 — Package checks green | PASS (with precondition) | typecheck, test (357), lint, lint:deps, build all pass after framework-components is built. A bare pnpm --filter @prisma-next/psl-parser test against the committed dist fails 56 tests on a stale upstream typing — a build-ordering artifact, not a code defect. See F02. The one lint "info" (a bare as Token) is in unchanged tokenizer.ts, not introduced here. |
Summary count
| Result | Count | ACs |
|---|---|---|
| PASS | 7 | AC2, AC4, AC5, AC6, AC7, AC8, AC9 |
| FAIL | 1 | AC3 (throws on deep nesting) |
| WEAK | 1 | AC1 (snapshot-pinned, not oracle deep-equality) |
| NOT VERIFIED | 0 | — |
| PASS-with-precondition | 1 | AC10 (green only in a built workspace) |
Conflict candidates for the architect pass
- F03 / AC1: whether the hand-built oracle should remain authoritative against
parse(deep-equality) or whetherprintTreesnapshots are the intended conformance mechanism — that is a typology/conceptual-integrity call. - F07: whether a string/number value-decoder belongs on the CST AST node at all, vs a separate semantic layer.
|
I addressed all of the reviews except: F01 - technically correctly flagged, but that happens only on very large synthetic input (1000s levels of nesting of object literals, etc). I don't think it ever occurs in actual PSL document and PSL is always trusted input, so DOS attack is also not possible. Recovery from this is possible but not exactly trivial, so I don't think it is worth it. |
Introduce a pure value object that owns offset<->LSP-position conversion: precompute line starts in one pass, answer positionAt by binary search, invert via offsetAt, clamp out-of-range in both directions, and place the CR of a CRLF pair on the preceding line with absolute offsets into the un-normalized source. Signed-off-by: Serhii Tatarintsev <[email protected]>
Introduce parse.ts with the single-pass token pull (trivia + Invalid + Eof, parallel absolute offsets), a non-emitting peekKind lookahead, the trivia-attachment discipline (trivia flushed into the enclosing open node so each child spans first->last significant token), a diagnostic sink producing LSP ranges via SourceFile, and a recoverToSyncPoint primitive. Build the leaf grammar over it: expressions, type annotations (space/namespace qualification, inline constructor, list and optional suffixes, over-qualification -> PSL_INVALID_QUALIFIED_TYPE), attributes (PSL_INVALID_ATTRIBUTE_SYNTAX on malformed), and balanced raw-token capture for unrecognised object-literal arguments. Diagnostic messages are provisional; code, range and recovery are final. Tests assert whole-tree deep-equality against the hand-built fixtures and lossless round-trip. Signed-off-by: Serhii Tatarintsev <[email protected]>
Deep-equality fixtures for every declaration kind (model, enum, namespace, composite type, types block, generic block), a representative multi-construct schema, lossless round-trip cases (object-literal arg, CRLF), and one minimal malformed input per declaration-level diagnostic. Signed-off-by: Serhii Tatarintsev <[email protected]>
Extend the fault-tolerant substrate with the top-level declaration grammar (model / enum / namespace / composite type / types block / generic block) and members (field / enum value / named type / key-value), reusing the existing leaf parsers, cursor, diagnostic sink, and recovery. Ship parse(source): ParseResult returning a DocumentAst-wrapped tree, the syntactic diagnostics, and the SourceFile; the parser never throws. Land the seven declaration-level diagnostics with skip-to-sync-point recovery so a complete tree is always returned. Signed-off-by: Serhii Tatarintsev <[email protected]>
Match each ParseDiagnostic.message to the existing regex parser's verbatim wording where an equivalent error condition exists (namespace nesting, reserved/duplicate blocks, unterminated blocks, unsupported top-level constructs, malformed members), interpolating the offending name/token. Genuinely new syntactic errors with no equivalent (qualified-type over-qualification, missing attribute name, generic block entry) keep clear implementer wording. A stray Invalid character reuses the existing PSL_UNSUPPORTED_TOP_LEVEL_BLOCK/member codes, so no new diagnostic code is minted. Codes, ranges, and recovery are unchanged. Tests assert the verbatim message plus an offset that maps onto the offending span. Signed-off-by: Serhii Tatarintsev <[email protected]>
Surface parse, SourceFile, and the ParseDiagnostic/ParseResult/Position/Range types from the ./syntax export barrel so consumers can import the recursive-descent parser. The package-root . entrypoint is intentionally left untouched (deferred to the parser-replacement follow-up). Signed-off-by: Serhii Tatarintsev <[email protected]>
…unter
The parser substrate eagerly pulled the entire token stream into a #tokens
array and kept a parallel #offsets array. The grammar only needs bounded
lookahead (already provided by Tokenizer.peek) and never backtracks, so the
arrays cost an O(n) pass and O(n) memory for nothing.
Replace both with a Tokenizer held by the Cursor and a single running #offset
counter (offset of the next un-consumed raw token, advanced by token.text.length
on each consume). Diagnostics now capture a DiagnosticMark { offset, length } via
the reshaped mark() (formerly currentSignificantIndex) computed from #offset plus
the summed lengths of the few peeked trivia tokens up to the offending token, so
markers stay valid after the cursor advances past them.
Behavior-preserving: green tree, trivia attachment, recovery, and every
diagnostic code/message/range are unchanged; all 309 package tests pass. The
pullTokens-array test is rewritten to assert offset behavior observably (a
diagnostic range mapped through interspersed trivia).
Signed-off-by: Serhii Tatarintsev <[email protected]>
…o Cursor class The cursor is a per-parse() scratch object with a single implementation, hand-constructed and not on the public barrel, so the interface+factory indirection added no value. Export the Cursor class directly, retype the grammar-function parameters to it, and construct it with new Cursor(source). Behavior-preserving: same tree, same diagnostics, public ./syntax barrel unchanged. Signed-off-by: Serhii Tatarintsev <[email protected]>
The Cursor class had a private #flushTrivia() doing the work and a public flushTrivia() that only forwarded to it. Move the loop body into the public method, delete the private one, and point the internal callers (startNode, bump, captureBalancedBraces) at the public method. The public method stays because parseDocument (a free function) calls it to flush trailing trivia before finishNode, and cannot reach a private member. Behavior-preserving: same flush logic, call sites, tree, and diagnostics. Signed-off-by: Serhii Tatarintsev <[email protected]>
…d ?? alternatives Each alternative parser now returns GreenNode | undefined, owns its discriminating peekKind/peekToken lookahead, and is a no-op on non-match (returns undefined having called only peek* — no startNode, bump, or flushTrivia). The forward-only cursor is therefore never left half-consumed by a rejected alternative, so alternatives compose with ??: parseModel ?? parseEnum ?? parseNamespace ?? parseTypesBlock ?? parseCompositeType ?? parseGenericBlock, and the analogous member chains. Recovery fallbacks (parseUnsupportedTopLevel, invalidMember) append raw tokens to the open parent rather than returning a child node, so they run via the if (!node) tail, not as a ?? arm. parseGenericBlock excludes the reserved keywords model/enum/namespace/ type so a malformed reserved block still falls through to the unsupported-declaration recovery, preserving existing behaviour byte-for-byte. The @@-vs-@ split is preserved: parseBlockAttribute matches @@ (ModelAttribute) only; single-@ attributes stay inside parseField/parseEnumValue. Signed-off-by: Serhii Tatarintsev <[email protected]>
The ordered-alternative dispatch rests on every alternative being a no-op on non-match. Assert this observationally with the existing cursor API: over input each parser should reject, call it, expect undefined, then drain the remaining stream and require it to reproduce the source byte-for-byte with no diagnostic emitted — proving nothing was consumed or mutated. No new cursor surface is introduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
… consts The diagnostic(code: PslDiagnosticCode, ...) parameter already type-checks inline literals against the canonical union, so the nine local code consts added indirection with no type-safety or DRY benefit. Inline the literal at each call site to match the house style already used in parser.ts and the tests. Same code values, identical behavior. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add the PSL_INVALID_DECLARATION member additively to the canonical PslDiagnosticCode union. It marks a reserved declaration keyword (model/enum/namespace/type) that committed its kind on the keyword alone but is missing its name and/or opening brace. Scope-note: this is the single permitted cross-package edit for the recursive-descent parser keyword-commit change. The addition is purely additive; no exhaustive switch/never consumer of PslDiagnosticCode exists in the workspace, so no consumer edits are required. Signed-off-by: Serhii Tatarintsev <[email protected]>
…nostics
A reserved declaration keyword (model/enum/namespace/type) now commits
the declaration kind on the keyword alone, so a missing name and/or
opening brace yields a typed node plus a keyword-anchored
PSL_INVALID_DECLARATION rather than PSL_UNSUPPORTED_TOP_LEVEL_BLOCK.
- Retarget the nameless `model {` case from unsupported to a
ModelDeclaration + PSL_INVALID_DECLARATION (missing-name message).
- Add coverage for each reserved keyword across missing-name,
missing-brace, and both, asserting node kind, code, message, the
keyword-anchored range, continued parsing, and lossless round-trip;
plus `type Ident` (no brace) -> composite type, bare `type` ->
types block, and a bare non-reserved identifier still -> unsupported.
- Update the no-op-on-non-match suite to feed non-matching keywords
(the keyword is now the sole discriminator) and replace the removed
parseCompositeType/parseTypesBlock arms with parseTypeDeclaration.
Signed-off-by: Serhii Tatarintsev <[email protected]>
… alone
model/enum/namespace/type now discriminate on the reserved keyword
itself rather than on a fully well-formed `kw Name {` header. A keyword
commits the declaration kind; a missing name and/or opening brace
produces a best-effort typed node plus a single keyword-anchored
PSL_INVALID_DECLARATION (first missing piece wins: missing name takes
precedence over missing brace), then recovers to the next sync point.
Parsing continues and the green tree round-trips losslessly.
- Replace the separate parseTypesBlock/parseCompositeType `??` arms with
one parseTypeDeclaration that commits `type` then disambiguates on the
next significant token (Ident -> composite type, else types block),
preserving the document-top-level and single-block constraints.
- Keep parseGenericBlock brace-discriminated and reserved-keyword-
excluded, so a bare non-reserved identifier with no brace stays an
unsupported top-level declaration.
- Preserve the no-consume-on-non-match invariant: each reserved parser
peeks via keywordIs and returns undefined untouched when its keyword
does not match, committing only after the match.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Remove the document-scoped "only one top-level `types` block" uniqueness check from the recursive-descent parser. It needs whole-document state and leans semantic, so it is deferred under the parser`s syntactic-only scope and will be reintroduced later. A second top-level `types` block now parses to a second TypesBlock node with no diagnostic. The DocumentState/state plumbing existed solely to track that uniqueness, so it is removed too. The namespace placement check and the malformed types-block member diagnostic both remain. Signed-off-by: Serhii Tatarintsev <[email protected]>
…ive parsers Restructure parseExpression into one peek-guarded function per expression alternative, each returning GreenNode | undefined and a no-op on non-match (no startNode/bump on the reject path), coalesced with ??. Add matching guards to parseArrayLiteral (LBracket) and parseFunctionCall (Ident+LParen) and have them return GreenNode | undefined. The Ident-leading ordering (functionCall -> boolean -> identifier) is preserved, so true( stays a function call named true. Behavior-preserving: same green tree, diagnostics, and recovery. Adds no-op-on-non-match coverage for each new alternative. Signed-off-by: Serhii Tatarintsev <[email protected]>
…bers parseKeyValue and parseNamedType treated the "=" as optional, silently accepting a member missing its separator (provider "x", bare provider, UserId Int) with no diagnostic. Add the else branch that reports the missing "=" anchored on the key/name, continuing best-effort so the trailing value/type still parses. Reuses the existing per-block member codes; round-trip holds and parse never throws. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add ObjectLiteralExpr/ObjectField SyntaxKinds and ObjectLiteralExprAst/ ObjectFieldAst wrappers, wired into the ExpressionAst union and castExpression so object literals are a first-class expression usable as array elements, attribute-arg values, key-value values, and nested object-field values. Export both wrappers from the ./syntax barrel. Extend the canonical PslDiagnosticCode union additively with PSL_INVALID_OBJECT_LITERAL (the one permitted cross-package edit); no exhaustive consumers exist, so no consumer edits are forced. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add parseObjectLiteralExpr/parseObjectField to the parseExpression
alternative chain, discriminated on LBrace. They parse { key: value, ... }
with identifier or string keys, recursive expression values, and
comma-separated entries with an optional trailing comma. Malformed
literals (missing colon, missing value, unterminated {) emit
PSL_INVALID_OBJECT_LITERAL while still producing a best-effort node and
preserving the lossless round-trip; parsing never throws.
Remove captureBalancedBraces and its two call sites: parseArgValue and
parseKeyValue now just call parseExpression, which returns the typed
ObjectLiteralExpr node instead of swallowing the braces as raw tokens.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Hand-built oracle fixtures and accessor tests for ObjectLiteralExprAst (lbrace/rbrace/fields) and ObjectFieldAst (key/colon/value), including a nested literal and a string-key literal that exercises the colon disambiguation. Parse-level tests for well-formed, nested, trailing-comma, and round-trip cases, plus a no-op-on-non-match check, and malformed cases (missing colon, missing value, unterminated) asserting PSL_INVALID_OBJECT_LITERAL with a best-effort node and intact round-trip. Update the existing object-literal argument tests (formerly the captureBalancedBraces consumers) to assert a queryable ObjectLiteralExpr node via fields() rather than bare raw tokens. Signed-off-by: Serhii Tatarintsev <[email protected]>
Update the parse-diagnostics assertions for the Q9/Q10/Q11 behaviour: the bare-identifier test now asserts a committed BlockDeclaration with a missing-brace PSL_INVALID_DECLARATION, the four missing-brace tests carry after-name zero-width spans, and the reserved-namespace-name test underlines the name. Q12: enrich the multi-declaration recovery test with printTree + highlight inline snapshots, delete the now-redundant `datasource` unsupported-declaration test (identical to the `oops` case under Q9), remove all `// REVIEW:` notes, and fix the stray over-indentation around the `model User` case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
…rammar
The types-block keyword is `types` (plural), not `type`; `type` is
composite-type only. Split parseTypeDeclaration into parseCompositeType
(`type Name {`) and parseTypesBlock (`types {`), add `types` to
RESERVED_BLOCK_KEYWORDS, move the namespace-scope check to the `types`
branch, and correct the buildTypesBlock oracle fixture to `Ident "types"`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ord tests
Correct conformance and diagnostic tests that spelled types blocks as
`type {` to the plural `types {`, regenerate the affected printTree and
highlight snapshots, and split the bare-keyword cases: `type` alone is now
a malformed composite (Expected a name after "type"); a new test covers
`types` alone yielding a TypesBlock (Expected "{" to open the "types" block).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add an optional lookahead arg to `mark()`: `mark(0)` is today's behaviour (next significant token), `mark(1)` is the one after, with the offset accumulating every intervening token length, trivia included. This is the one new cursor capability the block-machinery refactor needs to anchor the reserved-namespace-name diagnostic on the name while the cursor still sits on the keyword. Covered by a focused unit test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Collapse `parseReservedBlock` + `finishReservedHeader` into a single `parseBlock(cursor, kind, nameRequired, parseMember)` that reads the keyword off the cursor and takes a `nameRequired` boolean (true for model/enum/namespace/composite, false for the nameless `types` block). The five callers become guard-plus-one-call; `parseNamespace` and `parseTypesBlock` lose their `insideNamespace` parameter. `onHeader`/inline namespace-context diagnostics are eliminated: the three namespace-context checks (recursive namespace, top-level-only `types`, reserved namespace name) move into `parseDeclaration`, which already owns the context and sits on the keyword pre-dispatch. The exact current precedence is preserved (inside a namespace a nested `namespace` reports recursive, never reserved-name) and the spans are unchanged: recursive/types stay keyword-anchored via `mark()`, the reserved-name check stays name-anchored via the new `mark(1)`. Behaviour-preserving: all 353 tests pass with no snapshot regeneration. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Trim or drop doc-comments that restated the code: mark/markAfterLastToken, parseBlock, parseGenericBlock, parseTypesBlock, and remove the self-evident parseCompositeType doc-comment plus the inline `// keyword` markers after cursor.bump(). The stale namespace-check sentence on parseTypesBlock is dropped (that check now lives in parseDeclaration). Comments only — no behaviour or snapshot change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Add tests pinning that PSL has no reserved keywords: `model` parses as a model name, a field name, and (with `enum`) as enum values, each zero- diagnostic and round-tripping. Add a unicode-identifier test (CJK model name, Cyrillic + accented-Latin field names) asserting lossless round-trip across multi-byte code points. Both pass against the existing parser. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
…tifier-only
A missing colon inside an object literal swallowed the next field's key as the current field's value, orphaning that field's colon, leaving the object unterminated, and desyncing brace matching enough to corrupt the enclosing block (one missing colon -> four diagnostics). The field loop now re-enters on a following identifier key and the missing-colon branch no longer consumes the next key as a value, so `{ a b: 1 }` recovers like `{ a, b: 1 }` (one diagnostic, both fields intact). The diagnostic now anchors on the key it names.
Also remove string-literal object keys: PSL has no object-literal construct (the regex parser only modeled named attribute arguments with bare-identifier names), so a string in key position is flagged "Object literal keys must be identifiers" while still consumed for clean recovery. Disambiguation treats only identifiers as keys; a string after a missing colon is a value.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…key AST surface
An object literal with two fields and no comma between them ({ a: 1 b: 2 }) parsed with no diagnostic; it now reports "Expected \",\" between object-literal fields". As a result { a b: 1 } reports both its missing colon and the missing comma.
String literals are no longer valid object keys, so ObjectFieldAst.key() is narrowed from IdentifierAst | StringLiteralExprAst | undefined to IdentifierAst | undefined and the hand-built string-key fixture is removed. The green tree is unaffected — a malformed string key is still consumed for round-trip; key() returns undefined for it.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add an exported, escape-aware `isTerminatedStringLiteral` predicate to the tokenizer (the scanner still emits the same `StringLiteral` token for unterminated input, so callers re-scan with the scanner's `\\`-skips-next escape rule). Mint the additive `PSL_UNTERMINATED_STRING` diagnostic code on the `PslDiagnosticCode` union. `parseStringLiteralExpr` now consumes the token unchanged (lossless round-trip preserved) and reports the new code on the token's span when the literal lacks a non-escaped closing quote. Also pins the missing-brace trailing-trivia anchor (F05): the caret lands immediately after the last significant token, not past trailing whitespace, and pins the known newline-insensitive attribute attachment (F06). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Add a comment-only clarification at the `BlockDeclaration` entry noting it is
the generic/extension block node (the `kw [name] { key = value }` form), the
node-side counterpart of `parseGenericBlock`, deliberately distinct from the
reserved `model`/`enum`/`namespace`/`type`/`types` declarations. No identifier
renames.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…claration Aligns the generic-block node name with its parseGenericBlock producer (review A4); behaviour-preserving. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
…g-backslash parity check The closing quote of a string literal is unescaped iff an even number of backslashes immediately precede it, so termination can be decided by counting the trailing backslash run rather than re-scanning the whole literal. Behaviour-equivalent (the predicate tests are unchanged and green); the doc comment now spells out the parity reasoning with worked examples. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Replace the single regex-replace decoder in StringLiteralExprAst.value() with an explicit scan so fixed-width hex lookahead is precise. Adds \xHH (2 hex) and \uHHHH (4 hex) -> String.fromCharCode, keeping the existing \n \r \t \" \\ escapes. Malformed \x/\u (too few hex digits or non-hex) are emitted literally and scanning continues. Green-tree text is unchanged; this is a value()-only change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Add a word-bounded scanKeywordNumber matcher ahead of scanIdent so the exact words NaN, Infinity, and -Infinity become NumberLiteral tokens. They flow through parseNumberLiteralExpr into a NumberLiteralExpr node whose value() (Number(text)) yields NaN/Infinity/-Infinity unchanged. Identifier-continued forms (Infinityx, NaNxyz) stay Idents. Intended consequence: NaN and Infinity are now globally numeric literals and can no longer be used as identifiers. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
… the CST parser (#849) ## Linked issue Refs [TML-2893](https://linear.app/prisma-company/issue/TML-2893) — the PSL-parser replacement effort. The fault-tolerant CST parser itself already landed in [#795](#795); **this PR fills in the parser functionality that was still missing**, extending the existing CST parser with qualified names, single-quoted strings, and enum-block parsing. ## At a glance The CST parser already parsed bare names; this PR teaches it the **qualified** forms every downstream consumer needs — parsed as one `QualifiedName` node: ```prisma model Profile { id Int // cross-space + namespace-qualified type reference — now a single QualifiedName user supabase:auth.User @relation(fields: [userId], references: [id]) // namespace-qualified constructor type embedding pgvector.Vector(1536) } ``` Before this PR these qualified positions were handled by ad-hoc bounded-lookahead patches; now `parseQualifiedName` produces a uniform `QualifiedNameAst` (`[space ':']? Ident ('.' Ident)*`) wherever a qualified name can appear — type references, constructor callees, function-call callees, and `@@`-attribute names. ## Decision This PR **extends the existing fault-tolerant CST parser** with the functionality it was missing, leaving the legacy `parsePslDocument` untouched: 1. **A unified `QualifiedName` CST node + `parseQualifiedName`.** One parser and one AST node (`QualifiedNameAst`) for every qualified position, replacing the previous per-site lookahead handling. Emits `PSL_INVALID_QUALIFIED_NAME` for malformed over-qualified names. 2. **Single-quoted string literals.** The tokenizer now scans `'…'` as well as `"…"`, and `isTerminatedStringLiteral` handles both quote styles. 3. **Enum routed through generic blocks.** The dedicated `parseEnum` path and its `EnumDeclarationAst` / `EnumValueDeclarationAst` nodes are gone; an `enum` block now parses as a `GenericBlockDeclarationAst` (which also gained `@@`-attribute support inside generic-block members). 4. **Quoted object-literal keys.** Object fields accept string-literal keys (`{ "key": value }`), not just identifiers. The CST parser core (`parse`, `SourceFile`, the red/green tree) is **not** introduced here — it predates this branch. This PR is purely parser-functionality: the legacy `parsePslDocument` and its consumers (the SQL/Mongo interpreters) are untouched. ## How it fits together 1. **`QualifiedName` becomes a first-class node** — `syntax/ast/qualified-name.ts` adds `QualifiedNameAst` with `space` / `namespace` / `identifier` / `path` / `isOverQualified` accessors; `syntax-kind.ts` adds the `QualifiedName` kind; `exports/syntax.ts` exposes it. 2. **The parser emits it everywhere a qualified name can appear** — `parse.ts` adds `parseQualifiedName` / `parseQualifiedSegments` and rewires type-annotation, function-call, and `@@`-attribute parsing through it, retiring the bounded-lookahead patch. 3. **AST accessors return the new node** — `FieldAttributeAst.name()`, `ModelAttributeAst.name()`, and `TypeAnnotationAst.name()` now return `QualifiedNameAst`; `FunctionCallAst` gains `name()` / `path()`; `ObjectFieldAst` gains string-literal key support. 4. **Enum folds into generic blocks** — `parseEnum` and the enum AST classes are removed; `GenericBlockDeclarationAst` gains `attributes()` so `enum` (and other extension blocks) parse generically. 5. **One additive diagnostic code** — `PSL_INVALID_QUALIFIED_NAME` is added to `framework-components`'s `PslDiagnosticCode` (alongside, not replacing, the existing `PSL_INVALID_QUALIFIED_TYPE` the legacy parser uses). ## What lands in this PR | Area | What it adds / changes | | --- | --- | | `syntax/ast/qualified-name.ts` (new) | `QualifiedNameAst` — the unified qualified-name node | | `parse.ts` | `parseQualifiedName` + rewiring of type/attribute/call parsing; removal of `parseEnum`; string-literal object keys | | `tokenizer.ts` | single-quoted string scanning | | `syntax/ast/{attributes,expressions,type-annotation,declarations,identifier}.ts` | accessors return `QualifiedNameAst`; `GenericBlockDeclarationAst.attributes()`; enum AST classes removed | | `syntax/syntax-kind.ts`, `exports/syntax.ts` | `QualifiedName` kind; export of `QualifiedNameAst` / `printSyntax` | | `framework-components/.../psl-extension-block.ts` | additive `PSL_INVALID_QUALIFIED_NAME` code | | `test/parse-*.test.ts`, `syntax/ast.test.ts` | snapshots + assertions for the new shapes | | legacy `parser.ts` / `parsePslDocument` | **untouched** — still the interpreters' parser | ## Reviewer notes - **The parser pre-exists; this PR is additive functionality.** The diff is against a base that already contains the CST parser (#795), so `parse.ts` / `tokenizer.ts` / `syntax/` show as *modified*, not *added*. The only new file is `qualified-name.ts`. - **Nothing downstream is migrated.** `parsePslDocument` and its consumers (SQL/Mongo interpreters) are untouched; this PR only changes the parser surface. - **Enum support changed shape, not capability.** `enum` no longer has a dedicated AST node; it parses as a `GenericBlockDeclarationAst`. Tests assert the generic-block shape. - **One additive diagnostic code only.** `PSL_INVALID_QUALIFIED_NAME` is added (alongside the existing `PSL_INVALID_QUALIFIED_TYPE`); no other diagnostic codes change. - **Pre-existing, out of scope:** a bare-`as` lint info at `tokenizer.ts:69` (info-level on the ratchet, not introduced here). ## Compatibility / migration / risk Additive to the parser surface: the new `QualifiedNameAst` and the qualified-name handling are new; `parsePslDocument` and the `./parser` entry are unchanged, so no interpreter is migrated and contract output is identical to base. The one behavioral shape change is internal to the CST (enum → generic block), exercised by the parser tests; no contract consumer observes it on this branch. ## Verification - `pnpm --filter @prisma-next/psl-parser build` — green. - `pnpm --filter @prisma-next/psl-parser test` — CST `parse-*` / `syntax/ast` suites + the retained legacy `parser` suites. - `pnpm --filter @prisma-next/sql-contract-psl typecheck`, `@prisma-next/mongo-contract-psl typecheck` — green, unchanged (still on the legacy parser). - `pnpm build` (full), `pnpm typecheck` (full workspace), `pnpm lint:deps` — green. ## Alternatives considered - **Keep the per-site bounded-lookahead handling for qualified names.** Rejected: every qualified position (type ref, constructor callee, call callee, `@@`-attribute) re-implemented its own lookahead. A single `QualifiedName` node + `parseQualifiedName` collapses them to one uniform shape. - **Keep a dedicated `enum` AST node.** Rejected: enum is being reframed as an extension/generic block elsewhere in the effort; routing it through `GenericBlockDeclarationAst` removes a parallel code path rather than maintaining two. ## Checklist - [x] Commits are signed off (DCO). - [x] Read CONTRIBUTING.md. - [x] Tests updated / added. - [x] Title follows the `$TICKET_ID: <title>` convention. --------- Signed-off-by: Serhii Tatarintsev <[email protected]>
#850) ## What Delivers the **PSL formatter** for Prisma Next, end to end: a deterministic pretty-printer engine plus the `prisma format` CLI command that runs it. **1. Engine** — `@prisma-next/psl-parser/format`: ```ts import { format, type FormatOptions, PslFormatError } from '@prisma-next/psl-parser/format'; format(source); // canonical PSL, LF, 2-space indent format(source, { indent: 'tab', newline: 'CRLF' }); ``` `format(source, options?) -> string` parses via the CST and re-emits canonical PSL. Pure string→string: no file I/O, no node built-ins, no `@prisma-next/config` dependency. **2. CLI** — `prisma format`: Reads `prisma-next.config.ts`; when the contract source is PSL (`config.contract.source.sourceFormat === 'psl'`), formats `config.contract.source.inputs[0]` **in place**. Non-PSL or absent sources are left untouched. Indent/newline come from an optional `formatter` config section; the system newline (`os.EOL`) is resolved at the CLI. Closes TML-2928 (the whole issue — both the engine and the CLI). ## Why Prisma Next authors hand-write and machine-emit PSL, but there was no canonical formatter for the new authoring stack. The new red/green CST preserves all trivia (whitespace, comments, newlines) as tokens, making it the right substrate for a lossless pretty-printer: re-emit a normalized, deterministic layout while retaining comments and the full token stream. ## Engine behaviour - **CST-based** (`parse` + typed AST wrappers); does not touch the legacy `parsePslDocument`. - **`indent`**: positive integer (spaces) or `'tab'`; default 2. - **`newline`**: `'LF'` (default) or `'CRLF'`, applied uniformly. - **Per-block alignment**: field-name→type column and trailing attributes aligned per block. - **Trivia preservation**: leading / trailing / dangling comments and author blank lines (collapsed to one, never adjacent to a brace). - **Blank line before block attributes**: one blank line always separates the last field from the first `@@` attribute (house style). - **Idempotence**: `format(format(x)) === format(x)`. - **Refuses** input that carries parse diagnostics (`PslFormatError`) rather than emitting best-effort output. ## Key decisions - **Engine ships inside `@prisma-next/psl-parser`** via a `./format` subpath — no separate package, no new runtime dependency. Engine option validation is hand-rolled (the option space is two enum-ish fields; a schema lib would have violated the package's no-new-deps constraint). The `formatter` **config** section, by contrast, is arktype-validated — `@prisma-next/config` already depends on arktype. - **`os.EOL` resolution lives only in the CLI.** The engine never reads `os`; the `prisma format` command resolves `config.formatter.newline ?? (os.EOL === '\r\n' ? 'CRLF' : 'LF')` and passes an explicit `newline` into the engine. - **PSL-ness is a structured discriminator, not a filename heuristic.** `ContractSourceProvider` carries an optional `sourceFormat: 'psl' | 'typescript'`; every first-party provider declares it (`prismaContract`/`mongoContract` → `'psl'`; the `typescript*`/`empty` helpers → `'typescript'`). The command formats only `'psl'` sources; anything else (incl. absent) is left untouched. - **Inline `//` comments are a hard break barrier.** `field Type //comment` followed by a continuation `@attribute` preserves the break rather than hoisting the attribute past the comment — matching Prettier, Biome, and rustfmt (a `//` comment runs to end-of-line; joining a later token onto its line is both a correctness and an idempotence hazard). ## Tests — side-by-side fixture pairs The formatter's integration oracle is a set of hand-authored **side-by-side pairs** under `test/format/fixtures/<case>/{input,expected}.prisma` — open a pair to *see* exactly what the formatter does. The test asserts `format(input) === expected`, idempotence, and that formatting actually happened. Cases cover alignment, comment preservation, the inline-comment hard break, blank-line handling, block-attribute spacing, enum/generic blocks, and the namespaced-type round-trip (`space:ns.Type`). The CLI is covered by an e2e journey (`format.e2e.test.ts`) proving format-in-place, leave-untouched, and refuse-on-unparseable, each asserting on-disk file state. ## Validation - `pnpm lint:deps` — no violations (engine takes no node built-ins; the CLI→engine edge is layering-safe). - `@prisma-next/psl-parser` — 529 tests, no type errors; fixture pairs produce no snapshot churn. - `@prisma-next/config` — 29 tests (discriminator + `formatter` section). - `@prisma-next/cli` — `prisma format` operation tests + the e2e journey green. (Note: ~9 pre-existing flakes in `version.test.ts` / `removed-verb-redirects.test.ts` are cold-boot subprocess-timeout fragility, unrelated to this work.) ## Base Targets `main`. The formatter consumes the fault-tolerant CST parser surface, which landed on `main` via #795 and #849; this branch was originally stacked on the pre-merge `psl-cst-parser` branch and has been rebased onto `main` now that the CST work is merged. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * Added PSL formatter to canonically format Prisma schema language code. * Added `format` CLI command with `--config` option to format PSL files in place. * Added formatter configuration options for indentation and line ending styles (tabs vs. spaces, LF vs. CRLF). * Format command only processes PSL sources; TypeScript contracts are skipped. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Serhii Tatarintsev <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
What
Adds a fault-tolerant recursive-descent parser to
@prisma-next/psl-parserthat turns PSL source into the existing green/red concrete-syntax tree, plus aSourceFilethat owns offset↔position mapping. New public surface under the./syntaxentrypoint:The package already shipped a
Tokenizerand the full green/red tree + AST wrappers, but nothing connected source text to a tree — the tree layer was only reachable from hand-built fixtures. This wires that gap. The existing regex-basedparsePslDocumentis left untouched; replacing it is a follow-up.Why
A concrete-syntax-tree parser is the foundation a formatter / LSP / refactor tooling needs: it's lossless (round-trips byte-for-byte, trivia included), fault-tolerant (always returns a tree, reports every syntactic error, never throws), and position-free (tokens/nodes carry no offsets —
SourceFileis the single home for offset↔line/column).How it's built
SourceFile(src/source-file.ts) — precomputes line starts, answerspositionAt/offsetAtby binary search, 0-based LSP positions, CRLF-aware (the\rof a\r\npair belongs to the preceding line; offsets stay absolute into the un-normalized source), clamps out-of-range both directions.src/parse.ts) — drives theTokenizerlazily via itsnext()/peek()interface (bounded lookahead only; trivia +Invalid+Eofflow through), tracks token offsets with a single running counter, exposes a non-emittingpeekKindlookahead, the trivia-attachment discipline (trivia flushed into the enclosing open node; each child node spans first→last significant token), a diagnostic sink producing LSPranges viaSourceFile, and arecoverToSyncPointprimitive (skip to nextNewline/ enclosing}/Eof). Leaf parsers: expressions, type annotations, attributes.parse()— model / enum / namespace / composite type (type Name {) / types block (type {) / generic block (kw [name] {key=value), plus field / enum-value / named-type / key-value members. Wraps the green root as aDocumentAst. Recovery is per-member: one bad line emits one diagnostic and parsing continues.PslDiagnosticCodeunion (syntactic codes only). Messages are reconciled verbatim againstparsePslDocumentwherever an equivalent condition exists (FR8b).Reviewer notes (design decisions)
Identifier-node wrapping for name references. The hand-built oracle is internally inconsistent about a name's leaf shape (some fixtures put a bareIdentunderTypeAnnotation, others wrap it in anIdentifiernode). The wrapped form is the one the AST contract requires —TypeAnnotationAst.name()/namespaceName()/spaceName()resolve names throughIdentifiernode children, so a bare-Identannotation is accessor-broken.parsetherefore emits the wrapped shape everywhere a name appears; keywords/separators stay bare tokens. The frozen oracle fixtures are untouched; the spec's AC1 was amended to read deep-equality up to this documented leaf-canonicalization. (Decision recorded in the project spec, Open Question Q4.)PslDiagnosticCodeminted. A strayInvalidcharacter reusesPSL_UNSUPPORTED_TOP_LEVEL_BLOCK(same code + wordingparsePslDocumentroutes unrecognized top-level content to) — a clean fit, so the canonical union is unchanged and every consumer's exhaustiveness check stays valid.PSL_INVALID_QUALIFIED_TYPE,PSL_INVALID_ATTRIBUTE_SYNTAX,PSL_INVALID_EXTENSION_BLOCK_MEMBER) —parsePslDocumenthas no token-anchored equivalent message for these conditions (e.g. it routesa:b:cto a model-member error, never a qualified-type error), so implementer wording is correct per FR8b.Isolation / scope
.entrypoint are untouched.src/parser.ts(parsePslDocument) and the package-root.export show no changes vsmain; the new surface is exported from./syntaxonly (root re-export deferred to the parser-replacement follow-up).src/tokenizer.tsgains one exported predicate (isTerminatedStringLiteral) for the unterminated-string diagnostic, with no change to its scanning;src/syntax/**gains theObjectLiteralExpr/ObjectFieldnode kinds + AST wrappers (Q7) and a clarifying comment, and the test oracle was corrected (buildTypesBlocktype→types, Q13) with the dead string-key fixture removed; and the sharedPslDiagnosticCodeunion gains three syntactic members —PSL_INVALID_DECLARATION,PSL_INVALID_OBJECT_LITERAL,PSL_UNTERMINATED_STRING(additive; none removed or repurposed).Non-goals / follow-ups
parsefrom the package root, and retiring/repointingparsePslDocumentconsumers — the parser-replacement follow-up.@attron the next line attaches to the prior field — a divergence fromparsePslDocument's line semantics; harmless here, revisit at consumer repointing).@prisma-next/adapter-sqlite/adapter-postgres/mongo-orm(a missingtypescondition onadapter-sqlite's own./adapterexport) — present onmain, out of scope here.Validation
Package gates green:
typecheck,test(374 passed),lint,lint:deps, andbuild(the./syntaxdistexportsparse/SourceFile/ParseDiagnostic/ParseResult/Position/Range). CI-ordering precondition: the green test run requires@prisma-next/framework-componentsto be built first — it owns thePslDiagnosticCodeunion, and a bare package-only run against a stale upstreamdistfails to typecheck; Turbo'sdependsOncovers this in CI. Conformance is snapshot-pinned —printTreefor tree shape andhighlightfor diagnostic spans (the Q8 mechanism that replaced node-by-nodeGreenNodeBuilderdeep-equality) — alongside lossless round-trips (concatenated token text === source) and every syntactic diagnostic'scode+message+ LSPrange.Post-review updates
Review of this PR surfaced four follow-ups (and one design-cleanup), all landed on this branch. Where these supersede statements above, the note says so. Pinned decisions live in the project spec's "Post-PR review amendments" (Q9–Q13).
oops,datasource) now commits a genericBlockDeclarationand reportsPSL_INVALID_DECLARATION"Expected{to open the<name>block" — it's read as a custom declaration the author hasn't finished, not "unsupported content." A leading token that isn't an identifier (a strayInvalidchar like§) still reportsPSL_UNSUPPORTED_TOP_LEVEL_BLOCK. The§/Invalidrouting is unchanged. (Scope note above is corrected: this PR adds threePslDiagnosticCodemembers overall.){was expected), via a newCursor.markAfterLastToken(). The reserved-namespace-name diagnostic (namespace __unspecified__) underlines the name, not the keyword.typesvstype(Q13). The original work misread the grammar: it treatedtype {(singular) as a types block. The authority — the existingparsePslDocument— is unambiguous:types {(plural keyword, no name) is the types block;type Name {is a composite type. Corrected across the parser, the spec, the hand-built oracle fixture, and the tests.typesis now a reserved declaration keyword;type {/typealone is a malformed composite type ("Expected a name aftertype").printTree+highlightsnapshots; a redundant test was removed.parseReservedBlock+finishReservedHeadercollapsed into oneparseBlock(cursor, kind, nameRequired, parseMember)(the keyword is read from the cursor), and theonHeaderhook was eliminated by moving the three namespace-context checks into the dispatcher (parseDeclaration), the name-anchored one using a generalisedCursor.mark(lookahead). Three block helpers became two;−24lines onparse.ts; snapshot diff empty.{ a b: 1 }now recovers like{ a, b: 1 }. A missing comma between fields is now flagged (Expected "," between object-literal fields) rather than silently accepted. String-literal object keys are removed: PSL has no object-literal construct (the regex parser only modeled named attribute arguments with bare-identifier names), so a string in key position is flaggedObject literal keys must be identifiers, andObjectFieldAst.key()is narrowed toIdentifierAst | undefined.PSL_UNTERMINATED_STRINGvia an escape-aware tokenizer predicate (the tokenizer's scanning is otherwise unchanged).BlockDeclarationas the generic/extension-block node (no rename — A4).Deferred to the parser-replacement / convergence follow-up (by decision, not in this PR): unbounded recursion on pathological nesting (F01 — clean fix needs a neutral error-node kind); an ADR for the two-parser window, the
Position/Range-vs-PslPosition/PslSpancoordinate duplication, and the rule for shared-union membership (A1); renamingparse/Position/Range(A2/A3 — declined); whetherPSL_INVALID_OBJECT_LITERALbelongs in the shared union (A5); and theStringLiteralExprAst.value()/NumberLiteralExprAst.value()decoders (F07).Scope note (supersedes "Isolation / scope" above): the change is still additive and isolated to
psl-parser—parser.ts,tokenizer.ts, andsrc/syntax/**implementation remain untouched (frozen-diff vsmainempty). The one edit to a previously-frozen artifact is the test oracle fixturebuildTypesBlock(test/syntax/ast.test.ts), correctedtype→typesper Q13 — the freeze had presumed the fixture was correct, and it encoded the grammar bug. No newPslDiagnosticCodemember was added at any point.Validation (current): package gates green —
typecheck,test(357 passed),lint,lint:deps,build. Coverage added since the original cut includes keyword-as-identifier (PSL keywords are contextual, not reserved —modelis usable as a model/field/enum-value name) and unicode identifiers (lossless round-trip).