Debian Codegraph @

test/nearleyc.test.js

raw ◀ ▶
Source reconstructed at patch state 0 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1
2 const fs = require('fs');
3 const expect = require('expect');
4
5 const nearley = require('../lib/nearley');
6 const {compile, evalGrammar, parse, nearleyc} = require('./_shared');
7 const {sh, externalNearleyc, cleanup} = require('./external');
8
9 function read(filename) {
10 return fs.readFileSync(filename, 'utf-8');
11 }
12
13 function write(filename, contents) {
14 fs.writeFileSync(filename, contents, 'utf-8');
15 }
16
17 function prettyPrint(grammar) {
18 return grammar.rules.map(g => g.toString())
19 }
20
21 function typeScriptCheck(isStrict) {
22 const {outPath, stdout, stderr} = externalNearleyc("grammars/typescript-test.ne", ".ts");
23 expect(stderr).toBe("");
24 expect(stdout).toBe("");
25 const spawnSync = sh(`tsc ${isStrict ? "--strict" : ""} ${outPath}.ts`);
26 expect(spawnSync.stdout).toBe(""); // type errors get logged to stdout, not stderr
27 const grammar = nearley.Grammar.fromCompiled(require(`./${outPath}.js`).default);
28 expect(parse(grammar, "<123>")).toEqual([ [ '<', '123', '>' ] ]);
29 }
30
31
32 describe("bin/nearleyc", function() {
33 after(cleanup)
34
35 it('builds for ES5', function() {
36 const {outPath, stdout, stderr} = externalNearleyc("grammars/parens.ne", '.js');
37 expect(stderr).toBe("");
38 expect(stdout).toBe("");
39 const grammar = nearley.Grammar.fromCompiled(require(`./${outPath}.js`));
40 });
41
42 it('builds for ES6+', function() {
43 this.timeout(10000); // It takes a while to run babel!
44
45 const {outPath, stdout, stderr} = externalNearleyc("grammars/esmodules-test.ne", '.js');
46 expect(stderr).toBe("");
47 expect(stdout).toBe("");
48 write(`test/${outPath}-parse.js`, `import {Grammar, Parser} from '../lib/nearley'
49 import compiledGrammar from './${outPath}'
50
51 const grammar = Grammar.fromCompiled(compiledGrammar)
52 const parser = new Parser(grammar)
53 parser.feed('<4>')
54 console.log(JSON.stringify(parser.results))`);
55
56 {
57 const {stderr, stdout} = sh(`babel-node ${outPath}-parse.js --presets=env`);
58 expect(stderr).toBe("");
59 expect(JSON.parse(stdout)).toEqual([ [ '<', '4', '>' ] ]);
60 }
61 });
62
63 it('builds for CoffeeScript', function() {
64 const {outPath, stdout, stderr} = externalNearleyc("grammars/coffeescript-test.ne", ".coffee");
65 expect(stderr).toBe("");
66 expect(stdout).toBe("");
67 sh(`coffee -c ${outPath}.coffee`);
68 const grammar = nearley.Grammar.fromCompiled(require(`./${outPath}.js`));
69 expect(parse(grammar, "ABCDEFZ12309")).toEqual([ [ 'ABCDEFZ', '12309' ] ]);
70 });
71
72 it('builds for TypeScript', function() {
73 this.timeout(10000); // It takes a while to run tsc!
74 typeScriptCheck(false);
75 });
76
77 it('builds for TypeScript with `--strict` with no type errors', function() {
78 this.timeout(10000);
79 typeScriptCheck(true);
80 });
81
82 it('builds modules in folders', function() {
83 const {outPath, stdout, stderr} = externalNearleyc("grammars/folder-test.ne", '.js');
84 expect(stderr).toBe("");
85 expect(stdout).toBe("");
86 const grammar = nearley.Grammar.fromCompiled(require(`./${outPath}.js`));
87 });
88
89 it('builds modules with multiple includes of the same file', function() {
90 const {outPath, stdout, stderr} = externalNearleyc("grammars/multi-include-test.ne", '.js');
91 expect(stderr).toBe("");
92 expect(stdout).toBe("");
93 const grammar = nearley.Grammar.fromCompiled(require(`./${outPath}.js`));
94 });
95
96 it("warns about undefined symbol", function () {
97 const {stdout, stderr} = externalNearleyc("grammars/warning-undefined-test.ne", '.js');
98 expect(stderr).toNotBe("");
99 expect(stdout).toBe("");
100 });
101
102 it("doesn't warn when used with the --quiet option", function () {
103 const {stdout, stderr} = externalNearleyc("grammars/warning-undefined-test.ne", '.js', ['--quiet']);
104 expect(stderr).toBe("");
105 expect(stdout).toBe("");
106 });
107
108 it("allows trailing comments without newline terminators", function () {
109 const {stdout, stderr} = externalNearleyc("grammars/trailing-comment.ne", '.js');
110 expect(stderr).toBe("");
111 });
112
113
114 })
115
116 describe('nearleyc: example grammars', function() {
117
118 it('calculator example', function() {
119 const arith = compile(read("examples/calculator/arithmetic.ne"));
120 expect(parse(arith, "ln (3 + 2*(8/e - sin(pi/5)))")).toEqual([ Math.log(3 + 2*(8/Math.exp(1) - Math.sin(Math.PI/5))) ]);
121 });
122
123 it('csscolor example', function() {
124 const cssc = compile(read("examples/csscolor.ne"));
125 expect(parse(cssc, "#FF00FF")).toEqual([{r: 0xff, g: 0x00, b: 0xff}]);
126 expect(parse(cssc, "#8A7")).toEqual([{r: 0x88, g: 0xaa, b: 0x77}]);
127 expect(parse(cssc, "rgb(99,66,33)")).toEqual([{r: 99, g: 66, b: 33}]);
128 expect(parse(cssc, "hsl(99,66,33)")).toEqual([{h: 99, s: 66, l: 33}]);
129 expect(function() { parse(cssc, "#badcolor"); }).toThrow()
130 });
131
132 it('exponential whitespace bug', function() {
133 compile(read('test/grammars/indentation.ne'));
134 });
135
136 it('percent bug', function() {
137 compile(read('test/grammars/percent.ne'));
138 });
139
140 it('json', function() {
141 const grammar = compile(read("examples/json.ne"));
142 expect(prettyPrint(grammar)).toEqual([
143 'json$subexpression$1 → object',
144 'json$subexpression$1 → array',
145 'json → _ json$subexpression$1 _',
146 'object → "{" _ "}"',
147 'object$ebnf$1 → ',
148 'object$ebnf$1$subexpression$1 → _ "," _ pair',
149 'object$ebnf$1 → object$ebnf$1 object$ebnf$1$subexpression$1',
150 'object → "{" _ pair object$ebnf$1 _ "}"',
151 'array → "[" _ "]"',
152 'array$ebnf$1 → ',
153 'array$ebnf$1$subexpression$1 → _ "," _ value',
154 'array$ebnf$1 → array$ebnf$1 array$ebnf$1$subexpression$1',
155 'array → "[" _ value array$ebnf$1 _ "]"',
156 'value → object',
157 'value → array',
158 'value → number',
159 'value → string',
160 'value → "true"',
161 'value → "false"',
162 'value → "null"',
163 'number → %number',
164 'string → %string',
165 'pair → key _ ":" _ value',
166 'key → string',
167 '_ → ',
168 '_ → %space',
169 ])
170 });
171
172 it('classic crontab', function() {
173 // Try compiling the grammar
174 const classicCrontab = compile(read("examples/classic_crontab.ne"));
175 // Try parsing crontab file using the newly generated parser
176 const crontabTest = read('test/grammars/classic_crontab.test');
177 const crontabResults = read('test/grammars/classic_crontab.results');
178 expect(parse(classicCrontab, crontabTest)).toEqual([JSON.parse(crontabResults)]);
179 });
180
181 it('case-insensitive strings', function() {
182 const caseinsensitive = compile(read("test/grammars/caseinsensitive.ne"));
183 const passCases = [
184 "Les rêves des amoureux sont comme le bon vin!",
185 "LES RÊVES DES AMOUREUX SONT COMME LE BON VIN!",
186 "leS RêVeS DeS AmOuReUx sOnT CoMmE Le bOn vIn!",
187 "LEs rÊvEs dEs aMoUrEuX SoNt cOmMe lE BoN ViN!"
188 ];
189 passCases.forEach(function(c) {
190 const p = parse(caseinsensitive, c);
191 expect(p.length).toBe(1)
192 expect(p[0].toUpperCase()).toBe(passCases[1]);
193 });
194 });
195
196 it('scannerless nearley grammar', function() {
197 compile(read("test/grammars/scannerless-nearley.ne"));
198 })
199
200 });
201
202 describe('nearleyc: builtins', () => {
203
204 it('generate includes id', () => {
205 const source = nearleyc(`
206 X -> "hat" {% id %}
207 `)
208 expect(source.indexOf('function id(')).toNotBe(-1)
209 const g = evalGrammar(source)
210 expect(parse(g, "hat")).toEqual(["hat"])
211 })
212
213 // TODO fix docs?
214 it.skip('nuller', () => {
215 //@builtin "postprocessors.ne"
216 const source = nearleyc(`
217 ws -> " " {% nuller %}
218 `)
219 const g = evalGrammar(source)
220 expect(parse(g, " ")).toEqual([null])
221 })
222 })
223
224 describe('nearleyc: macros', () => {
225
226 it('seems to work', () => {
227 // Matches "'Hello?' 'Hello?' 'Hello?'"
228 const grammar = compile(`
229 matchThree[X] -> $X " " $X " " $X
230 inQuotes[X] -> "'" $X "'"
231 main -> matchThree[inQuotes["Hello?"]]
232 `);
233
234 expect(prettyPrint(grammar)).toEqual([
235 'main$macrocall$2$macrocall$2$string$1 → "H" "e" "l" "l" "o" "?"',
236 'main$macrocall$2$macrocall$2 → main$macrocall$2$macrocall$2$string$1',
237 'main$macrocall$2$macrocall$1 → "\'" main$macrocall$2$macrocall$2 "\'"',
238 'main$macrocall$2 → main$macrocall$2$macrocall$1',
239 'main$macrocall$1 → main$macrocall$2 " " main$macrocall$2 " " main$macrocall$2',
240 'main → main$macrocall$1',
241 ]);
242 });
243
244 it('must be defined before use', () => {
245 expect(() => compile(`
246 main -> matchThree[inQuotes["Hello?"]]
247 matchThree[X] -> $X " " $X " " $X
248 inQuotes[X] -> "'" $X "'"
249 `)).toThrow();
250 });
251
252 it('compiles a simple macro from external file', function() {
253 const grammar = compile(read("test/grammars/macro-test.ne"));
254 const passCases = [
255 "a",
256 "b",
257 "a/b",
258 "b/a",
259 ];
260 passCases.forEach(function(c) {
261 const p = parse(grammar, c);
262 expect(p.length).toBe(1);
263 expect(p[0]).toBe("a/b");
264 });
265 expect(() => parse(grammar, "ab")).toThrow();
266 });
267
268 })