@adrianepi/constant-folding
Version:
96 lines (86 loc) • 3.12 kB
JavaScript
const constantFolding = require('../src/constant-folding');
const should = require('chai').should();
const fs = require('fs');
const simpleExamples = [
{ text: `var f = 3+null;`, result: `var f = 3;\n`},
{ text: `var e = 4 | 3;`, result: `var e = 7;\n`},
{ text: `var d = 3+"c";`, result: `var d = 3c;\n`},
{ text: `var b = 9 +1;`, result: `var b = 10;\n`},
{ text: `var a = 2+3*5+b;`, result: `var a = 17 + b;\n`}
];
const arrayExamples = [
{ text: `[a, b, c].concat([d, e], f, g, [h]);`, result: `[ a, b, c, d, e, f, g, h];\n`},
{ text: `["a", "b", "c"].join();`, result: `"a,b,c";\n`},
{ text: `["a", "b", "c"].join('@');`, result: `"a@b@c";\n`},
{ text: `[1, 2, 3].length;`, result: `3;\n`},
{ text: `[1, 2, 3][2-1];`, result: `2;\n`},
{ text: `[1, 2, 3].shift();`, result: `1;\n`},
{ text: `[1, 2, 3].slice(0, 1+1);`, result: `[ 1, 2];\n`},
{ text: `[a, b, c].pop();`, result: `c;\n`},
{ text: `[a, b, c].reverse();`, result: `[ c, b, a];\n`},
];
const stringExamples = [
{ text: `"abc"[0];`, result: `"a";\n`},
{ text: `"abc".charAt();`, result: `"a";\n`},
{ text: `"abc".charAt(1);`, result: `"b";\n`},
{ text: `"abc".length;`, result: `3;\n`},
{ text: `"a,b,c".split(",");`, result: `[ "a", "b", "c" ];\n`},
];
describe('ConstantFolding simple tests', () => {
for (let c of simpleExamples) {
it('Testing ' + c.text, () => {
constantFolding(c.text, '-j').should .equal(c.result);
});
}
});
describe('ConstantFolding array tests', () => {
for (let c of arrayExamples) {
it('Testing ' + c.text, () => {
constantFolding(c.text, '-j').should .equal(c.result);
});
}
});
describe('ConstantFolding string tests', () => {
for (let c of stringExamples) {
it('Testing ' + c.text, () => {
constantFolding(c.text, '-j').should .equal(c.result);
});
}
});
describe('ConstantFolding AST tests', () => {
it('Testing example1 AST', () => {
const input = readFile("examples/example1.js");
const output = readFile("examples/outputAST1.json");
constantFolding(input, '-a').should .equal(output);
});
it('Testing example2 AST', () => {
const input = readFile("examples/example2.js");
const output = readFile("examples/outputAST2.json");
constantFolding(input, '-a').should .equal(output);
});
it('Testing example3 AST', () => {
const input = readFile("examples/example3.js");
const output = readFile("examples/outputAST3.json");
constantFolding(input, '-a').should .equal(output);
});
// it('Testing example3 with deb', () => {
// const input = readFile("examples/example3.js");
// const output = readFile("examples/outputJS3.js");
// constantFolding(input, '-d').should .equal(output);
// });
});
/**
* Reads a file.
*
* @param {string} input_file The input file
* @return {string} String with the content of the file.
*/
function readFile(input_file) {
let program = fs.readFileSync(input_file, 'utf8', (err, input) => {
if (err) {
console.log("Couldn't read the file: " + err);
return;
}
});
return program;
}