Skip to content
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

Add --parse-only flag #492

Merged
merged 10 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
5 changes: 5 additions & 0 deletions apps/interpreter/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ program
`Sets the target blocks of the of block debug logging, separated by comma. If not given, all blocks are targeted.`,
undefined,
)
.option(
'-po, --parse-only',
'Only parses the model without running it. Exits with 0 if the model is valid, with 1 otherwise.',
false,
)
.description('Run a Jayvee file')
.action(runAction);

Expand Down
103 changes: 103 additions & 0 deletions apps/interpreter/src/parse-only.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// SPDX-FileCopyrightText: 2023 Friedrich-Alexander-Universitat Erlangen-Nurnberg
//
// SPDX-License-Identifier: AGPL-3.0-only

import * as fs from 'node:fs/promises';
import * as os from 'os';
import * as path from 'path';
import * as process from 'process';

import {
clearBlockExecutorRegistry,
clearConstraintExecutorRegistry,
} from '@jvalue/jayvee-execution/test';
import {
RunOptions,
interpretModel,
interpretString,
} from '@jvalue/jayvee-interpreter-lib';

import { runAction } from './run-action';

jest.mock('@jvalue/jayvee-interpreter-lib', () => {
const original: object = jest.requireActual('@jvalue/jayvee-interpreter-lib'); // Step 2.
joluj marked this conversation as resolved.
Show resolved Hide resolved
return {
...original,
interpretModel: jest.fn(),
interpretString: jest.fn(),
};
});

describe('Parse Only', () => {
const baseDir = path.resolve(__dirname, '../../../example/');
const pathToValidModel = path.resolve(baseDir, 'cars.jv');

const defaultOptions: RunOptions = {
env: new Map<string, string>(),
debug: false,
debugGranularity: 'minimal',
debugTarget: undefined,
};

let tempFile: string | undefined = undefined;

afterEach(async () => {
if (tempFile != null) {
await fs.rm(tempFile);
// eslint-disable-next-line require-atomic-updates
tempFile = undefined;
}
});

afterEach(() => {
// Assert that model is not executed
expect(interpretString).not.toBeCalled();
expect(interpretModel).not.toBeCalled();
});

beforeEach(() => {
jest.clearAllMocks();
jest.spyOn(process, 'exit').mockImplementation(() => {
throw new Error();
});

// Reset jayvee specific stuff
clearBlockExecutorRegistry();
clearConstraintExecutorRegistry();
});

it('should exit with 0 on a valid option', async () => {
await expect(
runAction(pathToValidModel, {
...defaultOptions,
joluj marked this conversation as resolved.
Show resolved Hide resolved
parseOnly: true,
}),
).rejects.toBeDefined();

expect(process.exit).toBeCalledTimes(1);
joluj marked this conversation as resolved.
Show resolved Hide resolved
expect(process.exit).toHaveBeenCalledWith(0);
});

it('should exit with 1 on error', async () => {
joluj marked this conversation as resolved.
Show resolved Hide resolved
const validModel = (await fs.readFile(pathToValidModel)).toString();

tempFile = path.resolve(
os.tmpdir(),
// E.g. "0.gn6v6ra9575" -> "gn6v6ra9575.jv"
Math.random().toString(36).substring(2) + '.jv',
);

// Write a partial valid model in that file
joluj marked this conversation as resolved.
Show resolved Hide resolved
await fs.writeFile(tempFile, validModel.substring(validModel.length / 2));

await expect(
runAction(tempFile, {
...defaultOptions,
parseOnly: true,
}),
).rejects.toBeDefined();

expect(process.exit).toBeCalledTimes(1);
expect(process.exit).toHaveBeenCalledWith(1);
});
});
8 changes: 8 additions & 0 deletions apps/interpreter/src/run-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
//
// SPDX-License-Identifier: AGPL-3.0-only

import * as process from 'process';

import {
LoggerFactory,
RunOptions,
extractAstNodeFromFile,
interpretModel,
parseModel,
} from '@jvalue/jayvee-interpreter-lib';
import { JayveeModel, JayveeServices } from '@jvalue/jayvee-language-server';

