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

Draft: pretty-printer tests with randomly generated AST Expressions #1248

Open
wants to merge 15 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
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ src/func/funcfiftlib.js
**/grammar.ohm*.js
src/grammar/next/grammar.ts
jest.setup.js
jest.globalSetup.js
jest.teardown.js
/docs
version.build.ts
3 changes: 2 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@
"Ints",
"workchain",
"xffff",
"привет"
"привет",
"letrec"
],
"ignoreRegExpList": [
"\\b[xB]\\{[a-fA-F0-9]*_?\\}", // binary literals in Fift-asm
Expand Down
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ module.exports = {
testEnvironment: "node",
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
maxWorkers: "8",
globalSetup: "./jest.setup.js",
globalSetup: "./jest.globalSetup.js",
setupFiles: ["./jest.setup.js"],
globalTeardown: "./jest.teardown.js",
snapshotSerializers: ["@tact-lang/ton-jest/serializers"],
};
8 changes: 8 additions & 0 deletions jest.globalSetup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const coverage = require("@tact-lang/coverage");

module.exports = async () => {
if (process.env.COVERAGE === "true") {
coverage.beginCoverage();
}
};
55 changes: 49 additions & 6 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,51 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const coverage = require("@tact-lang/coverage");
const fc = require("fast-check");

module.exports = async () => {
if (process.env.COVERAGE === "true") {
coverage.beginCoverage();
function sanitizeObject(
obj,
options = {
excludeKeys: [],
valueTransformers: {},
},
) {
const { excludeKeys, valueTransformers } = options;

if (Array.isArray(obj)) {
return obj.map((item) => sanitizeObject(item, options));
} else if (obj !== null && typeof obj === "object") {
const newObj = {};
for (const [key, value] of Object.entries(obj)) {
if (!excludeKeys.includes(key)) {
const transformer = valueTransformers[key];
newObj[key] = transformer
? transformer(value)
: sanitizeObject(value, options);
}
}
return newObj;
}
};
return obj;
}

fc.configureGlobal({
reporter: (log) => {
if (log.failed) {
const sanitizedCounterexample = sanitizeObject(log.counterexample, {
excludeKeys: ["id", "loc"],
valueTransformers: {
value: (val) =>
typeof val === "bigint" ? val.toString() : val,
},
});

const errorMessage = `
Property failed after ${log.numRuns} tests
Seed: ${log.seed}
Path: ${log.counterexamplePath}
Counterexample: ${JSON.stringify(sanitizedCounterexample, null, 0)}
Errors: ${log.error ? log.error : "Unknown error"}
`;

throw new Error(errorMessage);
}
},
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"cross-env": "^7.0.3",
"cspell": "^8.8.3",
"eslint": "^8.56.0",
"fast-check": "^3.23.2",
"glob": "^8.1.0",
"husky": "^9.1.5",
"jest": "^29.3.1",
Expand Down
21 changes: 21 additions & 0 deletions src/test/prettyPrint/expressions.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import fc from "fast-check";
import { eqExpressions, getAstFactory } from "../../ast/ast";
import { prettyPrint } from "../../prettyPrinter";
import { getParser } from "../../grammar";
import { randomAstExpression } from "../utils/expression/randomAst";

describe("Pretty Print Expressions", () => {
const maxDepth = 3;

it(`should parse Ast`, () => {
fc.assert(
fc.property(randomAstExpression(maxDepth), (generatedAst) => {
const prettyBefore = prettyPrint(generatedAst);
const parser = getParser(getAstFactory(), "new");
const parsedAst = parser.parseExpression(prettyBefore);
expect(eqExpressions(generatedAst, parsedAst)).toBe(true);
}),
{ seed: 1, numRuns: 5000 },
);
});
});
260 changes: 260 additions & 0 deletions src/test/utils/expression/randomAst.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
import fc from "fast-check";
import {
AstBoolean,
AstConditional,
AstExpression,
AstFieldAccess,
AstId,
AstInitOf,
AstMethodCall,
AstNull,
AstNumber,
AstOpBinary,
AstOpUnary,
AstStaticCall,
AstString,
AstStructFieldInitializer,
AstStructInstance,
} from "../../../ast/ast";
import { dummySrcInfo } from "../../../grammar/src-info";

function dummyAstNode<T>(
generator: fc.Arbitrary<T>,
): fc.Arbitrary<T & { id: number; loc: typeof dummySrcInfo }> {
return generator.map((i) => ({
...i,
id: 0,
loc: dummySrcInfo,
}));
}

function randomAstBoolean(): fc.Arbitrary<AstBoolean> {
return dummyAstNode(
fc.record({
kind: fc.constant("boolean"),
value: fc.boolean(),
}),
);
}

function randomAstString(): fc.Arbitrary<AstString> {
const escapeString = (s: string): string =>
s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');

return dummyAstNode(
fc.record({
kind: fc.constant("string"),
value: fc.string().map((s) => escapeString(s)),
}),
);
}

function randomAstNumber(): fc.Arbitrary<AstNumber> {
const values = [
...Array.from({ length: 10 }, (_, i) => [0n, BigInt(i)]).flat(),
...Array.from({ length: 256 }, (_, i) => 1n ** BigInt(i)),
];

return dummyAstNode(
fc.record({
kind: fc.constant("number"),
base: fc.constantFrom(2, 8, 10, 16),
value: fc.oneof(...values.map((value) => fc.constant(value))),
}),
);
}

function randomAstOpUnary(
operand: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstOpUnary> {
return dummyAstNode(
fc.record({
kind: fc.constant("op_unary"),
op: fc.constantFrom("+", "-", "!", "!!", "~"),
operand: operand,
}),
);
}
function randomAstOpBinary(
leftExpression: fc.Arbitrary<AstExpression>,
rightExpression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstOpBinary> {
return dummyAstNode(
fc.record({
kind: fc.constant("op_binary"),
op: fc.constantFrom(
"+",
"-",
"*",
"/",
"!=",
">",
"<",
">=",
"<=",
"==",
"&&",
"||",
"%",
"<<",
">>",
"&",
"|",
"^",
),
left: leftExpression,
right: rightExpression,
}),
);
}

function randomAstConditional(
conditionExpression: fc.Arbitrary<AstExpression>,
thenBranchExpression: fc.Arbitrary<AstExpression>,
elseBranchExpression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstConditional> {
return dummyAstNode(
fc.record({
kind: fc.constant("conditional"),
condition: conditionExpression,
thenBranch: thenBranchExpression,
elseBranch: elseBranchExpression,
}),
);
}

function randomAstId(): fc.Arbitrary<AstId> {
return dummyAstNode(
fc.record({
kind: fc.constant("id"),
text: fc.stringMatching(/^[A-Za-z_][A-Za-z0-9_]*$/),
// Rules for text value are in src/grammar/grammar.ohm
}),
);
}

function randomAstCapitalizedId(): fc.Arbitrary<AstId> {
return dummyAstNode(
fc.record({
kind: fc.constant("id"),
text: fc.stringMatching(/^[A-Z]+$/),
// Rules for text value are in src/grammar/grammar.ohm
}),
);
}

function randomAstNull(): fc.Arbitrary<AstNull> {
return dummyAstNode(
fc.record({
kind: fc.constant("null"),
}),
);
}

function randomAstInitOf(
expression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstInitOf> {
return dummyAstNode(
fc.record({
kind: fc.constant("init_of"),
contract: randomAstId(),
args: fc.array(expression, { maxLength: 1 }),
}),
);
}

function randomAstStaticCall(
expression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstStaticCall> {
return dummyAstNode(
fc.record({
kind: fc.constant("static_call"),
function: randomAstId(),
args: fc.array(expression),
}),
);
}

function randomAstStructFieldInitializer(
expression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstStructFieldInitializer> {
return dummyAstNode(
fc.record({
kind: fc.constant("struct_field_initializer"),
field: randomAstId(),
initializer: expression,
}),
);
}

function randomAstStructInstance(
structFieldInitializer: fc.Arbitrary<AstStructFieldInitializer>,
): fc.Arbitrary<AstStructInstance> {
return dummyAstNode(
fc.record({
kind: fc.constant("struct_instance"),
type: randomAstCapitalizedId(),
args: fc.array(structFieldInitializer),
}),
);
}

function randomAstFieldAccess(
expression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstFieldAccess> {
return dummyAstNode(
fc.record({
kind: fc.constant("field_access"),
aggregate: expression,
field: randomAstId(),
}),
);
}

function randomAstMethodCall(
selfExpression: fc.Arbitrary<AstExpression>,
argsExpression: fc.Arbitrary<AstExpression>,
): fc.Arbitrary<AstMethodCall> {
return dummyAstNode(
fc.record({
self: selfExpression,
kind: fc.constant("method_call"),
method: randomAstId(),
args: fc.array(argsExpression),
}),
);
}

export function randomAstExpression(
maxDepth: number,
): fc.Arbitrary<AstExpression> {
// No weighted items
const baseExpressions = [
randomAstNumber(),
randomAstBoolean(),
randomAstId(),
randomAstNull(),
randomAstString(),
];

// More weighted items
return fc.memo((depth: number): fc.Arbitrary<AstExpression> => {
if (depth == 1) {
return fc.oneof(...baseExpressions);
}

const subExpr = () => randomAstExpression(depth - 1);

return fc.oneof(
...baseExpressions,
randomAstMethodCall(subExpr(), subExpr()),
randomAstFieldAccess(subExpr()),
randomAstStaticCall(subExpr()),
randomAstStructInstance(randomAstStructFieldInitializer(subExpr())),
randomAstInitOf(subExpr()),
randomAstOpUnary(subExpr()),
randomAstOpBinary(subExpr(), subExpr()),
randomAstConditional(subExpr(), subExpr(), subExpr()),
);
})(maxDepth);
}
Loading
Loading