Repository navigation
Add lossless PSL syntax tree + typed AST under psl-parser/syntax - #776
Conversation
|
Warning Review limit reached
More reviews will be available in 16 minutes and 45 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR implements green/red syntax trees, typed AST wrappers for PSL declarations/attributes/expressions/identifiers/type-annotations, helper utilities, a GreenNodeBuilder, barrel exports, package subpath export, and comprehensive Vitest tests. ChangesPSL Parser Syntax and AST Layer
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
…appers Implements a Roslyn/rust-analyzer style red/green tree infrastructure for PSL: - Green layer: immutable GreenToken/GreenNode with GreenNodeBuilder - Red layer: SyntaxNode with parent pointers, offsets, and navigation - Typed AST wrappers for all PSL constructs (documents, models, enums, fields, attributes, expressions) - Exported via new `@prisma-next/psl-parser/syntax` subpath Co-Authored-By: Claude Opus 4.6 <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
…rage gate Cover all previously untested AST wrapper methods (EnumDeclarationAst, TypesBlockAst, BlockDeclarationAst, NamedTypeDeclarationAst, FieldDeclarationAst.attributes, FunctionCallAst, ModelAttributeAst.argList) and SyntaxNode.textLength/prevSibling to bring functions coverage to 100%. Co-Authored-By: Claude Opus 4.6 <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
…es, enum attributes, and qualified type refs Adds the missing typed-AST vocabulary so the lossless syntax tree can represent the PSL surface the parser already accepts: - enum @@Map and enum-value @Map via attributes() accessors - composite-type `type N {}` declarations (CompositeTypeDeclaration) - namespace blocks (Namespace) whose declarations() yields only namespace-valid members (NamespaceMemberAst) - qualified (ns.T), cross-space (space:ns.T), and inline-constructor (Vector(1536)) type references on TypeAnnotation Signed-off-by: Serhii Tatarintsev <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/1-framework/2-authoring/psl-parser/src/syntax/ast/type-annotation.ts (1)
15-18: 💤 Low valueConsider deferring array collection to improve performance.
The REVIEW comment correctly notes that
Array.fromeagerly allocates and iterates all segments, while most callers (name(),spaceName(),namespaceName()) only need one element. A helper that iterates once and returns a specific index (e.g.,findSegmentAt(index)) would avoid the allocation cost.Since this is a new implementation and the current approach works correctly, this optimization can be deferred to a follow-up PR when profiling shows it's worthwhile.
🤖 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/syntax/ast/type-annotation.ts` around lines 15 - 18, The current `#segments`() method eagerly builds an array via Array.from(filterChildren(...)) causing unnecessary allocations; replace it with a streaming helper (e.g., findSegmentAt(index)) that iterates filterChildren(this.syntax, IdentifierAst.cast) once and returns the nth IdentifierAst or undefined without collecting all items, and update callers name(), spaceName(), and namespaceName() to call findSegmentAt(0/1/...) as appropriate so they avoid the allocation; keep IdentifierAst.cast and filterChildren usage unchanged, and leave the old `#segments`() behavior only if you need backward compatibility (or remove it after switching callers).
🤖 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.
Inline comments:
In `@packages/1-framework/2-authoring/psl-parser/src/syntax/ast/expressions.ts`:
- Around line 70-80: The value() method currently applies escape replacements in
an order that turns intended literal backslash sequences like "\\n" into actual
newlines; fix by handling escaped backslashes first or performing a single-pass
replacement mapping all escapes. Locate value() in expressions.ts (uses
this.token(), tok.text.slice(1, -1)) and either 1) run the .replace(/\\\\/g,
'\\') before the other .replace calls, or 2) replace all escape sequences in one
pass using a single regex with a callback that maps '\\\\' -> '\\', '\\n' ->
'\n', '\\r' -> '\r', '\\t' -> '\t', '\\"' -> '"' to ensure sequences like
"\\\\n" are preserved correctly as backslash + 'n'.
In `@packages/1-framework/2-authoring/psl-parser/src/syntax/red.ts`:
- Around line 101-110: The code uses bare "as" casts in descendants() and other
places (e.g., casting stack.pop() and child entries to SyntaxElement); replace
these casts with local runtime narrowing/guards: in descendants(), change "const
el = stack.pop() as SyntaxElement;" to let el = stack.pop(); if (!el) continue;
and keep the existing "if (el instanceof SyntaxNode)" check; when pushing
children remove "as SyntaxElement" and either filter/map children with a type
guard (e.g., children.filter((c): c is SyntaxElement => /* guard */)) or use an
instanceof/type-check before stack.push(children[i]); apply the same pattern
where bare casts appear at the other locations (lines around 141/143) — replace
"as" casts with explicit guards or predicate functions so SyntaxElement is
established by control flow rather than by assertion.
---
Nitpick comments:
In
`@packages/1-framework/2-authoring/psl-parser/src/syntax/ast/type-annotation.ts`:
- Around line 15-18: The current `#segments`() method eagerly builds an array via
Array.from(filterChildren(...)) causing unnecessary allocations; replace it with
a streaming helper (e.g., findSegmentAt(index)) that iterates
filterChildren(this.syntax, IdentifierAst.cast) once and returns the nth
IdentifierAst or undefined without collecting all items, and update callers
name(), spaceName(), and namespaceName() to call findSegmentAt(0/1/...) as
appropriate so they avoid the allocation; keep IdentifierAst.cast and
filterChildren usage unchanged, and leave the old `#segments`() behavior only if
you need backward compatibility (or remove it after switching callers).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 27a566f2-0e50-471b-89fb-8fc7e230e5e0
📒 Files selected for processing (17)
packages/1-framework/2-authoring/psl-parser/package.jsonpackages/1-framework/2-authoring/psl-parser/src/exports/syntax.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast-helpers.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/attributes.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/declarations.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/expressions.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/identifier.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/type-annotation.tspackages/1-framework/2-authoring/psl-parser/src/syntax/green-builder.tspackages/1-framework/2-authoring/psl-parser/src/syntax/green.tspackages/1-framework/2-authoring/psl-parser/src/syntax/red.tspackages/1-framework/2-authoring/psl-parser/src/syntax/syntax-kind.tspackages/1-framework/2-authoring/psl-parser/test/syntax/ast.test.tspackages/1-framework/2-authoring/psl-parser/test/syntax/green-builder.test.tspackages/1-framework/2-authoring/psl-parser/test/syntax/green.test.tspackages/1-framework/2-authoring/psl-parser/test/syntax/red.test.tspackages/1-framework/2-authoring/psl-parser/tsdown.config.ts
…nnotation segments Addresses CodeRabbit review on #776: - StringLiteralExprAst.value() decoded escapes via sequential replace, so an escaped backslash before a letter (PSL "test\\n") was mis-decoded as the following escape (newline). Decode in a single left-to-right pass instead. - TypeAnnotationAst no longer materialises an array of identifier segments per accessor; name()/namespaceName() iterate once, spaceName() takes the first child. Removes the leftover REVIEW note. Signed-off-by: Serhii Tatarintsev <[email protected]>
Linked issue
n/a — no Linear ticket. Exploratory work on the
@prisma-next/psl-parserlossless syntax tree. The only red/green-tree tickets (PLT-6314, PLT-6316) were canceled as automation errors; happy to link a TML issue if one should track this.At a glance
Before this branch the package exposed only the line-oriented
parsePslDocument(producing a flatPslDocumentAst); there was no@prisma-next/psl-parser/syntaxsubpath and no navigable tree.Decision
This PR introduces a lossless red/green syntax tree and a typed AST layer for PSL, shipped under the new
@prisma-next/psl-parser/syntaxsubpath. Two substantive pieces:GreenNode/GreenToken+GreenNodeBuilder), a red layer (SyntaxNode/SyntaxTokenwith lazily-computed offsets and full navigation — children, siblings, ancestors, descendants, tokens), and typed AST wrappers over theSyntaxKindalphabet.parsePslDocumentalready accepts: models, enums (including@@map/ per-value@map), composite types (type N {}), the documenttypes {}block,namespaceblocks, generickeyword Name { … }blocks, field/block attributes with namespaced names and positional/named argument lists, the expression grammar, and qualified / cross-space / inline-constructor type references.This PR ships the tree vocabulary and structure, not a producer that consumes PSL source — see Notes for the reviewer.
How it fits together
src/syntax/green.ts,green-builder.ts) — immutable, position-independent nodes/tokens, assembled with astartNode/token/finishNodebuilder. Tokens carrykind+textonly, so green subtrees are shareable.src/syntax/red.ts) —SyntaxNodewraps a green node with a parent pointer and an absolute offset computed lazily on walk.SyntaxToken extends Tokenwith thatoffset. This is the layer consumers navigate.src/syntax/ast/*.ts) — thin typed wrappers (DocumentAst,ModelDeclarationAst,EnumDeclarationAst,CompositeTypeDeclarationAst,NamespaceDeclarationAst,TypeAnnotationAst, the expression nodes, …) with intent-named accessors, each cast from aSyntaxNodeby kind.src/exports/syntax.ts) — the@prisma-next/psl-parser/syntaxbarrel, wired as atsdownentry and package export.Behavior changes & evidence
@prisma-next/psl-parser/syntaxentry point exposing the green/red layers and typed AST. Impl:src/exports/syntax.ts,tsdown.config.ts. Evidence:test/syntax/green.test.ts,test/syntax/red.test.ts.EnumDeclarationAst.attributes()(@@map) andEnumValueDeclarationAst.attributes()(per-value@map). Impl:src/syntax/ast/declarations.ts. Evidence:test/syntax/ast.test.ts.CompositeTypeDeclarationandNamespaceSyntaxKinds with their wrappers, wired intoDocumentAst.declarations(). A namespace'sdeclarations()yields only what may legally appear inside a namespace (NamespaceMemberAst= model | enum | composite type | block), while the document is the superset that additionally allowstypes {}and nestednamespace. Impl:src/syntax/ast/declarations.ts,src/syntax/syntax-kind.ts. Evidence:test/syntax/ast.test.ts.TypeAnnotationAst(auth.User,supabase:auth.User,Vector(1536)), preservingisList/isOptional. Impl:src/syntax/ast/type-annotation.ts. Evidence:test/syntax/ast.test.ts.Notes for the reviewer
GreenNodeBuilder(the tests do exactly this). This PR delivers the lossless structure and the typed AST vocabulary; wiring the tokenizer to the builder so real.psltext round-trips is separate, larger follow-up work. Reviewing against "is the vocabulary right and faithful toparser.ts?" rather than "does it parse?" is the intended lens.castNamespaceMemberis the authoritative set for a namespace body;DocumentAst.declarations()composes it as a superset. The dependency points one way (document → namespace members) so a document-only node liketypes {}can never leak into the namespace set —parser.ts:204rejectstypesinside a namespace, andparser.ts:182rejects nested namespaces.pnpm --filter @prisma-next/psl-parser testwithout building dependencies first surfaces implicit-any errors inparser.ts(it imports types from@prisma-next/framework-components). Those are an unbuilt-deps artifact, not introduced here; building the dep graph first clears them.test/syntax/ast.test.ts— it builds representative trees for each construct and asserts the accessors.Skill update
n/a — internal only. New public TypeScript surface (
@prisma-next/psl-parser/syntax) but it is not yet consumed by any user-facing CLI/config/error surface; no skill governs it.Testing performed
pnpm --filter @prisma-next/psl-parser... build— green (emits the newdist/syntax.mjs+ d.mts).pnpm --filter @prisma-next/psl-parser test— 227 passing (unit + type tests), no type errors.pnpm --filter @prisma-next/psl-parser lint— clean.pnpm lint:deps— no dependency-layering violations.Alternatives considered
parser.tsinstead of adding a tree. Rejected — the line/regex parser is lossy (it strips comments and whitespace) and can't back editor/tooling use cases that need a lossless, navigable tree with offsets.QualifiedTypeRefnode vs. extendingTypeAnnotation. Chose to extendTypeAnnotation: the namespace/space qualifiers and the inline constructor are optional decorations on the same annotation, alongside the existingisList/isOptional, so a single node with optional accessors matched the existing style with no newSyntaxKind.Checklist
git commit -s) per the DCO.TML-NNNN: <sentence-case title>form — no Linear ticket exists for this exploratory work; using a plain descriptive title. Will add the prefix if a ticket is assigned.Summary by CodeRabbit
Release Notes
New Features
Refactor
Tests