Skip to content

fix: support string literal keys for object expressions in ZModel #752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/language/src/generated/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ export function isEnumField(item: unknown): item is EnumField {
export interface FieldInitializer extends AstNode {
readonly $container: ObjectExpr;
readonly $type: 'FieldInitializer';
name: RegularID
name: RegularID | string
value: Expression
}

Expand Down
22 changes: 17 additions & 5 deletions packages/language/src/generated/grammar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1171,11 +1171,23 @@ export const ZModelGrammar = (): Grammar => loadedZModelGrammar ?? (loadedZModel
"feature": "name",
"operator": "=",
"terminal": {
"$type": "RuleCall",
"rule": {
"$ref": "#/rules@47"
},
"arguments": []
"$type": "Alternatives",
"elements": [
{
"$type": "RuleCall",
"rule": {
"$ref": "#/rules@47"
},
"arguments": []
},
{
"$type": "RuleCall",
"rule": {
"$ref": "#/rules@67"
},
"arguments": []
}
]
}
},
{
Expand Down
2 changes: 1 addition & 1 deletion packages/language/src/zmodel.langium
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ ObjectExpr:
'}';

FieldInitializer:
name=RegularID ':' value=(Expression);
name=(RegularID | STRING) ':' value=(Expression);

InvocationExpr:
function=[FunctionDecl] '(' ArgumentList? ')';
Expand Down
2 changes: 1 addition & 1 deletion packages/schema/tests/schema/stdlib.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { SchemaLoadingError } from '../utils';
import { NodeFileSystem } from 'langium/node';
import path from 'path';
import { URI } from 'vscode-uri';
import { createZModelServices } from '../../src/language-server/zmodel-module';
import { SchemaLoadingError } from '../utils';

describe('Stdlib Tests', () => {
it('stdlib', async () => {
Expand Down
8 changes: 5 additions & 3 deletions packages/schema/tests/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Model } from '@zenstackhq/language/ast';
import { Model } from '@zenstackhq/sdk/ast';
import * as fs from 'fs';
import { NodeFileSystem } from 'langium/node';
import * as path from 'path';
Expand All @@ -18,7 +18,7 @@ export async function loadModel(content: string, validate = true, verbose = true
fs.writeFileSync(docPath, content);
const { shared } = createZModelServices(NodeFileSystem);
const stdLib = shared.workspace.LangiumDocuments.getOrCreateDocument(
URI.file(path.resolve('src/res/stdlib.zmodel'))
URI.file(path.resolve(__dirname, '../../schema/src/res/stdlib.zmodel'))
);
const doc = shared.workspace.LangiumDocuments.getOrCreateDocument(URI.file(docPath));

Expand Down Expand Up @@ -60,7 +60,9 @@ export async function loadModelWithError(content: string, verbose = false) {
try {
await loadModel(content, true, verbose);
} catch (err) {
expect(err).toBeInstanceOf(SchemaLoadingError);
if (!(err instanceof SchemaLoadingError)) {
throw err;
}
return (err as SchemaLoadingError).errors;
}
throw new Error('No error is thrown');
Expand Down
13 changes: 10 additions & 3 deletions packages/sdk/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,17 @@ export function resolved<T extends AstNode>(ref: Reference<T>): T {
export function getLiteral<T extends string | number | boolean | any = any>(
expr: Expression | ConfigExpr | undefined
): T | undefined {
if (!isLiteralExpr(expr)) {
return getObjectLiteral<T>(expr);
switch (expr?.$type) {
case 'ObjectExpr':
return getObjectLiteral<T>(expr);
case 'StringLiteral':
case 'BooleanLiteral':
return expr.value as T;
case 'NumberLiteral':
return parseFloat(expr.value) as T;
default:
return undefined;
}
return expr.value as T;
}

export function getArray(expr: Expression | ConfigExpr | undefined) {
Expand Down
2 changes: 2 additions & 0 deletions packages/testtools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
"@zenstackhq/runtime": "workspace:*",
"@zenstackhq/sdk": "workspace:*",
"json5": "^2.2.3",
"langium": "1.2.0",
"pg": "^8.11.1",
"tmp": "^0.2.1",
"vscode-uri": "^3.0.6",
"zenstack": "workspace:*"
},
"devDependencies": {
Expand Down
3 changes: 2 additions & 1 deletion packages/testtools/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './schema';
export * from './db';
export * from './model';
export * from './schema';
69 changes: 69 additions & 0 deletions packages/testtools/src/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Model } from '@zenstackhq/sdk/ast';
import * as fs from 'fs';
import { NodeFileSystem } from 'langium/node';
import * as path from 'path';
import * as tmp from 'tmp';
import { URI } from 'vscode-uri';
import { createZModelServices } from 'zenstack/language-server/zmodel-module';
import { mergeBaseModel } from 'zenstack/utils/ast-utils';

export class SchemaLoadingError extends Error {
constructor(public readonly errors: string[]) {
super('Schema error:\n' + errors.join('\n'));
}
}

export async function loadModel(content: string, validate = true, verbose = true) {
const { name: docPath } = tmp.fileSync({ postfix: '.zmodel' });
fs.writeFileSync(docPath, content);
const { shared } = createZModelServices(NodeFileSystem);
const stdLib = shared.workspace.LangiumDocuments.getOrCreateDocument(
URI.file(path.resolve(__dirname, '../../schema/src/res/stdlib.zmodel'))
);
const doc = shared.workspace.LangiumDocuments.getOrCreateDocument(URI.file(docPath));

if (doc.parseResult.lexerErrors.length > 0) {
throw new SchemaLoadingError(doc.parseResult.lexerErrors.map((e) => e.message));
}

if (doc.parseResult.parserErrors.length > 0) {
throw new SchemaLoadingError(doc.parseResult.parserErrors.map((e) => e.message));
}

await shared.workspace.DocumentBuilder.build([stdLib, doc], {
validationChecks: validate ? 'all' : 'none',
});

const validationErrors = (doc.diagnostics ?? []).filter((e) => e.severity === 1);
if (validationErrors.length > 0) {
for (const validationError of validationErrors) {
if (verbose) {
const range = doc.textDocument.getText(validationError.range);
console.error(
`line ${validationError.range.start.line + 1}: ${validationError.message}${
range ? ' [' + range + ']' : ''
}`
);
}
}
throw new SchemaLoadingError(validationErrors.map((e) => e.message));
}

const model = (await doc.parseResult.value) as Model;

mergeBaseModel(model);

return model;
}

export async function loadModelWithError(content: string, verbose = false) {
try {
await loadModel(content, true, verbose);
} catch (err) {
if (!(err instanceof SchemaLoadingError)) {
throw err;
}
return (err as SchemaLoadingError).errors;
}
throw new Error('No error is thrown');
}
49 changes: 45 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 40 additions & 0 deletions tests/integration/tests/regression/issue-744.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { getObjectLiteral } from '@zenstackhq/sdk';
import { Plugin, PluginField, isPlugin } from '@zenstackhq/sdk/ast';
import { loadModel } from '@zenstackhq/testtools';

describe('Regression: issue 744', () => {
it('regression', async () => {
const model = await loadModel(
`
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

plugin zod {
provider = '@core/zod'
settings = {
'200': { status: 'ok' },
'x-y-z': 200,
foo: 'bar'
}
}

model Foo {
id String @id @default(cuid())
}
`
);

const plugin = model.declarations.find((d): d is Plugin => isPlugin(d));
const settings = plugin?.fields.find((f): f is PluginField => f.name === 'settings');
const value: any = getObjectLiteral(settings?.value);
expect(value['200']).toMatchObject({ status: 'ok' });
expect(value['x-y-z']).toBe(200);
expect(value.foo).toBe('bar');
});
});