Expand All @@ -23,6 +26,11 @@ export async function runAction(
services,
loggerFactory.createLogger(),
);
if (options.parseOnly === true) {
const { model, services } = await parseModel(extractAstNodeFn, options);
const exitCode = model != null && services != null ? 0 : 1;
process.exit(exitCode);
}
const exitCode = await interpretModel(extractAstNodeFn, options);
process.exit(exitCode);
}
50 changes: 41 additions & 9 deletions libs/interpreter-lib/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

import { strict as assert } from 'assert';

import * as R from '@jvalue/jayvee-execution';
import {
DebugGranularity,
ExecutionContext,
Logger,
NONE,
Expand All @@ -15,7 +17,6 @@ import {
registerDefaultConstraintExecutors,
useExtension as useExecutionExtension,
} from '@jvalue/jayvee-execution';
import * as R from '@jvalue/jayvee-execution';
import { StdExecExtension } from '@jvalue/jayvee-extensions/std/exec';
import {
BlockDefinition,
Expand All @@ -33,9 +34,9 @@ import {
import * as chalk from 'chalk';
import { NodeFileSystem } from 'langium/node';

import { LoggerFactory } from './logging/logger-factory';
import { LoggerFactory } from './logging';
import { ExitCode, extractAstNodeFromString } from './parsing-util';
import { validateRuntimeParameterLiteral } from './validation-checks/runtime-parameter-literal';
import { validateRuntimeParameterLiteral } from './validation-checks';

interface InterpreterOptions {
debugGranularity: R.DebugGranularity;
Expand All @@ -48,6 +49,7 @@ export interface RunOptions {
debug: boolean;
debugGranularity: string;
debugTarget: string | undefined;
parseOnly?: boolean;
}

export async function interpretString(
Expand All @@ -66,13 +68,25 @@ export async function interpretString(
return await interpretModel(extractAstNodeFn, options);
}

export async function interpretModel(
/**
* Parses a model without executing it.
* Also sets up the environment so that the model can be properly executed.
*
* @returns non-null model, services and loggerFactory on success.
*/
export async function parseModel(
extractAstNodeFn: (
services: JayveeServices,
loggerFactory: LoggerFactory,
) => Promise<JayveeModel>,
options: RunOptions,
): Promise<ExitCode> {
): Promise<{
model: JayveeModel | null;
loggerFactory: LoggerFactory;
services: JayveeServices | null;
}> {
let services: JayveeServices | null = null;
let model: JayveeModel | null = null;
const loggerFactory = new LoggerFactory(options.debug);
if (!isDebugGranularity(options.debugGranularity)) {
loggerFactory
Expand All @@ -83,23 +97,40 @@ export async function interpretModel(
', ',
)}.`,
);
return ExitCode.FAILURE;
return { model, services, loggerFactory };
}

useStdExtension();
registerDefaultConstraintExecutors();

const services = createJayveeServices(NodeFileSystem).Jayvee;
services = createJayveeServices(NodeFileSystem).Jayvee;
await initializeWorkspace(services);
setupJayveeServices(services, options.env);

let model: JayveeModel;
try {
model = await extractAstNodeFn(services, loggerFactory);
return { model, services, loggerFactory };
} catch (e) {
loggerFactory
.createLogger()
.logErr('Could not extract the AST node of the given model.');
return { model, services, loggerFactory };
}
}

export async function interpretModel(
extractAstNodeFn: (
services: JayveeServices,
loggerFactory: LoggerFactory,
) => Promise<JayveeModel>,
options: RunOptions,
): Promise<ExitCode> {
const { model, services, loggerFactory } = await parseModel(
extractAstNodeFn,
options,
);

if (model == null || services == null) {
return ExitCode.FAILURE;
}

Expand All @@ -111,7 +142,8 @@ export async function interpretModel(
loggerFactory,
{
debug: options.debug,
debugGranularity: options.debugGranularity,
// type of options.debugGranularity is asserted in parseModel
debugGranularity: options.debugGranularity as DebugGranularity,
debugTargets: debugTargets,
},
);
Expand Down
Loading