Repository navigation
TML-2929: replace legacy PSL parser with CST symbol table - #851
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR replaces legacy PSL document parsing inputs with a parse-plus-symbol-table pipeline, updates SQL and Mongo interpreters and providers to consume symbol-table artifacts plus seeded diagnostics, and rewires docs and tests to the new flow. ChangesPSL symbol-table pipeline migration
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)
534-541:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSkip already-reported malformed relation types.
resolveFieldTypeDescriptorsuppresses cascaded field-type diagnostics, but relation fields bypass it becauserelationAttributesstill includes fields whosetypeAlreadyReportedwas set by the CST view builder. Those can cascade intoPSL_UNKNOWN_CONTRACT_SPACE/PSL_INVALID_RELATION_TARGETafter the original malformed qualified-type diagnostic.Suggested fix
const relationAttributes = model.fields .map((field) => ({ field, relation: getAttribute(field.attributes, 'relation'), })) .filter((entry): entry is { field: CstFieldView; relation: CstAttributeView } => - Boolean(entry.relation), + Boolean(entry.relation) && !entry.field.typeAlreadyReported, );🤖 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/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 534 - 541, The relationAttributes assignment includes fields that have already been flagged as malformed in typeAlreadyReported, causing cascaded diagnostics. Modify the filter predicate in the relationAttributes assignment to additionally check that the field's typeAlreadyReported property is false before including the entry, ensuring that relation fields with pre-existing type errors are skipped and do not trigger PSL_UNKNOWN_CONTRACT_SPACE or PSL_INVALID_RELATION_TARGET diagnostics.
🧹 Nitpick comments (1)
packages/2-sql/2-authoring/contract-psl/test/interpreter.enum.test.ts (1)
86-90: ⚡ Quick winRemove or wire the no-op descriptor argument.
symbolTableInputFromParseArgscurrently ignorespslBlockDescriptors, so this spread does not affect the parse/symbol-table input. Either drop it here or thread the descriptor through the fixture if the test is meant to cover descriptor-aware parsing.🤖 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/2-sql/2-authoring/contract-psl/test/interpreter.enum.test.ts` around lines 86 - 90, The conditional spread of pslBlockDescriptors into the symbolTableInputFromParseArgs call has no effect since the function ignores this parameter. Either remove the spread operator and the descriptors condition entirely if descriptor-aware parsing is not needed for this test, or if it is needed, modify the symbolTableInputFromParseArgs function to actually accept and use the pslBlockDescriptors parameter by threading it through to where it matters.
🤖 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/extension-block.ts`:
- Around line 210-232: The buildRefResolutionContext function currently only
includes models from symbolTable.topLevel.models and assigns them all to the
__unspecified__ namespace, dropping any models that belong to named namespaces.
To fix this, retrieve both top-level models and named-namespace models from the
symbol table, then for each namespace (both __unspecified__ and any named
namespaces), create appropriate namespace entries using makePslNamespace with
the correct models assigned to each namespace. Update the allNamespaces return
value to include all created namespaces so that ref resolution can find models
in their actual namespaces and avoid false unknown ref diagnostics.
- Around line 117-133: In the extension-block.ts file, the code handling list
parameters with kind 'list' currently returns an empty list `{ kind: 'list',
items: [] }` when `ArrayLiteralAst.cast(value.syntax)` fails to cast the value
to an array. This silently converts invalid non-array input into a valid empty
list, bypassing validation errors. Add error handling for when the array cast
fails: after checking `if (array)`, add an else clause that throws an
appropriate error to indicate that a list parameter received a non-array
expression, ensuring invalid inputs are properly caught instead of coerced into
empty lists.
In `@packages/2-sql/2-authoring/contract-psl/README.md`:
- Line 85: The documented signature for interpretPslDocumentToSqlContract is
missing the composedExtensionContracts parameter. Add composedExtensionContracts
to the parameter list in the README documentation on line 85, placing it
alongside the other optional parameters like composedExtensionPacks, to align
the documentation with the actual function's input contract that depends on this
field.
In `@packages/2-sql/2-authoring/contract-psl/src/psl-named-type-resolution.ts`:
- Around line 99-100: The storageTypes object is initialized as an empty object
and likely populated using direct property assignments, which risks prototype
pollution if declaration names match prototype-special keys like __proto__.
Refactor the storageTypes initialization to accumulate entries in an array
during population (storing tuples of declaration.name and its corresponding
value), then construct the final object using Object.fromEntries() at the end
instead of direct assignment. This ensures all declared names become safe own
data properties without prototype chain corruption.
In `@packages/2-sql/2-authoring/contract-psl/src/symbol-views.ts`:
- Around line 122-131: The baseType extraction at line 124 uses
identifier()?.name() which drops namespace/space qualifiers from type
annotations. Replace the call chain annotation?.name()?.identifier()?.name()
with annotation?.name()?.name() to preserve the fully qualified type name,
ensuring that qualified base types like ns.Type are retained instead of being
reduced to just Type, which prevents incorrect downstream type resolution.
---
Outside diff comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 534-541: The relationAttributes assignment includes fields that
have already been flagged as malformed in typeAlreadyReported, causing cascaded
diagnostics. Modify the filter predicate in the relationAttributes assignment to
additionally check that the field's typeAlreadyReported property is false before
including the entry, ensuring that relation fields with pre-existing type errors
are skipped and do not trigger PSL_UNKNOWN_CONTRACT_SPACE or
PSL_INVALID_RELATION_TARGET diagnostics.
---
Nitpick comments:
In `@packages/2-sql/2-authoring/contract-psl/test/interpreter.enum.test.ts`:
- Around line 86-90: The conditional spread of pslBlockDescriptors into the
symbolTableInputFromParseArgs call has no effect since the function ignores this
parameter. Either remove the spread operator and the descriptors condition
entirely if descriptor-aware parsing is not needed for this test, or if it is
needed, modify the symbolTableInputFromParseArgs function to actually accept and
use the pslBlockDescriptors parameter by threading it through to where it
matters.
🪄 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: c484bdfc-b52d-48f0-9f44-35983b03c7b0
⛔ Files ignored due to path filters (8)
projects/psl-cst-symbol-table/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/build-symbol-table/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/build-symbol-table/spec.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/migrate-mongo-and-remove-legacy-parser/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/migrate-mongo-and-remove-legacy-parser/spec.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/migrate-sql-interpreter/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/migrate-sql-interpreter/spec.mdis excluded by!projects/**projects/psl-cst-symbol-table/spec.mdis excluded by!projects/**
📒 Files selected for processing (62)
docs/architecture docs/adrs/ADR 163 - Provider-invoked source interpretation packages.mdpackages/1-framework/1-core/framework-components/src/shared/psl-extension-block.tspackages/1-framework/2-authoring/psl-parser/README.mdpackages/1-framework/2-authoring/psl-parser/package.jsonpackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/1-framework/2-authoring/psl-parser/src/exports/parser.tspackages/1-framework/2-authoring/psl-parser/src/extension-block.tspackages/1-framework/2-authoring/psl-parser/src/parser.tspackages/1-framework/2-authoring/psl-parser/src/symbol-table.tspackages/1-framework/2-authoring/psl-parser/test/parser-enum.test.tspackages/1-framework/2-authoring/psl-parser/test/parser.test.tspackages/1-framework/2-authoring/psl-parser/test/symbol-table.test.tspackages/1-framework/2-authoring/psl-parser/tsdown.config.tspackages/1-framework/2-authoring/psl-printer/test/declarative-policy-select.round-trip.test.tspackages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/cst-read-views.tspackages/2-mongo-family/2-authoring/contract-psl/src/cst-read.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/src/provider.tspackages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.tspackages/2-mongo-family/2-authoring/contract-psl/src/symbol-views.tspackages/2-mongo-family/2-authoring/contract-psl/test/cst-read.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/symbol-views.test.tspackages/2-sql/2-authoring/contract-psl/README.mdpackages/2-sql/2-authoring/contract-psl/src/cst-read-views.tspackages/2-sql/2-authoring/contract-psl/src/cst-read.tspackages/2-sql/2-authoring/contract-psl/src/enum-block.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.tspackages/2-sql/2-authoring/contract-psl/src/psl-authoring-arguments.tspackages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-named-type-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.tspackages/2-sql/2-authoring/contract-psl/src/symbol-views.tspackages/2-sql/2-authoring/contract-psl/test/composed-mutation-defaults.test.tspackages/2-sql/2-authoring/contract-psl/test/cst-read.test.tspackages/2-sql/2-authoring/contract-psl/test/enum-block.test.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.control-policy.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.defaults.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.enum.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.extensions.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.types.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.value-objects.test.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.tspackages/2-sql/2-authoring/contract-psl/test/ts-psl-parity.test.tspackages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-runner.polymorphism.integration.test.tstest/integration/test/authoring/parity/ts-psl-parity.real-packs.test.tstest/integration/test/authoring/psl-index-type-options.integration.test.tstest/integration/test/mongo/migration-psl-authoring.test.tstest/integration/test/value-objects/value-objects.integration.test.ts
💤 Files with no reviewable changes (5)
- packages/1-framework/2-authoring/psl-parser/test/parser-enum.test.ts
- packages/1-framework/2-authoring/psl-parser/package.json
- packages/1-framework/2-authoring/psl-parser/src/parser.ts
- packages/1-framework/2-authoring/psl-parser/src/exports/parser.ts
- packages/1-framework/2-authoring/psl-parser/test/parser.test.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts (2)
497-513:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftPropagate field preset nullability into the resolved field.
FieldPresetContributions.nullableis preserved frominstantiateFieldPreset, but this push drops it; downstream model building readsresolvedField.field.optional, and Line 397 rejects?on preset fields, so nullable presets always lower as non-null columns.Proposed fix
export type ResolvedField = { readonly field: FieldSymbol; readonly columnName: string; readonly descriptor: ColumnDescriptor; + readonly nullable: boolean; readonly defaultValue?: ColumnDefault; readonly executionDefaults?: ExecutionMutationDefaultPhases; readonly isId: boolean; readonly isUnique: boolean; @@ resolvedFields.push({ field, columnName: mappedColumnName, descriptor, + nullable: presetContributions?.nullable ?? field.optional, ...ifDefined('defaultValue', fieldDefaultValue), ...ifDefined('executionDefaults', fieldExecutionDefaults), isId: isIdField || Boolean(presetContributions?.id), isUnique: Boolean(uniqueAttribute) || Boolean(presetContributions?.unique),Then update the model-node lowering site to consume the resolved nullability:
- nullable: resolvedField.field.optional, + nullable: resolvedField.nullable,🤖 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/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts` around lines 497 - 513, The nullable information from presetContributions is not being included when pushing resolved fields in the resolvedFields array. Add the nullable property from presetContributions to the resolved field object using the same ifDefined pattern used for other optional properties like defaultValue and executionDefaults. Capture presetContributions?.nullable and include it in the pushed object so that downstream model building can consume the resolved nullability instead of only relying on the original field.optional value.
44-47:⚠️ Potential issue | 🟠 Major | ⚡ Quick winValidate enum
@defaultarity before reading the first positional argument.This path silently ignores invalid enum defaults like
@default(A, B)and silently drops named-only defaults because it reads only the first positional entry, unlike the non-enum default path which requires exactly one positional argument.Proposed fix
function lowerEnumDefaultForField(input: { readonly modelName: string; readonly fieldName: string; readonly defaultAttribute: ResolvedAttribute; readonly enumHandle: EnumTypeHandle; readonly sourceId: string; readonly diagnostics: ContractSourceDiagnostic[]; }): LoweredFieldDefault { + const positionalEntries = input.defaultAttribute.args.filter((arg) => arg.kind === 'positional'); + const namedEntries = input.defaultAttribute.args.filter((arg) => arg.kind === 'named'); + + if (namedEntries.length > 0 || positionalEntries.length !== 1) { + input.diagnostics.push({ + code: 'PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT', + message: `Field "${input.modelName}.${input.fieldName}" requires exactly one positional `@default`(...) enum member.`, + sourceId: input.sourceId, + span: input.defaultAttribute.span, + }); + return {}; + } + const expressionEntry = getPositionalArgumentEntry(input.defaultAttribute); if (!expressionEntry) { - return {}; + input.diagnostics.push({ + code: 'PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT', + message: `Field "${input.modelName}.${input.fieldName}" requires a positional `@default`(...) enum member.`, + sourceId: input.sourceId, + span: input.defaultAttribute.span, + }); + return {}; }🤖 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/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts` around lines 44 - 47, The enum default validation in the code block starting with the getPositionalArgumentEntry call for input.defaultAttribute needs to validate the exact number of positional arguments, not just check if one exists. The current code silently accepts multiple positional arguments like `@default`(A, B) and drops any named-only arguments. Add validation to ensure there is exactly one positional argument and no invalid named arguments, similar to how the non-enum default path validates argument arity, and return an appropriate error response if the validation fails.
🧹 Nitpick comments (1)
packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts (1)
124-128: ⚡ Quick winPrefer
ifDefinedfor conditional object spreads.The ternary-based conditional spreads can be replaced with the
ifDefinedhelper to align with the established codebase pattern. Based on learnings, this codebase prefersifDefinedfrom@prisma-next/utils/definedfor conditional object spreads.♻️ Refactor to use ifDefined
First, add the import at the top of the file:
import type { ResolvedAttribute, ResolvedAttributeArg } from '`@prisma-next/psl-parser`'; import { parseQuotedStringLiteral } from '`@prisma-next/psl-parser`'; +import { ifDefined } from '`@prisma-next/utils/defined`';Then update the return statement:
return { - ...(relationName !== undefined ? { relationName } : {}), - ...(fields !== undefined ? { fields } : {}), - ...(references !== undefined ? { references } : {}), + ...ifDefined('relationName', relationName), + ...ifDefined('fields', fields), + ...ifDefined('references', references), };🤖 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/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts` around lines 124 - 128, Replace the ternary-based conditional object spreads in the return statement with the `ifDefined` helper function. First, add an import for `ifDefined` from `@prisma-next/utils/defined` at the top of the file. Then update the return statement to use `ifDefined` for each conditional property (relationName, fields, and references) instead of the current ternary spread pattern. This aligns with the established codebase pattern for handling conditional object spreads.Source: Learnings
🤖 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.
Outside diff comments:
In `@packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts`:
- Around line 497-513: The nullable information from presetContributions is not
being included when pushing resolved fields in the resolvedFields array. Add the
nullable property from presetContributions to the resolved field object using
the same ifDefined pattern used for other optional properties like defaultValue
and executionDefaults. Capture presetContributions?.nullable and include it in
the pushed object so that downstream model building can consume the resolved
nullability instead of only relying on the original field.optional value.
- Around line 44-47: The enum default validation in the code block starting with
the getPositionalArgumentEntry call for input.defaultAttribute needs to validate
the exact number of positional arguments, not just check if one exists. The
current code silently accepts multiple positional arguments like `@default`(A, B)
and drops any named-only arguments. Add validation to ensure there is exactly
one positional argument and no invalid named arguments, similar to how the
non-enum default path validates argument arity, and return an appropriate error
response if the validation fails.
---
Nitpick comments:
In `@packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts`:
- Around line 124-128: Replace the ternary-based conditional object spreads in
the return statement with the `ifDefined` helper function. First, add an import
for `ifDefined` from `@prisma-next/utils/defined` at the top of the file. Then
update the return statement to use `ifDefined` for each conditional property
(relationName, fields, and references) instead of the current ternary spread
pattern. This aligns with the established codebase pattern for handling
conditional object spreads.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 3c0c2f66-d1fa-43ef-8cbf-c8555fc89a74
⛔ Files ignored due to path filters (5)
projects/psl-cst-symbol-table/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/resolve-blocks-in-symbol-table/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/resolve-blocks-in-symbol-table/spec.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/resolve-in-symbol-table/plan.mdis excluded by!projects/**projects/psl-cst-symbol-table/slices/resolve-in-symbol-table/spec.mdis excluded by!projects/**
📒 Files selected for processing (30)
packages/1-framework/2-authoring/psl-parser/README.mdpackages/1-framework/2-authoring/psl-parser/src/block-reconstruction.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/1-framework/2-authoring/psl-parser/src/extension-block.tspackages/1-framework/2-authoring/psl-parser/src/resolve.tspackages/1-framework/2-authoring/psl-parser/src/symbol-table.tspackages/1-framework/2-authoring/psl-parser/test/symbol-table.test.tspackages/1-framework/2-authoring/psl-printer/test/declarative-policy-select.round-trip.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/src/provider.tspackages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.tspackages/2-sql/2-authoring/contract-psl/src/psl-authoring-arguments.tspackages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-named-type-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.enum.test.tspackages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-runner.polymorphism.integration.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.mdtest/integration/test/authoring/parity/ts-psl-parity.real-packs.test.tstest/integration/test/authoring/psl-index-type-options.integration.test.tstest/integration/test/mongo/migration-psl-authoring.test.tstest/integration/test/value-objects/value-objects.integration.test.ts
✅ Files skipped from review due to trivial changes (2)
- skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
- packages/1-framework/2-authoring/psl-parser/README.md
🚧 Files skipped from review as they are similar to previous changes (14)
- test/integration/test/mongo/migration-psl-authoring.test.ts
- test/integration/test/value-objects/value-objects.integration.test.ts
- packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
- packages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.ts
- packages/3-mongo-target/1-mongo-target/test/mongo-runner.polymorphism.integration.test.ts
- packages/2-sql/2-authoring/contract-psl/src/provider.ts
- test/integration/test/authoring/parity/ts-psl-parity.real-packs.test.ts
- packages/2-mongo-family/2-authoring/contract-psl/src/provider.ts
- packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
- test/integration/test/authoring/psl-index-type-options.integration.test.ts
- packages/1-framework/2-authoring/psl-printer/test/declarative-policy-select.round-trip.test.ts
- packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
- packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
- packages/2-sql/2-authoring/contract-psl/src/psl-named-type-resolution.ts
Dispatch 1 of slice build-symbol-table (TML-2929). Lands the symbol-table type surface (SymbolTable, per-kind symbols, BuildSymbolTableOptions, SymbolTableResult) and a signature-only buildSymbolTable stub, plus the new PSL_DUPLICATE_DECLARATION member of the PslDiagnosticCode union. No logic, no interpreter changes, nothing deleted. Signed-off-by: Serhii Tatarintsev <[email protected]>
Replace the dispatch-1 stub with the fault-tolerant builder: iterate the
top-level and per-namespace declarations, classify types{} bindings as
scalar vs type-alias against scalarTypes (constructor annotations are never
scalar), populate the keyed records, and emit PSL_DUPLICATE_DECLARATION
first-wins on a single per-scope name set (colliding across kinds), anchored
on the later declaration name span. Qualified type references are left
unresolved on field symbols. Adds co-located unit tests covering AC1-AC5 and
the pre-investigated edge cases, plus a README note for the new public API.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Introduce package-local cst-read adapters that the SQL interpreter helpers
will consume in place of legacy Psl* object access:
- readFieldTypeAnnotation: splits a FieldDeclarationAst type annotation into
{ typeName, typeNamespaceId, typeContractSpaceId, optional, list,
isConstructor, path } from the CST QualifiedNameAst, and returns a
discriminated malformed signal (PSL_INVALID_QUALIFIED_TYPE, matching the
legacy field-type rejection) on an over-qualified name rather than throwing.
- readAttribute: reads a FieldAttributeAst/ModelAttributeAst into
{ name, args:[{kind, name?, value, range}] }, rendering each arg expression
to its verbatim source text via printSyntax().trim() for byte-parity with the
legacy normalizeAttributeArgumentValue, so the existing string-based arg
parsers are reused unchanged.
Adds tests-first coverage for bare/optional/list/dot-qualified/colon-qualified/
over-qualified/constructor types and positional+named arg rendering across
quoted-string, number, function-call, array, and object-literal value cases.
No interpreter wiring yet; no legacy Psl* types imported.
Signed-off-by: Serhii Tatarintsev <[email protected]>
…iew log Drive project artifacts for TML-2929: project spec + plan, slice specs/plans for build-symbol-table (done) and migrate-sql-interpreter (in progress), the reviewer-maintained code-review log, and the learnings ledger. Transient project tracking; removed at close-out. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add reconstructExtensionBlock(GenericBlockDeclarationAst, SourceFile) that rebuilds the legacy PslExtensionBlock shape the SQL enum factory consumes from the CST node the symbol table surfaces as a BlockSymbol (keyword: enum). The symbol table defers block-parameter parsing, so this seam reproduces the legacy parsePslDocument extension-block output: - blockAttributes: node.attributes() read via the dispatch-1 readAttribute, so @@type("codec") surfaces with its codec-id arg value verbatim (quotes kept) exactly as the factory reads it. - parameters: node.entries() mapped first-wins to the legacy member shapes — a bare member to { kind: bare, span }, a key = value member to { kind: value, raw, span } where raw is the verbatim source value (matching the legacy descriptor-free path for a variadic block, e.g. "high" stays JSON-parseable). - spans mapped Range -> PslSpan (1-based line/column + real offset) at this wiring seam. Tests reconstruct an enum block via parse() and assert the shape field-by-field against the factory read-set, then run the in-package faithful enum-factory double (testEnumEntityContributions) end-to-end over the reconstruction to prove parity: bare members, valued members, mixed, and the missing-@@type diagnostic path. No interpreter wiring; the factory is untouched. Signed-off-by: Serhii Tatarintsev <[email protected]>
Pin the descriptor-typed-extension-block-parameters follow-up (surfaced at slice-2 dispatch 2, out of scope for the enum seam) into plan open items for slice 3, and capture the accumulated reviewer round notes. Signed-off-by: Serhii Tatarintsev <[email protected]>
Move the five leaf helpers (psl-attribute-parsing, psl-authoring-arguments, psl-column-resolution, psl-relation-resolution, psl-field-resolution) off the legacy Psl* object types and onto package-local read-views (cst-read-views.ts): CstAttributeView / CstFieldView / CstModelView / CstCompositeTypeView / CstNamedTypeView / CstTypeConstructorCallView. Each view is the exact read-set the helpers touch, with PslSpan diagnostic spans, so the legacy objects the interpreter entry still builds remain structurally assignable during the migration. Diagnostic codes are unchanged. Re-union the named-type resolver: move resolveNamedTypeDeclarations (+ its validateNamedTypeAttributes) out of interpreter.ts into a new psl-named-type-resolution.ts that consumes CstNamedTypeView[], swapping the legacy baseType-vs-typeConstructor presence discriminant for the isConstructor() flag the view carries. Extract the Range->PslSpan wiring-seam maps (nodePslSpan / rangeToPslSpan) into cst-read.ts and reuse them from enum-block.ts. The interpreter entry walk is unchanged (dispatch 4). Two transitional bridges remain, marked // dispatch-4: BuildModelNodeInput/BuildValueObjectsInput accept the views (the entry still constructs assignable Psl* objects), and the named-type call site maps the legacy PslNamedTypeDeclaration[] to CstNamedTypeView[] until the symbol-table feed lands. Rename instantiatePslFieldPreset -> instantiateFieldPreset (it no longer touches PslField). Full SQL contract-psl suite stays green (273 tests). Signed-off-by: Serhii Tatarintsev <[email protected]>
Rewrite interpretPslDocumentToSqlContract to consume the SymbolTable instead of
the legacy ParsePslDocumentResult. The input now carries { symbolTable,
sourceFile, sourceId } plus the unchanged target/scalarTypeDescriptors/
authoringContributions/composedExtension*/controlMutationDefaults/createNamespace/
codecLookup.
Walk: a new symbol-views.ts builds the dispatch-3 read views directly from
symbol-table entries + their CST .node (via the dispatch-1 readFieldTypeAnnotation
/readAttribute and dispatch-2 reconstructExtensionBlock). Top-level scope maps to
the legacy __unspecified__ bucket; each NamespaceSymbol maps to its name (unbound
to the late-binding sentinel) via resolveNamespaceIdForSqlTarget. Enums are
topLevel.blocks with keyword===enum; named-namespace enums still emit
PSL_ENUM_NAMESPACE_NOT_SUPPORTED. The named-type re-union feeds
topLevel.scalars + topLevel.typeAliases with the isConstructor discriminant.
Over-qualified field types surface PSL_INVALID_QUALIFIED_TYPE at this new
derivation site (the legacy parser rejected them at parse time). All preserved
diagnostic codes unchanged; spans derived via the Range->PslSpan maps.
Both // dispatch-4 bridges are collapsed; no legacy Psl* walk remains in
interpreter.ts (validated by the grep gate). validateNamespaceBlocksForSqlTarget
now takes NamespaceSymbol[] and derives spans from .node.
Adds the shared buildSymbolTableInput test helper (fixtures.ts) for the
dispatch-6 fan-out. A minimal // dispatch-5 parse swap in provider.ts keeps src/
compiling against the new input (dispatch 5 formalises diagnostic-list surfacing
and pslBlockDescriptors rehoming).
src/ typecheck + lint clean. The 14 interpreter-driven test suites are RED
pending the dispatch-6 test fan-out (they still pass the removed `document`
input); the 5 non-interpreter suites (cst-read, enum-block,
psl-attribute-parsing, default-function-registry, provider) are green.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Turn the dispatch-4 // dispatch-5 bridge into the real provider integration.
Diagnostic surfacing (the load-bearing fix): the bridge surfaced neither
parses nor buildSymbolTables diagnostics, dropping the parity the legacy
parsePslDocument path had (it threaded document.diagnostics through the
interpreters now-removed mapParserDiagnostics). The provider now collects BOTH
lists -- parse(schema).diagnostics and buildSymbolTable(...).diagnostics, kept
separate per the project decision -- maps each ParseDiagnostic
{ code, message, range } to a ContractSourceDiagnostic (sourceId: schemaPath,
span via rangeToPslSpan), and short-circuits with notOk when either is
non-empty, rather than interpreting a structurally broken document. Adds two
provider tests asserting the restored surfacing (PSL_UNTERMINATED_BLOCK from
parse, PSL_DUPLICATE_DECLARATION from buildSymbolTable).
pslBlockDescriptors rehoming (Open Question #1): the descriptor-agnostic CST
parse/buildSymbolTable no longer consume the thread and no SQL src/ consumer
remains, so it is dropped with an inline deferral note. The enum case is
covered by enum-block reconstruction; descriptor-typed block-parameter
validation is the tracked slice-3 follow-up. See the dispatch report for a
canary finding on PSL_EXTENSION_DUPLICATE_PARAMETER.
src/ typecheck + lint clean; provider.test.ts green (22 tests). The 14
interpreter-driven suites remain red pending the dispatch-6 test fan-out.
Signed-off-by: Serhii Tatarintsev <[email protected]>
…m members Close the parity gap surfaced in dispatch 5: duplicate enum members stopped producing PSL_EXTENSION_DUPLICATE_PARAMETER once dispatch 5 dropped the pslBlockDescriptors thread (reconstructExtensionBlock dropped the duplicate first-wins silently). reconstructExtensionBlock now takes a diagnostics: ContractSourceDiagnostic[] sink + sourceId (matching how the interpreter walk collects diagnostics) and, where it drops a duplicate member key, pushes one PSL_EXTENSION_DUPLICATE_PARAMETER with the span of the later KeyValuePairAst and the legacy message shape (Duplicate parameter "<key>" in "<keyword>" block "<blockName>"; first occurrence wins). First-wins resolution is unchanged. The interpreter walk threads its existing diagnostics array + sourceId into the reconstructExtensionBlock call (two extra args, both already in scope). Adds a unit test asserting a duplicate member emits the code and keeps the first binding. Signed-off-by: Serhii Tatarintsev <[email protected]>
…preter
Operator decision E1: match the legacy parsePslDocument combined-set behaviour
instead of the dispatch-5 fail-before-interpret short-circuit.
Provider: remove the short-circuit; keep mapParseDiagnostics and pass the
combined parse + buildSymbolTable diagnostics as a new seedDiagnostics input to
the interpreter. The interpreter walks the recovered document, appends its own
diagnostics, and its existing post-walk dedupeDiagnostics + length>0 -> notOk
gate emits the deduped parse + symbol-table + interpreter union in one run.
Interpreter: add seedDiagnostics?: readonly ContractSourceDiagnostic[]; the
walk now initialises its diagnostics array from the seed instead of empty.
Spurious-diagnostic guard (FR12): an over-qualified field type already emits
PSL_INVALID_QUALIFIED_TYPE at view-build time, but the recovered field then
fell through type resolution and cascaded a spurious PSL_UNSUPPORTED_FIELD_TYPE
the legacy path never produced (the legacy parser rejected the type before the
interpreter ran). buildFieldView now marks such fields typeAlreadyReported, and
resolveFieldTypeDescriptor short-circuits to { ok:false, alreadyReported:true }
so the cascade is suppressed. Confirmed via a throwaway probe: a.b.c now yields
exactly [PSL_INVALID_QUALIFIED_TYPE] from the walk; a dropped-duplicate model
whose sibling references it still resolves clean (ok), no spurious target error.
provider.test.ts: the two dispatch-5 surfacing tests now assert the combined
path; adds a test proving a schema with BOTH a symbol-table error
(PSL_DUPLICATE_DECLARATION) and an interpreter error (PSL_UNSUPPORTED_FIELD_TYPE)
surfaces both in one provider run.
src/ typecheck + lint clean; provider.test.ts green (23 tests). The 14
interpreter-driven suites remain red pending the dispatch-6 fan-out.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Migrate the 14 interpreter-driven test suites off the legacy
parsePslDocument({ schema }) + { document } shape onto the shared
symbolTableInputFromParseArgs helper (an object-form shim over
buildSymbolTableInput, added to fixtures.ts), spreading the resulting
{ symbolTable, sourceFile, sourceId } into the migrated interpreter input.
Mechanical: parsePslDocument( -> symbolTableInputFromParseArgs(, and every
`document` property usage -> a `...document` spread; the now-unused
parsePslDocument imports are dropped.
Rewrites the one structurally-coupled test (interpreter.diagnostics) that
hand-built a fake ParsePslDocumentResult to hit the
PSL_UNSUPPORTED_NAMED_TYPE_BASE guard: a real `types { Broken }` binding (no
`= type`) reaches that guard via the symbol-table walk, so the fake AST + its
testSpan/ParsePslDocumentResult imports are removed.
Slice DoD: enum-block.ts no longer imports the framework PslExtensionBlock*
types (replaced by a package-local ReconstructedExtensionBlock structural
mirror) and the doc-comment Psl* mentions are reworded, so
`rg PslModel|PslField|PslCompositeType|PslNamedTypeDeclaration|PslExtensionBlock|parsePslDocument src`
is now empty. typecheck (src + test) and lint:deps clean.
275/277 tests pass. The 2 remaining failures are a SURFACED PARITY DIVERGENCE
(not rewritten per the dispatch CRITICAL rule): both assert
PSL_UNSUPPORTED_TOP_LEVEL_BLOCK for a `datasource {}` / descriptor-less `enum`
top-level block, which the descriptor-agnostic CST parser no longer rejects
(it accepts any non-reserved keyword as a generic block). This is a consequence
of the dropped pslBlockDescriptors thread (slice spec Open Question #1) and
needs an operator decision \u2014 see the dispatch report.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Operator decision E2 (option b): re-home the legacy descriptor-driven
unknown-top-level-block rejection into the interpreter walk, closing the last
parity gap so the full SQL contract-psl suite is green.
The legacy parser consulted pslBlockDescriptors via lookupExtensionBlockDescriptor
to decide whether a `keyword name {` block was a legitimate extension block or
an unsupported top-level block (PSL_UNSUPPORTED_TOP_LEVEL_BLOCK). The
descriptor-agnostic CST parser accepts any non-reserved keyword as a generic
block, so the walk now reproduces that allow-list:
- composedBlockKeywords() builds the legitimate-keyword set from
authoringContributions.pslBlockDescriptors (keys whose leaf
isAuthoringPslBlockDescriptor) — the exact source the legacy parser keyed on.
- Each top-level BlockSymbol whose keyword is absent from that set emits
PSL_UNSUPPORTED_TOP_LEVEL_BLOCK (message "Unsupported top-level block
"<keyword>"", span on the keyword token via the new keywordPslSpan helper so
the span stays single-line, matching the legacy createTrimmedLineSpan anchor).
Namespace-level blocks get the same treatment (enum-in-namespace keeps its
existing PSL_ENUM_NAMESPACE_NOT_SUPPORTED).
- enum reconstruction now runs only for legitimate enum blocks; an enum with no
pslBlockDescriptors.enum composed is rejected as unknown — reproducing the
legacy behaviour the interpreter.enum test asserts.
Models, composite types, namespaces, types {} blocks, and legitimately-composed
enum/extension blocks are not flagged (no over-rejection). The two previously-
failing dispatch-6 tests now pass with their ORIGINAL assertions; full suite
green (19 files / 277 tests). DoD grep stays empty.
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ons, review log Records slice 2 (migrate-sql-interpreter) completion: dispatch plan additions (5b/5c/6b), resolved Open Question #1 (pslBlockDescriptors rehomed to the interpreter walk), the two new project open items (doubled qualified-name codes; descriptor-typed block params for slice 3), and the reviewer round log through slice-2 DoD. Signed-off-by: Serhii Tatarintsev <[email protected]>
…er deletion) Slice 3 artifacts for TML-2929: migrate the Mongo interpreter onto the symbol table, fix the four out-of-package SQL consumers slice 2 left broken (slice-2 escapee), rework the printer round-trip tests off parsePslDocument, and delete the legacy parser. Workspace-wide validation gate (not package-scoped) to prevent recurrence of the escapee. Signed-off-by: Serhii Tatarintsev <[email protected]>
Slice 2 changed interpretPslDocumentToSqlContract from { document } to
{ symbolTable, sourceFile, sourceId }, but its package-scoped gate missed four
consumers outside @prisma-next/sql-contract-psl that still passed the old shape
and were red on the branch. Rewire each to parse(schema) + buildSymbolTable(...)
+ the new input (scalarTypes from the test's scalarTypeDescriptor keys),
mirroring slice 2's test/provider pattern:
- test/integration/.../parity/ts-psl-parity.real-packs.test.ts
- packages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.ts
- test/integration/.../psl-index-type-options.integration.test.ts
- test/integration/.../value-objects.integration.test.ts (SQL half only:
interpretSqlPsl; interpretMongoPsl left on parsePslDocument for dispatch 4)
Each test keeps its original assertions (clean mechanical input-shape rewire;
no assertion changed). Also fixes the stale signature in the SQL package README
(the only other site the { document } gate flagged \u2014 documentation, not a
consumer).
All four test files green; rg interpretPslDocumentToSqlContract\({ document
empty. No src/, Mongo interpreter, parser, or 9-family change; parsePslDocument
not deleted.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Mongo is a strict subset of SQL (models, composite types, fields, attributes, polymorphism — no namespaces, enums/extension blocks, named-types, or type constructors), so it gets its own package-local trimmed copy of slice 2s proven SQL adapters rather than a cross-package dependency: - cst-read.ts: readFieldTypeAnnotation (incl. the over-qualified malformed signal → PSL_INVALID_QUALIFIED_TYPE, same code as SQL), readAttribute + readAttributeView (verbatim arg-value rendering), and the span maps (nodePslSpan, rangeToPslSpan, offsetToPslPosition). readConstructorCall and keywordPslSpan excluded (no constructors / no top-level blocks in Mongo). - cst-read-views.ts: CstAttributeArgView, CstAttributeView, CstFieldView, CstModelView, CstCompositeTypeView. CstNamedTypeView / CstTypeConstructorCallView (and the fields constructor slot) excluded. - symbol-views.ts: buildFieldView, buildModelView, buildCompositeTypeView. buildNamedTypeView excluded. The trim was clean — Mongos field view needs nothing SQLs lacks; only the constructor/named-type surface was removed. Diagnostic codes/spans match the SQL adapters for cross-target parity. Unit tests mirror slice-2 dispatch-1 (trimmed): type-annotation splitting (bare/optional/list/dot-/colon-/over- qualified), attribute name + arg-value rendering parity, and buildModelView/buildFieldView/buildCompositeTypeView from symbol-table entries. Not wired into the Mongo interpreter yet (dispatch 3). No SQL package, parser, provider, or 9-family change. Mongo package suite green (157 tests). Signed-off-by: Serhii Tatarintsev <[email protected]>
Slice 3 dispatch 3 (mongo-interpreter-and-helpers): mirror the SQL
interpreter migration for Mongo (simpler — no namespaces/enums/named-types/
constructors).
- interpreter.ts: input changes from { document: ParsePslDocumentResult } to
{ symbolTable, sourceFile, sourceId, scalarTypeDescriptors, codecLookup };
the six document.ast.* walks now consume SymbolTable.topLevel +
buildModelView/buildCompositeTypeView; namespace-block rejection iterates
topLevel.namespaces (named namespaces only); resolveNonRelationField honours
the typeAlreadyReported cascade-guard to avoid spurious
PSL_UNSUPPORTED_FIELD_TYPE; all diagnostic codes preserved.
- psl-helpers.ts: retargeted onto CstAttributeView/CstAttributeArgView.
- provider.ts: thin // dispatch-4 bridge (parse + buildSymbolTable) to keep
src/ compiling; real combined-diagnostic seeding lands in dispatch 4.
src/ typecheck clean; interpreter-driven test suites red pending the
dispatch-4 test fan-out (adapter + view + provider + derive-json-schema
suites green); lint:deps green.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Slice 3 dispatch 4 (mongo-provider-and-tests). Provider real swap (provider.ts): turn the // dispatch-4 bridge into the real integration mirroring SQL dispatch-5/5c — parse + buildSymbolTable, with combined-diagnostic seeding (mapParseDiagnostics maps both parse().diagnostics and buildSymbolTable().diagnostics to ContractSourceDiagnostic and seeds them into the interpreter via seedDiagnostics, NOT a fail-before-interpret short-circuit). Interpreter (interpreter.ts): add seedDiagnostics input + diagnosticDedupKey/ dedupeDiagnostics helpers (mirroring SQL); seed the diagnostics array at construction and dedupe at the single post-walk notOk gate, so the combined parse + symbol-table + interpreter union surfaces in one run. Test fan-out: rewire the 2 red unit-test files (interpreter.test.ts, interpreter.polymorphism.test.ts) and the 3 Mongo-side integration/target consumers (migration-psl-authoring, value-objects Mongo half, mongo-runner.polymorphism) onto a shared parse + buildSymbolTable input. All assertions/codes preserved; the namespace tests assert the primary PSL_UNSUPPORTED_NAMESPACE_BLOCK rejection (the accepted D3 divergence), no secondary-cascade adjustment needed. mongo-contract-psl typecheck + full suite green (157/157, == pre-migration count); lint:deps green; no parsePslDocument in packages/2-mongo-family. Mongo-gated integration tests (describeWithMongoDB) skip in this env (no mongod binary) but typecheck clean and the non-gated assertions pass. Signed-off-by: Serhii Tatarintsev <[email protected]>
…xtures Slice 3 dispatch 5 (printer-roundtrip-rework), partial. Convert the 6 round-trip cases in print-psl-from-ast.test.ts that called parsePslDocument to hand-built PslDocumentAst fixtures (matching the file s existing 17 literals style), so the printer suite no longer depends on the legacy parser slated for deletion in dispatch 6: - @Map escape-sequence preservation (print-side: no double-escape) - small two-model schema with a relation - top-level __unspecified__ bucket without a namespace wrapper - mixed top-level + namespaced (top-level unwrapped, named ns wrapped) - alphabetical namespace ordering - cross-space colon-prefix relation field (supabase:auth.User?) The parse->print->parse symmetry cases keep their printer-side assertion (the printer s AST->text contract); the re-parse half tested the parser, which is being removed. print-psl-from-ast.test.ts is now fully off parsePslDocument. declarative-policy-select.round-trip.test.ts is NOT reworked here: it is predominantly a parse/validate/lower/resolve test of the descriptor-driven extension-block path (no symbol-table home), so hand-building its AST would launder real assertions into tautologies. Halt-condition hit; surfaced for an operator retire-vs-relocate decision (see report). psl-printer typecheck + suite green (46 tests); lint:deps green. Signed-off-by: Serhii Tatarintsev <[email protected]>
…on for policy_select) Corrects the E3 "no symbol-table home" premise: policy_select is a generic block, reconstructExtensionBlock produces the PslExtensionBlock the factory consumes, and validateExtensionBlock is a standalone framework function — so the descriptor-driven path reproduces at full FR12 parity. Dispatch 5d wires the validation pass over reconstructed blocks and migrates the policy-select round-trip test off parsePslDocument, rather than retiring it. Signed-off-by: Serhii Tatarintsev <[email protected]>
…policy_select test Slice 3 dispatch 5d (descriptor-validation-and-policy-select-test). policy_select is wireable, not unsupportable (E3 corrected): it is a generic block surfacing as a BlockSymbol, and validateExtensionBlock is a standalone framework function. So we wire it rather than retire the test. New @prisma-next/psl-parser module src/extension-block.ts (option a \u2014 shared, generic CST->PslExtensionBlock, layering-clean since psl-parser already depends on framework-components; the SQL package enum-block reconstruct is left untouched, so SQL behaviour is not reopened): - reconstructExtensionBlock(node, descriptor, sourceFile): descriptor-AWARE reconstruction that classifies each member into its ref/value/option/list/bare PslExtensionBlock param kind (the SQL enum-block reconstruct is descriptor-free and only yields bare/value, which the validator and the policy_select factory cannot consume). - findBlockDescriptor(namespace, keyword): resolve a descriptor by keyword. - validateExtensionBlockFromSymbol(...): reconstruct + build the ref-resolution context from the symbol table top-level models (so target = Post resolves) + run the framework validateExtensionBlock. Migrate declarative-policy-select.round-trip.test.ts off parsePslDocument to parse -> buildSymbolTable -> reconstruct -> validate / factory / print. All 9 assertions preserved, incl. PSL_EXTENSION_MISSING_REQUIRED_PARAMETER, PSL_EXTENSION_UNRESOLVED_REF, and PSL_EXTENSION_INVALID_VALUE (empty codec lookup); the print/round-trip re-parses through the same CST pipeline and compares lowered IR. Full parity, no gap. psl-parser + psl-printer typecheck clean; printer suite green (46 tests incl. all 10 policy-select); lint:deps green; printer fully off parsePslDocument. Signed-off-by: Serhii Tatarintsev <[email protected]>
Slice 3 dispatch 6 (delete-legacy-parser) \u2014 the final dispatch. Every consumer is now off parsePslDocument (both interpreters, the SQL stragglers, the printer tests), so the legacy parser is removed. Deleted: - src/parser.ts (the ~1640-line parsePslDocument implementation) - src/exports/parser.ts (sole export was parsePslDocument) - test/parser.test.ts + test/parser-enum.test.ts (legacy-parser-only tests) Pruned: - the parsePslDocument export line from src/exports/index.ts - the now-dead ParsePslDocumentInput / ParsePslDocumentResult type re-exports (zero barrel importers; the framework-components definitions stay) - the ./parser subpath from package.json exports + tsdown entry Kept (verified by per-symbol grep): src/attribute-helpers.ts (parseQuotedStringLiteral is shared), the entire CST path (parse.ts, symbol-table.ts, extension-block.ts, tokenizer.ts, source-file.ts, syntax/**), and all other Psl* type re-exports \u2014 PslSpan alone has 13 genuine barrel importers across the SQL + Mongo packages, so the convenience surface stays. Docs: parser README (Public API: parse + buildSymbolTable, /syntax subpath), SQL contract-psl README, ADR 163 (provider now calls parse + buildSymbolTable and seeds combined diagnostics). Reworded two code-file doc-comments so the slice-DoD grep is clean. Workspace gate: pnpm build (66/66) + pnpm typecheck (138/138) clean; test:packages green except the known mongodb-memory-server binary + CLI spawn-timeout env limitations (no type errors, psl-parser suite 349/349 green); test:integration 929 passed / 171 skipped, the 26 failed files all the mongod binary limitation (SQL/non-mongo green); lint:deps green (1090 modules); rg parsePslDocument across packages/ + test/ (non-md) is EMPTY. Closes slice migrate-mongo-and-remove-legacy-parser and project psl-cst-symbol-table (AC7-AC10). Signed-off-by: Serhii Tatarintsev <[email protected]>
…e, delete views) Signed-off-by: Serhii Tatarintsev <[email protected]>
Slice 4 (resolve-in-symbol-table) dispatch 1 \u2014 reverse project decision #4: centralize the resolution the SQL + Mongo packages each re-derive into views. New src/resolve.ts (the shared home, Open Question #1 working position) holds the proven resolution ported faithfully from the SQL cst-read.ts/symbol-views.ts: - resolveFieldTypeAnnotation: QualifiedNameAst split (typeName/typeNamespaceId/ typeContractSpaceId) + optional/list/isConstructor, with the over-qualified malformed signal. - readResolvedAttribute(s) + readResolvedConstructorCall: verbatim-source arg value rendering (printSyntax(...).trim()), dotted attribute names. - nodePslSpan/rangeToPslSpan: the Range -> PslSpan map. - ResolvedAttribute / ResolvedAttributeArg / ResolvedTypeConstructorCall. buildSymbolTable now resolves once: - FieldSymbol gains typeName/typeNamespaceId?/typeContractSpaceId?/optional/list/ typeConstructor?/attributes/malformedType?. Over-qualified field types emit PSL_INVALID_QUALIFIED_TYPE into the symbol-table diagnostics (a ParseDiagnostic, same code as before) and set malformedType (replacing the per-package typeAlreadyReported view flag). - ScalarSymbol/TypeAliasSymbol gain the resolved binding shape (baseType?/ typeConstructor?/isConstructor/attributes) via ResolvedNamedTypeBinding. - ModelSymbol/CompositeTypeSymbol gain their model/composite-level attributes. Faithful port: same diagnostic code, same span derivation, same verbatim arg rendering, same isConstructor gating \u2014 so D2/D3 are pure deletions + field-access rewires. The Resolved* types are exported from the package index. Tests: 11 new symbol-table resolution tests (qualified split bare/dot/colon/ over-qualified, optional/list, constructor, field+model+composite attributes, scalar-vs-alias resolved binding). psl-parser 361/361 green; typecheck clean; lint:deps green. Interpreter view layers untouched (deleted in D2/D3). Note for D2: CstFieldView declared a typeRef? field that symbol-views.ts never populated (always undefined from the view path); FieldSymbol omits it. The SQL helpers that read field.typeRef sourced it from a non-view path \u2014 D2 handles that sourcing. Signed-off-by: Serhii Tatarintsev <[email protected]>
…layer Slice 4 dispatch 2 (sql-consume-resolved-delete-views). psl-parser (option 1, approved): add declaration-level span: PslSpan to FieldSymbol/ModelSymbol/CompositeTypeSymbol/ScalarSymbol/TypeAliasSymbol/ NamespaceSymbol/BlockSymbol, populated as nodePslSpan(node.syntax, sourceFile) — a byte-faithful relocation of what the deleted view produced. Export the resolve.ts span maps + attribute/type readers (nodePslSpan, rangeToPslSpan, keywordPslSpan, readResolvedAttribute(s), readResolvedConstructorCall, resolveFieldTypeAnnotation) from the package index. New symbol-table test asserts the relocated declaration spans + verbatim function-call/array/ object-literal arg rendering. SQL contract-psl: the interpreter + helpers now read the resolved fields directly off the symbols (FieldSymbol/ModelSymbol/CompositeTypeSymbol/ ScalarSymbol|TypeAliasSymbol + ResolvedAttribute/ResolvedTypeConstructorCall) instead of building/consuming CstFieldView etc. The interpreter walk drops the view-build pass (pushes symbols directly; record fields iterated via Object.values); the typeAlreadyReported cascade-suppression now keys off FieldSymbol.malformedType; the dead field.typeRef reads (never populated by the view) are dropped undefined-equivalent. enum-block.ts re-points to psl-parser readResolvedAttribute (PslSpan args directly, dropping the Range->PslSpan re-map); provider.ts imports rangeToPslSpan from psl-parser. Deleted: cst-read-views.ts, symbol-views.ts, cst-read.ts, and test/cst-read.test.ts (the resolution it unit-tested moved to psl-parser, where equivalent coverage was added). PARITY: every diagnostic code AND span preserved (span is byte-identical — same nodePslSpan derivation relocated). psl-parser 363 green; SQL suite green with UNCHANGED assertions. SQL count is 261 (was 277): the 16-test drop is exactly the deleted cst-read.test.ts, whose resolution coverage relocated to psl-parser — a relocation, not a silent drop. lint:deps green; no Cst*View/buildFieldView/ symbol-views/cst-read-views references remain in the SQL package. Signed-off-by: Serhii Tatarintsev <[email protected]>
…iew layer Slice 4 dispatch 3 (mongo-consume-resolved-delete-views) - the mirror of D2 for Mongo. Mongo contract-psl: the interpreter + psl-helpers.ts now read the resolved fields directly off the symbol-table symbols (FieldSymbol.typeName/optional/ list/attributes/span/malformedType, ModelSymbol.attributes/span, CompositeTypeSymbol.attributes/span, ResolvedAttribute/ResolvedAttributeArg) instead of building/consuming the Mongo CstModelView/CstFieldView/ CstCompositeTypeView/CstAttributeView via buildModelView/symbol-views.ts. The interpreter walk drops the view-build pass (consumes Object.values(topLevel.*) directly); record fields are iterated via Object.values(...) where the view code iterated an array, and via keyed access (model.fields[name]) where it find-by-name'd. The resolveNonRelationField cascade-suppression now keys off FieldSymbol.malformedType (was the view typeAlreadyReported). Mongo never read field.typeRef, so no dead branch to drop. provider.ts imports rangeToPslSpan from psl-parser. Deleted: cst-read-views.ts, symbol-views.ts, cst-read.ts (the Mongo adapter copy - its field/attribute reading + span maps are in psl-parser resolve.ts), and test/cst-read.test.ts + test/symbol-views.test.ts (the adapter unit tests, whose resolution coverage relocated to psl-parser in D1). PARITY: every diagnostic code + span preserved (span byte-identical - the relocated nodePslSpan derivation). Mongo unit suite green with UNCHANGED assertions. Count is 137, was 157: the 20-test drop is exactly the deleted adapter tests (cst-read.test.ts 15 + symbol-views.test.ts 5), relocated to psl-parser - a relocation, not a silent drop. No describeWithMongoDB suites in this package, so no Mongo-gated skips here (CI/integration cover those). lint:deps green; no Cst*View/buildModelView/buildFieldView/symbol-views/ cst-read-views references remain in the Mongo package. Signed-off-by: Serhii Tatarintsev <[email protected]>
…n-in-symbol-table Slice 4 dispatch 4 (slice-dod-sweep), the final dispatch. Repo-wide view-name sweep is clean: rg for CstFieldView/CstModelView/ CstCompositeTypeView/CstNamedTypeView/CstAttributeView/CstAttributeArgView/ CstTypeConstructorCallView/buildFieldView/buildModelView/buildCompositeTypeView/ buildNamedTypeView/symbol-views/cst-read-views/cst-read across packages/ + test/ returns nothing - both interpreter packages views are fully deleted (D2/D3). Doc sweep: the psl-parser README buildSymbolTable bullet was stale (claimed qualified type references are left unresolved on field symbols). Updated to describe the resolved field/named-type shape buildSymbolTable now produces (split type, optional/list, typeConstructor, attributes, malformedType, the ScalarSymbol/TypeAliasSymbol binding, declaration span) and the new resolve.ts exports; noted there is no per-package field/attribute view layer. The two contract-psl READMEs already described parse + buildSymbolTable accurately (slice-3 work) and had no view-layer mentions. Slice DoD met: view layer gone repo-wide; workspace gate green modulo the known sandbox env limitations. pnpm build (66/66) + pnpm typecheck (138/138) clean; lint:deps green; the four slice-4 packages all green in isolation - psl-parser 363, sql-contract-psl 261, mongo-contract-psl 137, psl-printer 46. The 37 test:packages failures are all environmental: mongodb-memory-server cannot fetch a mongod binary on NixOS (the mongo-* suites) + CLI spawnSync subprocess timeouts (cli/cli-telemetry) + one parallel-load flake (extension-pgvector sql-renderer.cast-policy, which passes standalone). No new regression from the view removal. Signed-off-by: Serhii Tatarintsev <[email protected]>
…ol table, descriptors required) Signed-off-by: Serhii Tatarintsev <[email protected]>
…uired
Slice 5 dispatch 1 (resolve-blocks-in-buildSymbolTable) - the block-level
mirror of slice 4's field-resolution move. Block reconstruction returns to
buildSymbolTable (where parsePslDocument had it on main).
- BuildSymbolTableOptions gains a REQUIRED pslBlockDescriptors:
AuthoringPslBlockDescriptorNamespace. Block resolution cannot classify params
without it; every real caller has it (providers from
authoringContributions.pslBlockDescriptors; tests pass it explicitly).
- BlockSymbol gains block: PslExtensionBlock, populated by buildSymbolTable for
both top-level and namespace-nested blocks: findBlockDescriptor(descriptors,
keyword) -> reconstructExtensionBlock(node, descriptor, sourceFile,
diagnostics). Descriptor present -> kind = descriptor.discriminator with
ref/option/value/list classification; descriptor absent (unknown keyword) ->
kind = keyword, descriptor-free bare/value members. Duplicate members are
first-wins and flagged PSL_EXTENSION_DUPLICATE_PARAMETER into the symbol-table
diagnostics (parity with the legacy descriptor-driven parser and SQL's
enum-block.ts).
- MOVED reconstructExtensionBlock + reconstructParamValue +
reconstructFromExpression out of extension-block.ts into a new psl-parser
internal module block-reconstruction.ts (used by the symbol-table build).
The carried shape is PslExtensionBlock as-is (operator-noted temporary; the
leaner-shape question is a recorded follow-up, not redesigned here).
- extension-block.ts keeps findBlockDescriptor + validateExtensionBlockFromSymbol;
the latter now reads input.block.block (the already-reconstructed block)
instead of re-reconstructing. reconstructExtensionBlock is no longer exported
from the package index (it is internal to the build now).
- Updated all 13 buildSymbolTable call sites to pass pslBlockDescriptors: the 2
providers (context.authoringContributions.pslBlockDescriptors); the SQL
fixtures + Mongo test helpers + integration/extension tests ({} where no
blocks); the real-packs parity test (stack.authoringContributions.
pslBlockDescriptors); the printer policy_select test (assembled.
pslBlockDescriptors), whose reconstruct() now reads BlockSymbol.block.
SQL enum-block.ts reconstruction is NOT deleted yet (D2 does that once the SQL
factory path reads BlockSymbol.block). No behaviour change to the SQL enum path
this dispatch.
Gate: psl-parser typecheck + test green (368, +5 block-resolution tests:
enum/descriptor-typed/unknown-keyword/duplicate-member/namespace-nested);
sql-contract-psl + mongo-contract-psl + psl-printer typecheck clean and suites
green (261 / 137 / 46, unchanged - no behaviour drift); integration consumers
typecheck clean against the new required arg; lint:deps green. No caller lacked
descriptors (no STOP). reconstructExtensionBlock now lives in the symbol-table
build, not exported as the extension-block consumer entry.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Slice 5 dispatch 2 (consume-resolved-block-delete-enum-block), the final dispatch of the slice. The SQL enum factory path now reads the resolved PslExtensionBlock that buildSymbolTable produces (BlockSymbol.block, slice 5 D1) instead of reconstructing it locally. - interpreter.ts: the topLevelEnums walk maps each enum BlockSymbol to block.block (the descriptor-classified PslExtensionBlock) rather than calling SQL's reconstructExtensionBlock; ProcessEnumDeclarationsInput.enumBlocks is now readonly PslExtensionBlock[]. The enum factory consumes the same shape. - Deleted src/enum-block.ts (its reconstruction moved to psl-parser's block-reconstruction.ts in D1) and test/enum-block.test.ts (10 tests; reconstruction coverage relocated to psl-parser's D1 block-resolution tests). Test-fixtures fix (the load-bearing prerequisite): buildSymbolTableInput / symbolTableInputFromParseArgs now (a) thread pslBlockDescriptors into buildSymbolTable so BlockSymbol.block is descriptor-classified (the enum descriptor's discriminator + params), and (b) return buildSymbolTable's diagnostics as seedDiagnostics (mapped ParseDiagnostic -> ContractSourceDiagnostic via rangeToPslSpan, mirroring the provider) so the interpreter-driven tests see the same diagnostic set the real provider produces. Without this, deleting enum-block.ts would have dropped the duplicate-member PSL_EXTENSION_DUPLICATE_PARAMETER diagnostic. Corrected one stale test (operator-approved): interpreter.enum.test.ts "duplicate enum block names" asserted silent last-writer-wins (ok:true) - deleted-parser behaviour that contradicts the shipped provider path (provider.test.ts already asserts duplicate top-level declarations -> PSL_DUPLICATE_DECLARATION + ok:false) and operator decisions #2/#4 (duplicate names collide first-wins AND are flagged). Now asserts ok:false + PSL_DUPLICATE_DECLARATION, title/comment rewritten to the symbol-table first-wins-and-flag behaviour. No other assertion touched. PARITY: every diagnostic code + the emitted enum contract preserved (the block.block the factory gets is byte-identical to enum-block.ts's output, given the now-threaded enum descriptor); the duplicate-member PSL_EXTENSION_DUPLICATE_PARAMETER test passes via seedDiagnostics. SQL suite green (251, = 261 - 10 deleted enum-block.test.ts); psl-printer policy_select round-trip green unchanged. Slice DoD: pnpm build (66/66) + pnpm typecheck (138/138) clean; lint:deps green (1085 modules); rg 'reconstructExtensionBlock|enum-block' packages/2-sql packages/2-mongo-family empty. The four slice packages green in isolation: psl-parser 368, sql-contract-psl 251, mongo-contract-psl 137, psl-printer 46. The 43 test:packages failures are all environmental (mongodb-memory-server mongod-binary unavailable on NixOS; CLI spawnSync subprocess timeouts) - no new regression. Closes slice 5. Signed-off-by: Serhii Tatarintsev <[email protected]>
…duplicate diagnostics) Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…nebraker-b0e449 Resolved conflicts: - packages/2-sql/2-authoring/contract-psl/src/interpreter.ts: re-applied RLS extension-block lowering on top of #851's CST/symbol-table rewrite; lowerExtensionBlocksForNamespace updated to use NamespaceSymbol instead of PslNamespace; removed SqlAuthoringContributions (interface removed upstream); kept both AuthoringEntityTypeDescriptor and AuthoringPslBlockDescriptorNamespace - packages/2-sql/2-authoring/contract-psl/src/provider.ts: took origin/main (parsePslDocument call in HEAD was superseded by buildSymbolTable) - packages/2-sql/2-authoring/contract-psl/test/interpreter.extensions.test.ts: migrated two RLS extension tests to symbolTableInputFromParseArgs / new API; createNamespace now passed explicitly (target.authoring fallback removed) - pnpm-lock.yaml: regenerated via pnpm install Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…lTable API #851 removed parsePslDocument from @prisma-next/psl-parser. Update three test files that still used the old API: - psl-policy-authoring.test.ts: replace parsePslDocument + namespacePslExtensionBlocks with parse/buildSymbolTable, use NamespaceSymbol.blocks instead of PslNamespace - rls-lifecycle-e2e.integration.test.ts: same migration in buildContractFromPsl helper - rls-walking-skeleton-psl.integration.test.ts: same in buildPslContract helper Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ovider The interpreter no longer falls back to target.authoring.createNamespace (removed when the target type narrowed to the framework TargetPackRef during the #851 merge). That broke the PSL emit path for configs that lower extension entities (e.g. examples/supabase RLS policy) without explicitly passing createNamespace, surfacing as 'extension entities lowered but the target supplies no createNamespace factory'. Restore the fallback in the PSL provider: read createNamespace off the target pack's authoring descriptor (a typed view via blindCast, since the framework AuthoringContributions type does not declare this SQL-specific field) and pass it to the interpreter when the caller does not supply one explicitly. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Linked issue
Refs TML-2929
Branches off #849 (TML-2893, the CST parser
parse+ qualified-name/enum-block support), which is merged tomain.At a glance
PSL providers now build a resolved, scope-aware symbol table from the CST parser and hand that to the SQL and Mongo interpreters instead of the legacy line-based parser's pre-resolved AST:
Before this PR, both interpreters consumed
parsePslDocument's pre-resolvedPslDocumentAst. That parser — and its ~3.5k lines — is now gone; the CSTparseis the only parser in the package, andbuildSymbolTableowns the resolution layer the old parser used to provide.Decision
This PR carries four substantive pieces:
buildSymbolTable, co-located with the CSTparsein@prisma-next/psl-parser. It turns the CSTDocumentAstinto the keyed, scope-aware symbol table the interpreters need, rebuilt on the CST. It is fault-tolerant, keeps parser diagnostics separate from symbol-table diagnostics, and is the sole owner ofPSL_DUPLICATE_DECLARATIONfor same-name collisions (first-wins, collide-regardless-of-kind).@prisma-next/psl-parser: fields carry split qualified type references, optional/list/constructor state, rendered attributes, and malformed-type markers; scalar/type-alias bindings carry their resolved shape; block symbols carry descriptor-classifiedPslExtensionBlockvalues built with the requiredpslBlockDescriptorsinput.buildSymbolTable.parsePslDocumentdeleted — the function, its ~1.6k-line implementation, its./parserexport, and its ~1.8k lines of legacy tests. The legacyPslDocumentAsttypes stay because the introspection printer still consumes them; only the legacy parser is removed.How it fits together
Build the symbol table —
psl-parser/src/symbol-table.tswalks the CSTDocumentAst, buckets declarations into keyed records discriminated bykind, nests namespace members and block fields under their owner, classifiestypes {}bindings as scalar-vs-alias against the target'sscalarTypes, and emits duplicate-declaration diagnostics. Every symbol references its originating CST node.Resolve field and named-type shape once —
psl-parser/src/resolve.tscentralizes the qualified-name split, optional/list/constructor handling, attribute rendering, and malformed-type cascade guard that the SQL and Mongo packages used to duplicate in package-local view layers.Resolve extension blocks once —
psl-parser/src/block-reconstruction.tsreconstructs descriptor-classifiedPslExtensionBlockvalues forBlockSymbol.block;psl-parser/src/extension-block.tskeeps descriptor lookup and validation helpers. SQL now readsBlockSymbol.blockdirectly, so its oldenum-block.tsreconstruction is gone.Walk the table in each interpreter — SQL
interpreter.tsand Mongointerpreter.tsconsume the symbol table instead ofdocument.ast.namespaces, preserving every diagnostic code while removing the defensive duplicate-model throw and the interpreter-local diagnostic dedupe helpers that existed only because duplicate ownership was not yet clean.Wire the providers — SQL
provider.tsand Mongoprovider.tscallparse+buildSymbolTable, pass target scalar descriptors and block descriptors, seed both diagnostic lists into the interpreter, and emit the combined diagnostic set in one run (no fail-before-interpret short-circuit).Delete the legacy parser — with no consumer left,
parsePslDocumentand its tests are removed; the printer's round-trip tests are reworked to build their legacy AST inputs without it.Reviewer notes
parser.ts(−1642),parser.test.ts(−1507), andparser-enum.test.ts(−329). The PR is net negative overall. Spot-check the export prune inpsl-parser/src/exports/index.ts: onlyparsePslDocument/ParsePslDocumentInput/ParsePslDocumentResultand the dead parser subpath were removed; still-usedPsl*types remain exported.buildSymbolTable, matching the old parser's single-resolver shape and deleting the downstream duplication.parsediagnostics andbuildSymbolTablediagnostics remain separate at the source (deliberate), then providers seed both into the interpreter so callers see one combined result. There is no longer SQL/Mongo interpreter-local diagnostic dedupe; probe-backed validation showed it was collapsing nothing real afterbuildSymbolTablebecame the sole duplicate-declaration owner.policy_selectis preserved, not dropped. Descriptor-typed extension blocks reconstruct from the CST via the symbol table and are validated with the framework's standalonevalidateExtensionBlock. Thedeclarative-policy-select.round-trip.test.tsrework drives the realparse → buildSymbolTable → validate → factory → printpipeline over malformed text; its diagnostic assertions are real, not laundered.a.b.c) now surfaces bothPSL_INVALID_QUALIFIED_NAME(from the CST parser, native) andPSL_INVALID_QUALIFIED_TYPE(from symbol-table field resolution); legacy emitted only the latter. Both are accurate; collapsing to one remains a noted follow-up.Compatibility / migration / risk
contract.json/ IR shape change; this is a parser-and-interpreter-internal migration. The legacyPslDocumentAsttypes remain exported for the introspection printer.@prisma-next/psl-parser./parsersubpath export is removed. No code consumed it; downstream code should importparseandbuildSymbolTableinstead, and pass both target scalar types andpslBlockDescriptorswhen constructing a symbol table.buildSymbolTableis now the single place to look for duplicate-declaration ownership, field/named-type resolution, and block reconstruction. That reduces parity risk between SQL and Mongo, but it also makes symbol-table tests the primary coverage surface for resolution behavior.Testing performed
Latest validation on final pushed HEAD:
pnpm --filter @prisma-next/psl-parser test— clean: 12 files / 368 tests.pnpm --filter @prisma-next/sql-contract-psl test— clean: 17 files / 251 tests.pnpm --filter @prisma-next/mongo-contract-psl test— clean: 4 files / 137 tests.pnpm build— clean: 66/66 tasks.pnpm typecheck— clean: 138/138 tasks.pnpm lint:deps— clean.pnpm test:packages— attempted on final HEAD, but not green in this local environment: Mongo memory-server cannot resolve amongodbinary on NixOS (Unknown/unsupported linux "nixos" id_like's: []) and several CLI tests hit their 500ms timeout. This matches the already-recorded environmental class; CI with the proper Mongo/CLI environment should be used as the full package-suite authority.rg "throw new Error\(.*duplicate model" packages/2-sql/2-authoring/contract-psl/srcempty;rg "function dedupeDiagnostics" packagesempty.Follow-ups
PSL_INVALID_QUALIFIED_NAME+PSL_INVALID_QUALIFIED_TYPE) on over-qualified types to a single code — decide which layer owns the rejection (touches the shared CST parser).BlockSymbol.block: PslExtensionBlockis the right long-term carried shape, or whether the symbol table should expose a leaner resolved block representation. This PR restores single ownership of block reconstruction; it does not settle the long-term shape question.Alternatives considered
buildSymbolTableand deleted the adapters.BlockSymbol.blockbecame descriptor-classified at symbol-table construction. SQL now consumes the same resolved block shape as every other consumer.buildSymbolTable— rejected; keeping parser diagnostics and symbol-table diagnostics separate lets callers attribute whether a problem came from parsing or resolution while still surfacing both at the provider boundary.policy_selectround-trip test when it appeared to depend on the deleted parser — rejected; the capability was rebuildable on the CST, so we wired it rather than lose coverage.Checklist
TML-NNNN: …convention.Summary by CodeRabbit
PSL_DUPLICATE_DECLARATIONdiagnostics with first-wins behavior and reporting on the later declaration span.parse(...)+buildSymbolTable(...)pipeline.parsePslDocumententry points/subpath exports.