Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

feat(psl-parser): fault-tolerant recursive-descent parser (parse + SourceFile) under ./syntax - #795

Merged
SevInf merged 44 commits into
mainfrom
psl-parser-new
Jun 11, 2026
Merged

SevInf merged 44 commits into
mainfrom
psl-parser-new

Conversation

@SevInf

@SevInf SevInf commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds a fault-tolerant recursive-descent parser to @prisma-next/psl-parser that turns PSL source into the existing green/red concrete-syntax tree, plus a SourceFile that owns offset↔position mapping. New public surface under the ./syntax entrypoint:

import { parse } from '@prisma-next/psl-parser/syntax';

const { document, diagnostics, sourceFile } = parse('model User {\n  id Int @id\n}');
// document    : DocumentAst   (iterate document.declarations())
// diagnostics : readonly ParseDiagnostic[]   (empty for well-formed input)
// sourceFile  : SourceFile    (offset ↔ LSP Position/Range)

The package already shipped a Tokenizer and 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-based parsePslDocument is 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 — SourceFile is the single home for offset↔line/column).

How it's built

  • SourceFile (src/source-file.ts) — precomputes line starts, answers positionAt/offsetAt by binary search, 0-based LSP positions, CRLF-aware (the \r of a \r\n pair belongs to the preceding line; offsets stay absolute into the un-normalized source), clamps out-of-range both directions.
  • Substrate + leaf grammar (src/parse.ts) — drives the Tokenizer lazily via its next()/peek() interface (bounded lookahead only; trivia + Invalid + Eof flow through), tracks token offsets with a single running counter, exposes a non-emitting peekKind lookahead, the trivia-attachment discipline (trivia flushed into the enclosing open node; each child node spans first→last significant token), a diagnostic sink producing LSP ranges via SourceFile, and a recoverToSyncPoint primitive (skip to next Newline / enclosing } / Eof). Leaf parsers: expressions, type annotations, attributes.
  • Declarations + 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 a DocumentAst. Recovery is per-member: one bad line emits one diagnostic and parsing continues.
  • Diagnostics reuse the existing PslDiagnosticCode union (syntactic codes only). Messages are reconciled verbatim against parsePslDocument wherever an equivalent condition exists (FR8b).

Reviewer notes (design decisions)

  • Canonical Identifier-node wrapping for name references. The hand-built oracle is internally inconsistent about a name's leaf shape (some fixtures put a bare Ident under TypeAnnotation, others wrap it in an Identifier node). The wrapped form is the one the AST contract requires — TypeAnnotationAst.name()/namespaceName()/spaceName() resolve names through Identifier node children, so a bare-Ident annotation is accessor-broken. parse therefore 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.)
  • No new PslDiagnosticCode minted. A stray Invalid character reuses PSL_UNSUPPORTED_TOP_LEVEL_BLOCK (same code + wording parsePslDocument routes unrecognized top-level content to) — a clean fit, so the canonical union is unchanged and every consumer's exhaustiveness check stays valid.
  • Three codes keep implementer wording (PSL_INVALID_QUALIFIED_TYPE, PSL_INVALID_ATTRIBUTE_SYNTAX, PSL_INVALID_EXTENSION_BLOCK_MEMBER) — parsePslDocument has no token-anchored equivalent message for these conditions (e.g. it routes a:b:c to a model-member error, never a qualified-type error), so implementer wording is correct per FR8b.

