-
Notifications
You must be signed in to change notification settings - Fork 0
/
nearleycompile_to_ts.sh
executable file
·49 lines (41 loc) · 1.48 KB
/
nearleycompile_to_ts.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/bash
readonly input=$1
readonly output=$2
set -e
[ "$input" == "" ] && {
echo "Missing first parameter (input file)"
exit 1
}
[ "$output" == "" ] && {
echo "Missing second parameter (output file)"
exit 1
}
cat <<EOT > /tmp/nearley.header.ts
// Edit the imports (top) and post-processing/exports (bottom) in nearleycompile_to_ts.sh
// Edit the grammar in src/searchDSL.ne
import nearley from 'nearley';
import { simplify } from './simpleSerializer';
EOT
npx --no-install nearleyc $input \
| sed "3d;5s/^var/const/" \
| grep -B 99999999999999 "if (typeof module !== 'undefined" \
| grep -v "if (typeof module !== 'undefined" \
> /tmp/nearley.body.ts
cat <<EOT > /tmp/nearley.footer.ts
export function parse(query: string, options: { ignoreAmbiguity?: boolean } = {}) {
if (query.match(/^\s*$/)) { return { type: 'yes' }; }
const nearleyParser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
nearleyParser.feed(query);
if (nearleyParser.results.length < 1) {
throw new Error('Failed to parse. \n' + query);
}
if (!options.ignoreAmbiguity && nearleyParser.results.length > 1) {
const summary = 'Bad bad bad. Grammar is ambiguous -- query has multiple valid interpretations';
const details = nearleyParser.results.map(simplify).map(x => ' - ' + x).join('\n');
const message = summary + ':\n' + query + '\n' + details;
throw new Error(message);
}
return nearleyParser.results[0];
}
EOT
cat /tmp/nearley.{header,body,footer}.ts > $output