Skip to content

add an option to generate a partial ast definition #1854

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions packages/langium-cli/langium-config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@
"langiumInternal": {
"description": "A flag to determine whether langium uses itself to bootstrap",
"type": "boolean"
},
"generatePartialAst": {
"description": "Generate a partial AST with optional properties (usefull to access the parsed AST with an incomplete document)",
"type": "boolean"
}
},
"required": [
Expand Down
9 changes: 6 additions & 3 deletions packages/langium-cli/src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { loadConfig } from './package.js';
import { AstUtils, GrammarAST } from 'langium';
import { createLangiumGrammarServices, resolveImport, resolveImportUri, resolveTransitiveImports } from 'langium/grammar';
import { NodeFileSystem } from 'langium/node';
import { generateAst } from './generator/ast-generator.js';
import { generateAst, generateAstPartial } from './generator/ast-generator.js';
import { serializeGrammar } from './generator/grammar-serializer.js';
import { generateModule } from './generator/module-generator.js';
import { generateBnf } from './generator/bnf-generator.js';
Expand Down Expand Up @@ -327,7 +327,7 @@ export async function runGenerator(config: LangiumConfig, options: GenerateOptio
const output = path.resolve(relPath, config.out ?? 'src/generated');
log('log', options, `Writing generated files to ${chalk.white.bold(output)}`);

if (await rmdirWithFail(output, ['ast.ts', 'grammar.ts', 'module.ts'], options)) {
if (await rmdirWithFail(output, ['ast.ts', 'ast-partial.ts', 'grammar.ts', 'module.ts'], options)) {
return buildResult(false);
}
if (await mkdirWithFail(output, options)) {
Expand All @@ -336,7 +336,10 @@ export async function runGenerator(config: LangiumConfig, options: GenerateOptio

const genAst = generateAst(grammarServices, embeddedGrammars, config);
await writeWithFail(path.resolve(updateLangiumInternalAstPath(output, config), 'ast.ts'), genAst, options);

if(config.generatePartialAst) {
const genAstPartial = generateAstPartial(grammarServices, embeddedGrammars, config);
await writeWithFail(path.resolve(updateLangiumInternalAstPath(output, config), 'ast-partial.ts'), genAstPartial, options);
}
const serializedGrammar = serializeGrammar(grammarServices, embeddedGrammars, config);
await writeWithFail(path.resolve(output, 'grammar.ts'), serializedGrammar, options);

Expand Down
43 changes: 41 additions & 2 deletions packages/langium-cli/src/generator/ast-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import { collectAst, collectTypeHierarchy, findReferenceTypes, isAstType, mergeT
import { generatedHeader } from './node-util.js';
import { collectKeywords, collectTerminalRegexps } from './langium-util.js';

export function generateAst(services: LangiumCoreServices, grammars: Grammar[], config: LangiumConfig): string {
export function generateAst(services: LangiumCoreServices, grammars: Grammar[], config: LangiumConfig,): string {
const astTypes = collectAst(grammars, services.shared.workspace.LangiumDocuments);
const importFrom = config.langiumInternal ? `../../syntax-tree${config.importExtension}` : 'langium';

/* eslint-disable @typescript-eslint/indent */
const fileNode = expandToNode`
${generatedHeader}
Expand All @@ -25,7 +26,7 @@ export function generateAst(services: LangiumCoreServices, grammars: Grammar[],
${generateTerminalConstants(grammars, config)}

${joinToNode(astTypes.unions, union => union.toAstTypesString(isAstType(union.type)), { appendNewLineIfNotEmpty: true })}
${joinToNode(astTypes.interfaces, iFace => iFace.toAstTypesString(true), { appendNewLineIfNotEmpty: true })}
${joinToNode(astTypes.interfaces, iFace => iFace.toAstTypesString(true, false), { appendNewLineIfNotEmpty: true })}
${
astTypes.unions = astTypes.unions.filter(e => isAstType(e.type)),
generateAstReflection(config, astTypes)
Expand All @@ -34,6 +35,30 @@ export function generateAst(services: LangiumCoreServices, grammars: Grammar[],
return toString(fileNode);
/* eslint-enable @typescript-eslint/indent */
}
export function generateAstPartial(services: LangiumCoreServices, grammars: Grammar[], config: LangiumConfig,): string {
const astTypes = collectAst(grammars, services.shared.workspace.LangiumDocuments);
const importFrom = config.langiumInternal ? `../../syntax-tree${config.importExtension}` : 'langium';

/* eslint-disable @typescript-eslint/indent */
const fileNode = expandToNode`
${generatedHeader}

/* eslint-disable */
import * as langium from '${importFrom}';
import * as ast from './ast.js';

${generateTerminalConstantsPartial(grammars, config)}

${joinToNode(astTypes.unions, union => union.toAstTypesString(isAstType(union.type), true), { appendNewLineIfNotEmpty: true })}
${joinToNode(astTypes.interfaces, iFace => iFace.toAstTypesString(true, true), { appendNewLineIfNotEmpty: true })}
${
astTypes.unions = astTypes.unions.filter(e => isAstType(e.type)),
generateAstReflectionPartial(config, astTypes)
}
`;
return toString(fileNode);
/* eslint-enable @typescript-eslint/indent */
}

function generateAstReflection(config: LangiumConfig, astTypes: AstTypes): Generated {
const typeNames: string[] = astTypes.interfaces.map(t => t.name)
Expand Down Expand Up @@ -68,6 +93,14 @@ function generateAstReflection(config: LangiumConfig, astTypes: AstTypes): Gener
`.appendNewLine();
}

function generateAstReflectionPartial(config: LangiumConfig, _astTypes: AstTypes): Generated {

return expandToNode`

export type { ${config.projectName}AstType, ${config.projectName}AstReflection } from './ast.js';
export const reflection = ast.reflection;
`.appendNewLine();
}
function buildTypeMetaDataMethod(astTypes: AstTypes): Generated {
/* eslint-disable @typescript-eslint/indent */
return expandToNode`
Expand Down Expand Up @@ -252,3 +285,9 @@ function generateTerminalConstants(grammars: Grammar[], config: LangiumConfig):
export type ${config.projectName}TokenNames = ${config.projectName}TerminalNames | ${config.projectName}KeywordNames;
`.appendNewLine();
}

function generateTerminalConstantsPartial(grammars: Grammar[], config: LangiumConfig): Generated {
return expandToNode`
export { ${config.projectName}Terminals, type ${config.projectName}TerminalNames, type ${config.projectName}KeywordNames, type ${config.projectName}TokenNames } from './ast.js';
`.appendNewLine();
}
2 changes: 2 additions & 0 deletions packages/langium-cli/src/package-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export interface LangiumConfig {
chevrotainParserConfig?: IParserConfig,
/** The following option is meant to be used only by Langium itself */
langiumInternal?: boolean
/** Generate a partial AST with optional properties (usefull to access the parsed AST with an incomplete document) */
generatePartialAst?: boolean
}

export interface LangiumLanguageConfig {
Expand Down
28 changes: 18 additions & 10 deletions packages/langium/src/grammar/type-system/type-collector/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,14 @@ export class UnionType {
this.dataType = options?.dataType;
}

toAstTypesString(reflectionInfo: boolean): string {
toAstTypesString(reflectionInfo: boolean, isPartial?: boolean): string {
const unionNode = expandToNode`
export type ${this.name} = ${propertyTypeToString(this.type, 'AstType')};
`.appendNewLine();

if (reflectionInfo) {
unionNode.appendNewLine()
.append(addReflectionInfo(this.name));
.append(addReflectionInfo(this.name, isPartial));
}

if (this.dataType) {
Expand Down Expand Up @@ -218,7 +218,7 @@ export class InterfaceType {
this.abstract = abstract;
}

toAstTypesString(reflectionInfo: boolean): string {
toAstTypesString(reflectionInfo: boolean, isPartial?: boolean): string {
const interfaceSuperTypes = this.interfaceSuperTypes.map(e => e.name);
const superTypes = interfaceSuperTypes.length > 0 ? distinctAndSorted([...interfaceSuperTypes]) : ['langium.AstNode'];
const interfaceNode = expandToNode`
Expand All @@ -233,15 +233,15 @@ export class InterfaceType {
body.append(`readonly $type: ${distinctAndSorted([...this.typeNames]).map(e => `'${e}'`).join(' | ')};`).appendNewLine();
}
body.append(
pushProperties(this.properties, 'AstType')
pushProperties(this.properties, 'AstType', isPartial)
);
});
interfaceNode.append('}').appendNewLine();

if (reflectionInfo) {
interfaceNode
.appendNewLine()
.append(addReflectionInfo(this.name));
.append(addReflectionInfo(this.name, isPartial));
}

return toString(interfaceNode);
Expand All @@ -253,7 +253,7 @@ export class InterfaceType {
return toString(
expandToNode`
interface ${name}${superTypes.length > 0 ? ` extends ${superTypes}` : ''} {
${pushProperties(this.properties, 'DeclaredType', reservedWords)}
${pushProperties(this.properties, 'DeclaredType', false, reservedWords)}
}
`.appendNewLine()
);
Expand Down Expand Up @@ -408,12 +408,13 @@ function typeParenthesis(type: PropertyType, name: string): string {
function pushProperties(
properties: Property[],
mode: 'AstType' | 'DeclaredType',
isPartial?: boolean,
reserved = new Set<string>()
): Generated {

function propertyToString(property: Property): string {
const name = mode === 'AstType' ? property.name : escapeReservedWords(property.name, reserved);
const optional = property.optional && !isMandatoryPropertyType(property.type);
const optional = !isMandatoryPropertyType(property.type) && property.defaultValue === undefined && (property.optional || isPartial);
const propType = propertyTypeToString(property.type, mode);
return `${name}${optional ? '?' : ''}: ${propType};`;
}
Expand All @@ -440,14 +441,21 @@ export function isMandatoryPropertyType(propertyType: PropertyType): boolean {
}
}

function addReflectionInfo(name: string): Generated {
return expandToNode`
function addReflectionInfo(name: string, isPartial?: boolean): Generated {
return (isPartial ?
expandToNode`
export const ${name} = ast.${name};

export function is${name}(item: unknown): item is ${name} {
return reflection.isInstance(item, ${name});
}
`: expandToNode`
export const ${name} = '${name}';

export function is${name}(item: unknown): item is ${name} {
return reflection.isInstance(item, ${name});
}
`.appendNewLine();
`).appendNewLine();
}

function addDataTypeReflectionInfo(union: UnionType): Generated {
Expand Down