Isolation / scope

  • The legacy regex parser and the . entrypoint are untouched. src/parser.ts (parsePslDocument) and the package-root . export show no changes vs main; the new surface is exported from ./syntax only (root re-export deferred to the parser-replacement follow-up).
  • Frozen surfaces this PR does edit — additively, by design or operator-directed during review (the original "nothing else changes / no new codes" framing no longer holds): src/tokenizer.ts gains one exported predicate (isTerminatedStringLiteral) for the unterminated-string diagnostic, with no change to its scanning; src/syntax/** gains the ObjectLiteralExpr/ObjectField node kinds + AST wrappers (Q7) and a clarifying comment, and the test oracle was corrected (buildTypesBlock type→types, Q13) with the dead string-key fixture removed; and the shared PslDiagnosticCode union gains three syntactic members — PSL_INVALID_DECLARATION, PSL_INVALID_OBJECT_LITERAL, PSL_UNTERMINATED_STRING (additive; none removed or repurposed).

Non-goals / follow-ups

  • Surfacing parse from the package root, and retiring/repointing parsePslDocument consumers — the parser-replacement follow-up.
  • Newline-insensitive attribute attachment (the CST treats newlines as trivia, so a standalone @attr on the next line attaches to the prior field — a divergence from parsePslDocument's line semantics; harmless here, revisit at consumer repointing).
  • Pre-existing, unrelated workspace-typecheck break in @prisma-next/adapter-sqlite / adapter-postgres / mongo-orm (a missing types condition on adapter-sqlite's own ./adapter export) — present on main, out of scope here.

Validation

Package gates green: typecheck, test (374 passed), lint, lint:deps, and build (the ./syntax dist exports parse / SourceFile / ParseDiagnostic / ParseResult / Position / Range). CI-ordering precondition: the green test run requires @prisma-next/framework-components to be built first — it owns the PslDiagnosticCode union, and a bare package-only run against a stale upstream dist fails to typecheck; Turbo's dependsOn covers this in CI. Conformance is snapshot-pinned — printTree for tree shape and highlight for diagnostic spans (the Q8 mechanism that replaced node-by-node GreenNodeBuilder deep-equality) — alongside lossless round-trips (concatenated token text === source) and every syntactic diagnostic's code + message + LSP range.

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).

  • Malformed custom declarations (Q9). A bare non-reserved top-level identifier with no brace (oops, datasource) now commits a generic BlockDeclaration and reports PSL_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 stray Invalid char like §) still reports PSL_UNSUPPORTED_TOP_LEVEL_BLOCK. The §/Invalid routing is unchanged. (Scope note above is corrected: this PR adds three PslDiagnosticCode members overall.)
  • Diagnostic-span polish (Q10, Q11). Missing-brace diagnostics anchor a zero-width span after the name (where the { was expected), via a new Cursor.markAfterLastToken(). The reserved-namespace-name diagnostic (namespace __unspecified__) underlines the name, not the keyword.
  • Grammar correction — types vs type (Q13). The original work misread the grammar: it treated type { (singular) as a types block. The authority — the existing parsePslDocument — 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. types is now a reserved declaration keyword; type { / type alone is a malformed composite type ("Expected a name after type").
  • Test-presentation (Q12). The multi-declaration recovery test gained printTree + highlight snapshots; a redundant test was removed.
  • Refactor — block-declaration machinery (no behaviour change). parseReservedBlock + finishReservedHeader collapsed into one parseBlock(cursor, kind, nameRequired, parseMember) (the keyword is read from the cursor), and the onHeader hook was eliminated by moving the three namespace-context checks into the dispatcher (parseDeclaration), the name-anchored one using a generalised Cursor.mark(lookahead). Three block helpers became two; −24 lines on parse.ts; snapshot diff empty.
  • Object-literal recovery + string keys (review F04 + operator follow-up). A missing colon inside an object literal no longer swallows the next field's key as a value — which had left the object unterminated and desynced the enclosing block (one missing colon → four diagnostics); { 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 flagged Object literal keys must be identifiers, and ObjectFieldAst.key() is narrowed to IdentifierAst | undefined.
  • Unterminated string literals (review — previously dismissed as out-of-scope). Accepted silently before; now flagged PSL_UNTERMINATED_STRING via an escape-aware tokenizer predicate (the tokenizer's scanning is otherwise unchanged).
  • Characterization + naming (review F05/F06/A4). Pinned the missing-brace caret position (it correctly anchors after the name — F05 was a non-issue) and the known newline-insensitive attribute attachment (F06); documented BlockDeclaration as 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/PslSpan coordinate duplication, and the rule for shared-union membership (A1); renaming parse/Position/Range (A2/A3 — declined); whether PSL_INVALID_OBJECT_LITERAL belongs in the shared union (A5); and the StringLiteralExprAst.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, and src/syntax/** implementation remain untouched (frozen-diff vs main empty). The one edit to a previously-frozen artifact is the test oracle fixture buildTypesBlock (test/syntax/ast.test.ts), corrected type→types per Q13 — the freeze had presumed the fixture was correct, and it encoded the grammar bug. No new PslDiagnosticCode member 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 — model is usable as a model/field/enum-value name) and unicode identifiers (lossless round-trip).

@SevInf
SevInf requested a review from a team as a code owner June 9, 2026 17:56
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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.

Changes

PSL Parser Implementation

Layer / File(s) Summary
Source File and Position Mapping
packages/1-framework/2-authoring/psl-parser/src/source-file.ts, packages/1-framework/2-authoring/psl-parser/test/source-file.test.ts
SourceFile computes per-line start offsets and converts between absolute offsets and { line, character } with clamping and binary-search lookup; tests verify LF/CRLF/mixed/newline and clamping behavior.
Tokenization, Cursor, and Diagnostics
packages/1-framework/2-authoring/psl-parser/src/parse.ts, packages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.ts
Adds ParseDiagnostic/ParseResult, DiagnosticMark, and a Cursor that tokenizes with absolute offsets, builds green nodes while attaching trivia, computes diagnostic ranges, captures balanced {...} raw tokens, and supports recovery to sync points; includes leaf tests for offset tracking, peek behavior, and recovery semantics.
Expression Parsing
packages/1-framework/2-authoring/psl-parser/src/parse.ts, packages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.ts
Parses string/number/boolean literals, array literals, function-call-like constructors, and identifiers; returns undefined when no expression is present; tests assert round-trip fidelity.
Attribute and Arg Parsing
packages/1-framework/2-authoring/psl-parser/src/parse.ts, packages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.ts
Parses @/@@ attributes with optional dotted names and optional parenthesized arg lists; supports name: value args and captures {...} balanced raw tokens when needed; emits diagnostics for missing/malformed attribute names.
Type Annotation Parsing
packages/1-framework/2-authoring/psl-parser/src/parse.ts, packages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.ts
Parses qualified identifiers (colon and dot separators), constructor-style inline types, optional [] and ? suffixes, and emits diagnostics for over-qualification; tests cover fault-tolerance and offending-offset assertions.
Document and Declaration Parsing
packages/1-framework/2-authoring/psl-parser/src/parse.ts, packages/1-framework/2-authoring/psl-parser/test/parse-document.test.ts, packages/1-framework/2-authoring/psl-parser/test/parse-diagnostics.test.ts
parse(source) builds a DocumentAst and returns diagnostics and SourceFile; declaration parser recognizes model, enum, namespace, and type blocks, parses block bodies and members, enforces single top-level types block, emits unterminated-block and member diagnostics, and recovers. Tests validate lossless round-trips, mixed declarations ordering, CRLF handling, diagnostic codes/messages, and robustness against adversarial inputs.
Public API Re-exports
packages/1-framework/2-authoring/psl-parser/src/exports/syntax.ts
Re-exports ParseDiagnostic, ParseResult, parse, Position, Range, and SourceFile.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • wmadden

Poem

🐰 Hops through source text, line by line,
Parse the schema, syntax so fine!
Attributes whisper, types align,
Green trees grow where errors shine.
Round-trip faithful — rabbits dine on dev-time.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a fault-tolerant recursive-descent parser (parse function) and SourceFile utility exported from the ./syntax entrypoint in psl-parser.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch psl-parser-new

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/@prisma-next/extension-author-tools@795

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/@prisma-next/mongo-runtime@795

@prisma-next/family-mongo

npm i https://pkg.pr.new/@prisma-next/family-mongo@795

@prisma-next/sql-runtime

npm i https://pkg.pr.new/@prisma-next/sql-runtime@795

@prisma-next/family-sql

npm i https://pkg.pr.new/@prisma-next/family-sql@795

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/@prisma-next/extension-arktype-json@795

@prisma-next/middleware-cache

npm i https://pkg.pr.new/@prisma-next/middleware-cache@795

@prisma-next/mongo

npm i https://pkg.pr.new/@prisma-next/mongo@795

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/@prisma-next/extension-paradedb@795

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/@prisma-next/extension-pgvector@795

@prisma-next/extension-postgis

npm i https://pkg.pr.new/@prisma-next/extension-postgis@795

@prisma-next/postgres

npm i https://pkg.pr.new/@prisma-next/postgres@795

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/@prisma-next/sql-orm-client@795

@prisma-next/sqlite

npm i https://pkg.pr.new/@prisma-next/sqlite@795

@prisma-next/extension-supabase

npm i https://pkg.pr.new/@prisma-next/extension-supabase@795

@prisma-next/target-mongo

npm i https://pkg.pr.new/@prisma-next/target-mongo@795

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/@prisma-next/adapter-mongo@795

@prisma-next/driver-mongo

npm i https://pkg.pr.new/@prisma-next/driver-mongo@795

@prisma-next/contract

npm i https://pkg.pr.new/@prisma-next/contract@795

@prisma-next/utils

npm i https://pkg.pr.new/@prisma-next/utils@795

@prisma-next/config

npm i https://pkg.pr.new/@prisma-next/config@795

@prisma-next/errors

npm i https://pkg.pr.new/@prisma-next/errors@795

@prisma-next/framework-components

npm i https://pkg.pr.new/@prisma-next/framework-components@795

@prisma-next/operations

npm i https://pkg.pr.new/@prisma-next/operations@795

@prisma-next/ts-render

npm i https://pkg.pr.new/@prisma-next/ts-render@795

@prisma-next/contract-authoring

npm i https://pkg.pr.new/@prisma-next/contract-authoring@795

@prisma-next/ids

npm i https://pkg.pr.new/@prisma-next/ids@795

@prisma-next/psl-parser

npm i https://pkg.pr.new/@prisma-next/psl-parser@795

@prisma-next/psl-printer

npm i https://pkg.pr.new/@prisma-next/psl-printer@795

@prisma-next/cli

npm i https://pkg.pr.new/@prisma-next/cli@795

@prisma-next/cli-telemetry

npm i https://pkg.pr.new/@prisma-next/cli-telemetry@795

@prisma-next/emitter

npm i https://pkg.pr.new/@prisma-next/emitter@795

@prisma-next/migration-tools

npm i https://pkg.pr.new/@prisma-next/migration-tools@795

prisma-next

npm i https://pkg.pr.new/prisma-next@795

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/@prisma-next/vite-plugin-contract-emit@795

@prisma-next/mongo-codec

npm i https://pkg.pr.new/@prisma-next/mongo-codec@795

@prisma-next/mongo-contract

npm i https://pkg.pr.new/@prisma-next/mongo-contract@795

@prisma-next/mongo-value

npm i https://pkg.pr.new/@prisma-next/mongo-value@795

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/@prisma-next/mongo-contract-psl@795

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/@prisma-next/mongo-contract-ts@795

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/@prisma-next/mongo-emitter@795

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/@prisma-next/mongo-schema-ir@795

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/@prisma-next/mongo-query-ast@795

@prisma-next/mongo-orm

npm i https://pkg.pr.new/@prisma-next/mongo-orm@795

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/@prisma-next/mongo-query-builder@795

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/@prisma-next/mongo-lowering@795

@prisma-next/mongo-wire

npm i https://pkg.pr.new/@prisma-next/mongo-wire@795

@prisma-next/sql-contract

npm i https://pkg.pr.new/@prisma-next/sql-contract@795

@prisma-next/sql-errors

npm i https://pkg.pr.new/@prisma-next/sql-errors@795

@prisma-next/sql-operations

npm i https://pkg.pr.new/@prisma-next/sql-operations@795

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/@prisma-next/sql-schema-ir@795

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/@prisma-next/sql-contract-psl@795

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/@prisma-next/sql-contract-ts@795

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/@prisma-next/sql-contract-emitter@795

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/@prisma-next/sql-lane-query-builder@795

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/@prisma-next/sql-relational-core@795

@prisma-next/sql-builder

npm i https://pkg.pr.new/@prisma-next/sql-builder@795

@prisma-next/target-postgres

npm i https://pkg.pr.new/@prisma-next/target-postgres@795

@prisma-next/target-sqlite

npm i https://pkg.pr.new/@prisma-next/target-sqlite@795

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/@prisma-next/adapter-postgres@795

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/@prisma-next/adapter-sqlite@795

@prisma-next/driver-postgres

npm i https://pkg.pr.new/@prisma-next/driver-postgres@795

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/@prisma-next/driver-sqlite@795

commit: 18b8af2

@github-actions

github-actions Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 154.35 KB (0%)
postgres / emit 121.56 KB (0%)
mongo / no-emit 76.83 KB (0%)
mongo / emit 70.95 KB (0%)
cf-worker / no-emit 183.37 KB (0%)
cf-worker / emit 147.31 KB (0%)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/1-framework/2-authoring/psl-parser/src/parse.ts (1)

504-525: 💤 Low value

Minor: Diagnostic code reuse for duplicate types blocks is semantically imprecise but acceptable.

At line 515, INVALID_TYPES_MEMBER is used for duplicate top-level types blocks, while the same code is used for invalid entries inside a types block (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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ab8857 and 5d8f468.

📒 Files selected for processing (2)
  • packages/1-framework/2-authoring/psl-parser/src/parse.ts
  • packages/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

@wmadden-electric

Copy link
Copy Markdown
Contributor

System-design review — PR #795: fault-tolerant recursive-descent PSL parser

Reviewer 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 (PslDiagnostic, PslPosition/PslSpan), and it widens a shared core union (PslDiagnosticCode) from an authoring-layer feature. These are conceptual-integrity costs the team is taking on knowingly or not; they should be named in an ADR before the parser-replacement follow-up cements them.


1. What problem is being solved, and what new concepts enter the system

Before this change, @prisma-next/psl-parser had two reachable layers: a regex/line-based parsePslDocument (src/parser.ts) that goes straight from source text to a semantic PSL AST (PslDocumentAst, the migration-plane shape in framework-components), and a separate green/red concrete-syntax-tree machinery (src/syntax/**) reachable only from hand-built fixtures. Nothing connected raw source text to that tree.

This PR adds the missing edge: a fault-tolerant recursive-descent parse(source) that produces the green/red tree wrapped as a DocumentAst, plus a SourceFile that owns offset↔line/column mapping. It is the substrate for formatter / LSP / refactor tooling.

New concepts introduced at the type/module/namespace level:

  • SourceFile — the single owner of offset↔position mapping. This is a genuinely new, well-named concept: it answers "what line/character is this offset?" by binary search over precomputed line starts. Reads cold correctly — a fresh contributor expects exactly this.
  • Cursor — the parser substrate: token cursor, green-tree builder, diagnostic sink, recovery primitive, all in one class. Reasonable name for "the moving read position plus the machinery that rides along with it," though it is doing more than a cursor (see §4).
  • ParseDiagnostic / ParseResult — the output shapes of parse.
  • The position-free CST invariant — tokens and nodes carry no offsets; SourceFile is the only home for positions. This is a real, defensible invariant and the most valuable structural decision in the PR. It keeps the tree a pure structural artifact and concentrates all coordinate arithmetic in one place. It reads true.
  • Position / Range — LSP-shaped (0-based line/character) coordinate types, defined in source-file.ts.
  • The ./syntax entrypoint surface — parse, SourceFile, ParseResult, ParseDiagnostic, Position, Range, plus the AST/green/red exports.

The position-free-CST invariant and the SourceFile-as-sole-position-owner concept are the load-bearing wins here, and they are correctly shaped. The concerns below are about duplication against concepts the system already had, not about these new ones being wrong in isolation.


2. Subsystem fit and conceptual integrity

2a. Two parsers now coexist — name the conceptual-integrity cost

The package now exposes two functions that both turn PSL source into a tree:

  • parsePslDocument(input): ParsePslDocumentResult — source → semantic PslDocumentAst, line/regex based, returns PslDiagnostic[] carrying PslSpan (offset + 1-based-style line/column).
  • parse(source): ParseResult — source → concrete DocumentAst green/red tree, recursive-descent, returns ParseDiagnostic[] carrying LSP Range.

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 parsePslDocument and parse in one package, both "parse PSL," read cold as "the old one and the new one," not as "the semantic-AST one and the lossless-CST one." A fresh contributor cannot tell from the names which to reach for, and the spec's own risk register flags exactly this ("consumers could pick the wrong one"). The bare name parse is the weakest name in the PR: it is the most generic verb in the package and it is the narrower of the two parsers (CST only). If anything, the lossless-CST parser is the more specialized one and should carry the more specific name (parseToSyntaxTree, parseCst, or similar), leaving room for the eventual unified entry point. This is a conceptual-integrity cost the team is taking on; it is acceptable for the duration of the two-parser window if named as debt, which is what the ADR recommendation in §5 is for. This is a naming change with operational cost (it renames a just-shipped public export on ./syntax), so I flag it as a likely conflict point with the principal-engineer lens — see the closing summary.

2b. Layer placement of the parser — correct

The parser lives in packages/1-framework/2-authoring/psl-parser (framework domain, authoring layer). That is the right bounded context: turning author-written source into a tree is an authoring concern, and the package already owned the tree machinery and the sibling parser. No objection.

2c. Widening a core union from an authoring feature — dependency-direction smell

PslDiagnosticCode is defined in framework-components/src/shared/psl-extension-block.ts — the core layer, shared plane. This PR adds two members (PSL_INVALID_DECLARATION, PSL_INVALID_OBJECT_LITERAL) to that union to serve the new authoring-layer parser.

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 PSL_INVALID_DECLARATION plausibly is) and questionable if they are parser-implementation-specific (PSL_INVALID_OBJECT_LITERAL is closer to that line — object literals are a parse-only grammar feature parsePslDocument does not have). The exhaustiveness blast radius (any consumer switching over PslDiagnosticCode) is a principal-engineer concern and is referred there; the typology concern — does this code belong in the shared union or in a parser-local one? — is the architect's, and it deserves an explicit answer in the ADR rather than an implicit "add it to the shared union because that is where the others live."

2d. Position/Range duplication — the most significant structural finding

source-file.ts defines Position { line, character } and Range { start, end } — LSP-shaped, 0-based. The core layer already defines PslPosition { offset, line, column } and PslSpan { start, end } in psl-extension-block.ts, and PslDiagnostic (core) already pairs a PslDiagnosticCode with a PslSpan.

So the system now carries two coordinate-type families and two diagnostic types for the same domain:

Concept Core layer (existing) This PR (new, authoring)
Point PslPosition (offset, line, column) Position (line, character)
Span PslSpan (start, end) Range (start, end)
Diagnostic PslDiagnostic (code, message, sourceId, span) ParseDiagnostic (code, message, range)

Apply the 'reads cold' probe: a fresh contributor handed both PslPosition and Position in the same package's dependency graph would assume they are the same thing or wonder why one is prefixed and one is not. Apply the consumer-vs-essence probe: the new Position/Range are named for the consumer convention (LSP / editor tooling: 0-based line/character) rather than for the essence (a source coordinate). The essence is identical to PslPosition; only the numbering convention and field names differ.

This is not automatically wrong — there is a real, defensible reason for two representations:

  • PslPosition carries offset and uses line/column in the convention parsePslDocument emits; Position is strict LSP 0-based line/character with no offset, which is what an LSP server hands an editor.

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:

  1. One coordinate vocabulary with the convention captured explicitly (e.g. a single SourceFile that exposes both offset and LSP position, and one Span/Range type the whole PSL stack shares), or
  2. Two clearly-named conventions — e.g. keep PslSpan for the offset/column form and name the new one LspRange/LspPosition so the surface tells the reader the distinction is "which coordinate convention," not "which parser happened to author it." Bare Position/Range in an authoring package, distinct from the core PslPosition/PslSpan, is the worst of both: it neither reuses the existing concept nor names why it diverges.

Recommendation: do not invent a third name; either reuse the core span vocabulary or rename the new types to LspPosition/LspRange (or scope them under a clearly-LSP namespace) so the divergence is "convention," stated, not "two synonyms for source coordinate." This interacts with the parser-replacement follow-up: when parsePslDocument is retired, the system should converge on one diagnostic and one coordinate family, and shipping a second unnamed one now makes that convergence harder.

2e. Where Position/Range belong as a layer question

Even granting that LSP-shaped coordinates are a distinct convention, source-file.ts in the authoring layer is a reasonable home for SourceFile (it is the authoring-tooling artifact that computes them). But the Position/Range types are general LSP vocabulary with no authoring-specific content; if a second consumer outside this package ever needs them, they will want to import them without depending on the parser. That is a future concern, not a current defect — note it, do not act on it now. The current placement is acceptable because SourceFile is the only producer today.


3. Boundary correctness (import-direction meaning, not just compilation)

  • psl-parser → framework-components for PslDiagnosticCode / UNSPECIFIED_PSL_NAMESPACE_ID: direction is correct (authoring depends on core/shared). The meaning is right: the diagnostic-code vocabulary and the reserved-namespace id are shared PSL concepts the core legitimately owns. The reverse pressure on the union (§2c) is the only caveat.
  • Position/Range defined in source-file.ts (authoring): compiles and is locally cohesive, but the meaning is that the authoring layer now owns a second source-coordinate vocabulary while the core owns the first. That is the duplication of §2d, surfaced as a boundary statement: the concept "source coordinate" is now split across two layers under two names. If the team keeps two conventions, the LSP one arguably belongs beside the other in core/shared so the whole stack shares it; if the team keeps one, the duplication dissolves. Either way the current split is the debt to name.
  • No cross-plane or domain violation is introduced; the parser stays within framework/authoring and depends downward/outward only. pnpm lint:deps cleanliness is a principal-engineer verification item; the intent of every edge here is defensible.

4. Naming and typology — probe results on every introduced name

Running the discriminator-completeness, consumer-vs-essence, concept-vs-mechanism, symmetry, and reads-cold probes across the surface:

  • parse — too generic, and it is the narrower of the two parsers (see §2a). Recommend a name that says "to syntax tree" (parseToSyntaxTree / parseCst). Concept-vs-mechanism: the mechanism (recursive descent) need not be in the name, but the output (CST vs semantic AST) should be, because that is the distinction that matters to the caller choosing between the two functions.
  • ParseResult / ParseDiagnostic — inherit the parse ambiguity. If parse is renamed, these follow (SyntaxParseResult, etc.). ParseDiagnostic also duplicates the core PslDiagnostic concept (§2d). Symmetry probe against PslDiagnostic: the two are nearly structurally symmetric (code + message + span) but diverge on sourceId (core has it, this lacks it) and span type. That asymmetry is unstated; it should either be reconciled or named.
  • SourceFile — good. Reads cold exactly as intended. No prefix, real concept, single responsibility (offset↔position). Keep.
  • Position / Range — see §2d. Consumer-encoded names for a concept that already exists under another name (PslPosition/PslSpan). Rename to make the LSP convention explicit, or reuse the existing vocabulary.
  • Cursor — the class is the parser substrate (token cursor + green-tree builder + diagnostic sink + recovery). The name describes one of its four jobs. This is a mild single-responsibility / name-coverage smell: "cursor" undersells "the parser state machine." ParserState or ParserCore would read truer. Not blocking — the team already iterated here (a commit message shows a ParserCursor interface+factory was collapsed into this class), and collapsing a stateless-looking substrate into a class is a legitimate call. Note it; do not block on it.
  • peekKind / peekToken / mark / markAfterLastToken / recoverToSyncPoint / flushTrivia / bump — these are standard recursive-descent / Roslyn-style vocabulary and read true to anyone who has seen a hand-written parser. bump, peek, mark, "sync point" are established terms; keep. markAfterLastToken is descriptive and honest about what it anchors. No objection.
  • DiagnosticMark — a captured {offset, length} token span. Reasonable; it is a parser-internal mechanism, correctly not exported. Concept-vs-mechanism: it is a mechanism and lives where mechanisms should (private to parse.ts). Fine.
  • parseBlock / BlockDeclaration / BlockDeclarationAst — BlockDeclaration is the committed node for a non-reserved, extension-style kw [name] { … } block. The name reads cold as "any block declaration," but it specifically means "generic/custom block, as opposed to the reserved model/enum/etc." The reserved ones are also blocks. So BlockDeclaration is doing discriminator work ("the generic kind") that its name does not carry. GenericBlockDeclaration / CustomBlockDeclaration would be truer, matching the parseGenericBlock function that produces it. Surface as a typology hole: the function is parseGenericBlock but the node it emits drops the "generic," so function and node disagree on the discriminator.
  • ObjectLiteralExpr / ObjectField (+ *Ast) — clean, symmetric with the existing ArrayLiteral / StringLiteralExpr / etc. sibling family. Reads cold correctly. Good additions; they follow the established expression-node pattern (frozen-class AST wrappers with cast and child accessors) without strain.
  • PSL_INVALID_DECLARATION — plausibly part of the shared PSL diagnostic vocabulary. Acceptable in the core union.
  • PSL_INVALID_OBJECT_LITERAL — the most parser-specific of the new codes (object literals are a parse-only grammar feature). Weakest case for living in the shared core union (§2c). Either justify it as shared vocabulary or consider whether parser-local codes want a different home.
  • The ./syntax entrypoint name — good. It names the concept (concrete-syntax tree) and cleanly separates the CST surface from the existing semantic-AST surface. The position-free CST, SourceFile, and parse all belong under "syntax." This is the one place the surface does tell the reader "this is the CST world, the other entry point is the semantic world" — which is exactly the distinction §2a wishes the function names also made. Keep; lean on it.

5. ADRs

The branch adds no ADR under docs/architecture docs/adrs/ (confirmed: 12 changed files, none under adrs/; the directory's existing ADRs 001–010+ are untouched).

An ADR is warranted, for three decisions this PR locks in:

  1. A second parser in the same package, with an explicit "retire parsePslDocument later" plan. The two-parser window, the divergence in semantics (attribute attachment across newlines, per the spec's non-goals), and the eventual convergence target are exactly the kind of decision ADRs exist to record. Without it, the next contributor sees two parsers and no written reason.
  2. A second source-coordinate / diagnostic vocabulary (Position/Range/ParseDiagnostic alongside PslPosition/PslSpan/PslDiagnostic). If the team intends to converge on the LSP shape when parsePslDocument retires, that intent should be written down so the duplication reads as a transition, not as two permanent synonyms.
  3. Widening the shared PslDiagnosticCode union from an authoring feature — the rule for "what earns a place in the shared union vs a parser-local one" is currently implicit.

Recommendation: a short ADR ("Two PSL parsers and the convergence plan") covering all three. This is the architect's lock-in-the-vocabulary concern; the cost of leaving these decisions unwritten compounds across every consumer that adopts parse / Position / ParseDiagnostic before the convergence.


6. Test strategy adequacy — at the architectural-property level only

(Whether the tests are correct or complete is a principal-engineer concern; here I check only that the test structure proves the architectural properties the design claims, and that test partitioning mirrors the conceptual partitioning.)

The test files map cleanly onto the design's claimed properties, which is good evidence the conceptual boundaries are real:

  • Position-free CST invariant + lossless round-trip — parse-document.test.ts has a dedicated round-trips lossless schemas block, and source-file.test.ts isolates the coordinate mapping. The separation of "tree structure" tests from "coordinate" tests mirrors the position-free invariant: positions are tested only against SourceFile, never against nodes. That partition is exactly what the invariant claims, so the test layout is evidence the invariant holds structurally, not just by assertion.
  • Oracle conformance — parse() well-formed document conformance asserts whole-tree equality against hand-built fixtures (up to the documented Identifier-wrapping). The architectural caveat (from the spec's risk register) is that the oracle was internally inconsistent and the PR corrected it, so conformance now partly tests parser-against-author-intent rather than against an independent authority. That is a real weakening of the oracle's authority; it is acceptable given the corrections are documented, but it is the kind of thing the ADR should note so the next person knows the oracle is not independent.
  • Fault tolerance / per-member recovery — covered by the diagnostics suites and the recoverToSyncPoint tests; the "one bad line, one diagnostic, parsing continues" property has explicit multi-construct coverage.
  • Contextual keywords + unicode — dedicated blocks (treats declaration keywords as contextual, plus the unicode commit). These prove the "keywords are contextual, not reserved" design claim directly.
  • Ordered-alternative no-op-on-non-match — ordered-alternative parsers are no-ops on non-match and expression alternatives are no-ops on non-match directly test the ??-chaining invariant that a rejected alternative consumes nothing. This is the one structural invariant the parser most depends on (a forward-only cursor must never be left half-consumed by a rejected arm), and it has a named test. Good — the test names are evidence of conceptual partitioning, not incidental coverage.

The test partitioning is sound and is itself evidence the design's boundaries are real. No architectural-property hole found in the test structure; correctness/coverage adequacy is referred to the principal-engineer pass.


7. Out-of-scope items (referred, not adjudicated)

  • Correctness of recovery, exhaustiveness blast radius of the union widening, lint:deps/build/typecheck greenness, the clamp/binary-search math in SourceFile → principal-engineer.
  • Whether parse's API is learnable from a README, whether the ./syntax surface is discoverable → devrel.
  • Whether building a second parser now (vs replacing parsePslDocument directly) is the right scope → PM / principal-engineer.
  • The PR body's contradicted scope claims ("No new PslDiagnosticCode member," "src/syntax/** untouched") — these are factual discrepancies between the PR body and the diff, flagged in the spec's open questions; reconciling the PR narrative is a tech-lead / principal-engineer item, not an architecture defect in the code itself.

Summary of required / recommended actions

# 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

@wmadden-electric

Copy link
Copy Markdown
Contributor

Code review — PR #795: fault-tolerant recursive-descent PSL parser

Principal-engineer pass. Lens: failure modes, operability, blast radius, cost/complexity, constraints-vs-assumptions.

Summary

A well-structured, well-tested recursive-descent parser that turns PSL source into the existing green/red tree with a SourceFile for offset↔position mapping. The grammar coverage, fault tolerance, and diagnostic fidelity are genuinely solid, but the "parse never throws for all inputs" claim is an unbounded-recursion assumption, not a property: deeply nested input overflows the stack and throws a RangeError.

What looks solid

  • Diagnostic fidelity is strong and behaviourally tested. Every syntactic diagnostic test asserts code + verbatim message + the LSP range rendered through a highlight helper that underlines the exact span on the exact line. These are real behavioural assertions, not name-only checks (e.g. test/parse-diagnostics.test.ts lines 65–80, 415–445).
  • SourceFile mapping is carefully done. Binary search over precomputed line starts, 0-based positions, CRLF handling (the \r belongs to the preceding line), clamping in both directions, and an inverse-round-trip test over every offset (test/source-file.test.ts lines 56–61, 70–86). I re-ran these mentally against the code and they hold.
  • The forward-only cursor invariant is tested observationally, not just asserted. expectNoOpReject drains the stream after a rejected alternative and checks the source round-trips byte-for-byte with no diagnostic emitted (test/parse-document.test.ts lines 668–678) — this is the right way to prove "a rejected ?? arm consumed nothing".
  • Lossless round-trip holds across the cases I pressure-tested: malformed input, CRLF, unicode identifiers, lone \r, BOM, unterminated string, and empty source all reproduce the source exactly (verified by running a probe against the parser, not just reading tests).
  • The shared-union widening is low blast radius. I grepped every consumer of PslDiagnosticCode (parser.ts, exports/index.ts, framework-components/.../psl-ast.ts, the union definition itself) — none switch exhaustively over it or build a Record<PslDiagnosticCode, …>. The code is carried as an opaque string on diagnostics. Adding two members breaks no exhaustiveness check. See "Acceptance-criteria verification" AC and the blast-radius note in finding F03.
  • Build, lint, lint:deps, and the 357-test suite all pass once the workspace is built (see F01 for the build-ordering caveat).

Findings

F01 — parse throws RangeError (stack overflow) on deeply nested input; the "never throws" property is unbounded-recursion-assumed, not enforced

Location: packages/1-framework/2-authoring/psl-parser/src/parse.ts — the mutually-recursive descent (parseObjectLiteralExpr → parseObjectField → parseExpression, lines 256–300; parseNamespace → parseBlock → parseBlockBody → parseDeclaration, lines 584–587, 512–541, 606–619). The Cursor tracks #depth (lines 52, 122–127) but never checks it against a limit.

Issue: FR3/AC3 state parse never throws — "every syntactic error produces a diagnostic; … parsing continues". I ran a probe against the actual parser:

objlit n=100:   OK
objlit n=1000:  OK
objlit n=5000:  THREW RangeError      // ~5k nested object literals
ns n=1000:      OK (999 diagnostics)
ns n=20000:     THREW RangeError      // ~20k nested namespaces

The depth at which it breaks depends on the host's stack size, so the real threshold is environment-dependent — that is exactly the kind of assumption-wearing-constraint-clothing the "never throws" claim hides. The consumer this is built for is a future LSP/formatter, where the input is attacker- or generator-controlled (a large machine-emitted schema, a fuzzer, a paste of minified JSON in a @default({...})). A single deeply-nested literal turns "the parser reports diagnostics and keeps going" into "the language server process crashed". #depth is already threaded through startNode/finishNode, so the mechanism to fix this is half-built and unused.

Suggestion: Enforce a depth limit. When #depth exceeds a bound (a few hundred is far beyond any real schema), stop descending: emit a single diagnostic (a new or reused code such as PSL_INVALID_DECLARATION / a nesting-specific message), run recoverToSyncPoint, and return a best-effort node instead of recursing. Add a test asserting parse of, say, 10_000 nested braces returns a result with a diagnostic and does not throw — the inverse of the current 'never throws on adversarial input' test (test/parse-document.test.ts lines 653–657), which only covers shallow garbage.

// in Cursor.startNode, before recursing further:
if (this.#depth > MAX_NESTING_DEPTH) {
  // emit one diagnostic, recover, and unwind instead of descending
}

F02 — The PR body's "357 passed" is only true after the upstream package is rebuilt; a clean pnpm --filter @prisma-next/psl-parser test on this branch reports 56 failures

Location: cross-package — packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.ts (source edit adding the two union members) vs packages/1-framework/1-core/framework-components/dist/psl-ast.* (the built artifact psl-parser actually imports, via the "./psl-ast": "./dist/psl-ast.mjs" export map).

Issue: Running the package's own test command as a reviewer, I got Test Files 1 failed | 11 passed (12); Tests 56 failed | 301 passed (357). The failure is a TypeCheckError: Type '"PSL_INVALID_EXTENSION_BLOCK_MEMBER"' is not assignable to type 'PslDiagnosticCode' at the pre-existing src/parser.ts:1689. Root cause: the new diagnostic codes were added to the framework-components source but the dist/psl-ast.d.mts that psl-parser consumes is stale and does not contain them — so the union the consumer sees is the old, narrower one, and even a pre-existing use of PSL_INVALID_EXTENSION_BLOCK_MEMBER fails to typecheck. After pnpm --filter @prisma-next/framework-components build, the same command reports 357 passed (357), no type errors. So the suite is genuinely green, but only in a built workspace. This is the project's documented "rebuild the upstream package after changing exported types" discipline (CLAUDE.md golden rules) biting at review time, and it means CI ordering matters: the psl-parser job must run after framework-components is built, or it will fail exactly as I saw.

Suggestion: Confirm the CI pipeline builds framework-components before typechecking/testing psl-parser (Turbo's dependsOn should cover this — worth a one-line confirmation in the PR that the green run was a full-workspace build, not a bare package run). No code change required; this is a "the claim needs its precondition stated" item so the next person who runs the package suite in isolation isn't misled.

F03 — No test asserts parse() output deep-equals the hand-built oracle; AC1/FR9 "oracle deep-equality up to Identifier-canonicalization" is verified by author-written snapshots instead

Location: packages/1-framework/2-authoring/psl-parser/test/syntax/ast.test.ts (hand-built fixtures, fed to AST accessors — never to parse) vs test/parse-document.test.ts / test/parse-leaf.test.ts (parse output asserted via printTree inline snapshots).

Issue: The spec (AC1) and PR body describe "the conformance suite asserts whole-tree deep-equality of parse output against the hand-built oracle fixtures, up to the documented Identifier-wrapping canonicalization". I grepped for it: there is no toEqual/toStrictEqual comparing a parse(...) tree to a build*() fixture anywhere. What actually exists is two separate things: (a) ast.test.ts builds fixtures by hand and exercises the AST accessor layer on them — it never calls parse; (b) the parse tests pin tree shape with printTree inline snapshots that the parser author generated. Both are reasonable tests, but the oracle's independent authority is never brought to bear on parse. The snapshot was written by observing the parser's own output, so for the AST-shape dimension the conformance is parser-against-parser-author-intent, exactly the "oracle drift" risk the spec flags. The byte-for-byte round-trip (greenText === source) is independent and strong; the internal node shape is not independently checked.

Suggestion: Either (a) add a small number of true deep-equality assertions feeding a parse(...) result and the matching hand-built oracle fixture into expect(...).toEqual(...) (modulo the documented Identifier wrapping), which is what AC1 promises; or (b) if the team is satisfied that printTree snapshots are the intended conformance mechanism, correct the spec/PR wording so AC1 says "snapshot-pinned tree shape" rather than "deep-equality against the oracle". This is a referral-adjacent point on whether the oracle should stay authoritative — the architect pass owns that call; I am flagging that the claimed test does not exist as written.

F04 — Object-literal recovery on a missing : can over-consume and silently swallow the following field's content

Location: packages/1-framework/2-authoring/psl-parser/src/parse.ts — parseObjectField, lines 291–298 (the else branch for a key with no colon calls parseExpression(cursor) as best-effort).

Issue: When a field has a key but no :, the code emits the Expected ":" diagnostic and then unconditionally calls parseExpression to "consume a value if one follows". On input like { a b: 1 }, after the a key with no colon, the best-effort parseExpression consumes b as an identifier expression; the outer loop then sees : (not ,/}) and breaks, leaving : 1 } unconsumed in the parent. The round-trip still holds (the parent re-absorbs the tail as trivia/raw tokens at a higher level), but the structured recovery is worse than it looks: the b: 1 field is not recognised as a field, and only one diagnostic is produced for what a human reads as two problems. This is a quality-of-recovery issue in the exact substrate an LSP relies on to keep producing useful structure past an error. It is not covered by a test — the existing missing-colon test (test/parse-leaf.test.ts lines 524–534) uses { a 1 }, where the best-effort consume happens to land correctly.

Suggestion: Add a test for { a b: 1 } (or { a, b: 1 }) pinning the recovery shape, and consider not consuming a best-effort value when the next significant token is itself a plausible key followed by : — i.e. let the loop re-enter parseObjectField rather than eating the next key as this field's value. At minimum, document the chosen recovery behaviour with a test so a future change does not silently regress it.

F05 — markAfterLastToken anchors a zero-width missing-brace span before trailing trivia, which can place the caret mid-whitespace rather than at end-of-content

Location: packages/1-framework/2-authoring/psl-parser/src/parse.ts — markAfterLastToken (lines 117–119) returns { offset: #offset, length: 0 }, used for the missing-{ diagnostic in parseBlock (line 532) and parseGenericBlock (line 577). #offset is advanced including trailing trivia by bump/flushTrivia via #advance (lines 134–141, 154–161, 176–178).

Issue: The doc comment says the mark sits "just past the last consumed significant token (before any trailing trivia)", but #offset is the running counter after whatever was last consumed, and bump/flushTrivia fold trailing trivia into the consumed offset before the missing-brace check runs. For model User (no trailing space) the tested behaviour is correct — the caret lands right after User (test/parse-diagnostics.test.ts lines 301–313). But for model User (trailing spaces, or a trailing newline before EOF) the zero-width span would anchor after the whitespace, not at the end of User. No test covers the trailing-trivia case, so the comment and the behaviour may already disagree. For an LSP squiggle this is the difference between "underline sits at the name" and "underline floats in empty space".

Suggestion: Add a test with trailing whitespace/newline after a brace-less header (e.g. 'model User \n') and confirm the caret position is the one you want. If it should sit immediately after the last significant token, capture that offset at the point the significant token is bumped rather than reading the post-trivia #offset. Either fix the behaviour or correct the comment to match.

F06 — A standalone block attribute on the line after a field silently attaches to the prior field — a real semantic divergence from parsePslDocument, currently only mentioned in the PR body

Location: packages/1-framework/2-authoring/psl-parser/src/parse.ts — parseField (lines 689–698) and parseEnumValue (lines 700–708) loop while (cursor.peekKind() === 'At'), and because newlines are trivia the loop crosses line boundaries.

Issue: The PR body lists "newline-insensitive attribute attachment" as a known divergence and defers it to consumer repointing. That is a legitimate scope call (the new parser is ./syntax-only and nothing consumes it for semantics yet — see Deferred). But the divergence is undocumented in the code and tests: there is no test pinning the current behaviour, so when the follow-up repoints consumers, whoever does it has no failing test telling them this case differs from parsePslDocument's line semantics. This is conceptual debt being taken on quietly.

Suggestion: Add a test that pins the current cross-newline attachment behaviour (e.g. model M {\n id Int\n @id\n} — assert the @id attaches to id), with a comment pointing at the divergence so the follow-up has a concrete signal. This is cheap and turns an in-prose caveat into an executable one.

F07 — StringLiteralExprAst.value() hand-rolls an escape decoder that diverges from PSL/JSON string semantics

Location: packages/1-framework/2-authoring/psl-parser/src/syntax/ast/expressions.ts — value() lines 70–90.

Issue: The unescape handles \n \r \t \" \\ and passes everything else through as \<char>. It does not handle \u#### / \x## / \0 / \b / \f, and Number(tok.text) in NumberLiteralExprAst.value() (lines 108–112) will silently produce NaN or a lossy value for inputs the tokenizer accepts but Number mis-parses. This is a value-decoder reinventing a solved problem; for the LSP/formatter use case, returning a subtly wrong decoded string is worse than the raw token. It is new public surface (./syntax exports StringLiteralExprAst), so the divergence ships to consumers.

Suggestion: Either narrow the public contract (document that value() is a best-effort decode and consumers should prefer the raw token text for fidelity), or reuse an existing decode path if the tokenizer/parsePslDocument already has one — worth a grep before hand-rolling. If a hand-rolled decoder stays, add tests for \u, \0, and a malformed escape so the behaviour is pinned rather than incidental. (Architect referral: whether a value-decode belongs on the CST AST node at all, vs a separate semantic layer, is a typology call.)

Deferred (out of scope)

  • Unterminated strings produce no diagnostic. I probed model M {\n id String @default("oops\n} — it round-trips but yields zero diagnostics. Root cause is the tokenizer (src/tokenizer.ts lines 186–195, unchanged on this branch): it emits a StringLiteral token for an unterminated string with no error signal, so the parser has no way to flag it. Fixing this means changing the tokenizer, which C1 explicitly keeps frozen. Out of scope: it belongs to a tokenizer-diagnostics change, not this parser PR.
  • Replacing parsePslDocument / exporting parse from the package root. Explicit non-goal (FR1, PR "Non-goals"). The two-parser divergence window (including F06's attribute attachment) lives here until the follow-up repoints consumers.
  • BOM at start of file produces two diagnostics rather than being skipped. Probed model M {} → round-trips, 2 diagnostics (the BOM is routed as unsupported top-level content). Whether a leading BOM should be silently consumed is a tokenizer/lexing policy question, not a parser-substrate one; same frozen-tokenizer reason as the unterminated-string item.
  • The pre-existing workspace typecheck break in adapter-sqlite/adapter-postgres/mongo-orm. Present on main, called out in the PR body. Not this PR's to fix.

Already addressed

These were the PR's own post-review amendments (Q9–Q13). I verified each against the branch's code/tests and the named commits.

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 whether printTree snapshots 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.

@SevInf

SevInf commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

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.
ADRs - I don't agree that decision to have 2 parsers is worth documenting because old parser will go away in the very next PR. We should probably document decision regarding new parser architecture, I'll do it once I've replaced the old one.
F03 - this was an outdated acceptance criteria. Those tests existed at some point but were not really human-readable in any form. Replaced it with debug print snapshots instead.

SevInf added 21 commits June 11, 2026 15:52
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]>
SevInf and others added 16 commits June 11, 2026 15:52
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]>
@SevInf
SevInf merged commit cca7f81 into main Jun 11, 2026
20 checks passed
@SevInf
SevInf deleted the psl-parser-new branch June 11, 2026 16:05
SevInf added a commit that referenced this pull request Jun 17, 2026
… 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]>
SevInf added a commit that referenced this pull request Jun 19, 2026
#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]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants