-
Notifications
You must be signed in to change notification settings - Fork 5
/
ambiguityCheck.js
1894 lines (1688 loc) · 65.9 KB
/
ambiguityCheck.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Usage
* node ambiguityCheck [options]
*
* Description
* Finds and prints instances of ambiguity in the grammar.
*
* Ambiguity exists if multiple paths exist to the same rightmost symbols, and the resulting
* semantic trees and/or display texts are indistinguishable. If ambiguity is found among a pair
* of paths, prints the parse trees, semantic trees, and display texts for those paths to show
* the necessary changes to make to the grammar
*
* This module was a massive undertaking. All 32 cases of possible ambiguity are meticulously
* documented in detail in 'ambiguityTests.js'. Many algorithms were created and ensured to
* catch all possible ambiguous cases. Several algorithms, unique data structures, and
* heuristics were developed to make the construction of all possible paths and the comparison
* of paths as fast as possible. Many trials and errors. It was well over 100 hours of arduous
* research and development.
*
* Options
* -n, --tree-sym-limit The maximum number of symbols permitted in the construction of a path
* when searching for ambiguity, limiting processing time. This bound is
* necessary, as the grammar permits paths of infinite length and
* combination. [default: 9]
* -c, --complete-trees Require parse trees to completely reduce, with no nonterminal symbols
* remaining to parse, to be examined for ambiguity. This yields output
* that can be easier to understand, however, requires a greater
* `--tree-sym-limit` value than otherwise to find the same instances of
* ambiguity. [boolean] [default: true]
* -a, --find-all Find every distinct pair of ambiguous trees instead of one instance per
* each pair of rules. Often, this is superfluous for determining the
* necessary changes to make to the grammar. This can be helpful, however,
* as the grammatical change required might not be in a root rule, but
* rather in a subsequent rule only demonstrated when used with this root
* rule. For certain cases with `--find-all`, such as recursive rules
* (i.e., a rule whose RHS contains the LHS), an excessive number of
* ambiguity instances are printed. [boolean]
* -s, --semantic-check Check every path for illegal semantics when forcefully and completely
* reduced (i.e., reduced irrespective of parsing state and semantic
* argument requirements). This exposes illegal semantics that should be
* detected and discarded earlier. [boolean]
* -t, --test-rules Replace the grammar with the ambiguous test rules, defined and
* documented in 'ambiguityTests.js', to check the accuracy of this
* algorithm. [boolean]
* -q, --quiet Suppress program output. [boolean]
* -h, --help Display this screen. [boolean]
*/
var util = require('../../util/util')
var yargs = require('yargs')
var argv = yargs
.usage([
util.colors.bold('Usage'),
' node $0 [options]',
'',
util.colors.bold('Description'),
' Finds and prints instances of ambiguity in the grammar.',
'',
' Ambiguity exists if multiple paths exist to the same rightmost symbols, and the resulting semantic trees and/or display texts are indistinguishable. If ambiguity is found among a pair of paths, prints the parse trees, semantic trees, and display texts for those paths to show the necessary changes to make to the grammar',
'',
' This module was a massive undertaking. All 32 cases of possible ambiguity are meticulously documented in detail in \'ambiguityTests.js\'. Many algorithms were created and ensured to catch all possible ambiguous cases. Several algorithms, unique data structures, and heuristics were developed to make the construction of all possible paths and the comparison of paths as fast as possible. Many trials and errors. It was well over 100 hours of arduous research and development.',
].join('\n'))
.updateStrings({
'Options:': util.colors.bold('Options'),
})
.options({
'n': {
alias: 'tree-sym-limit',
description: 'The maximum number of symbols permitted in the construction of a path when searching for ambiguity, limiting processing time. This bound is necessary, as the grammar permits paths of infinite length and combination.',
requiresArg: true,
default: 9,
},
'c': {
alias: 'complete-trees',
description: 'Require parse trees to completely reduce, with no nonterminal symbols remaining to parse, to be examined for ambiguity. This yields output that can be easier to understand, however, requires a greater `--tree-sym-limit` value than otherwise to find the same instances of ambiguity.',
type: 'boolean',
default: true,
},
'a': {
alias: 'find-all',
description: 'Find every distinct pair of ambiguous trees instead of one instance per each pair of rules. Often, this is superfluous for determining the necessary changes to make to the grammar. This can be helpful, however, as the grammatical change required might not be in a root rule, but rather in a subsequent rule only demonstrated when used with this root rule. For certain cases with `--find-all`, such as recursive rules (i.e., a rule whose RHS contains the LHS), an excessive number of ambiguity instances are printed.',
type: 'boolean',
},
's': {
alias: 'semantic-check',
description: 'Check every path for illegal semantics when forcefully and completely reduced (i.e., reduced irrespective of parsing state and semantic argument requirements). This exposes illegal semantics that should be detected and discarded earlier.',
type: 'boolean',
},
't': {
alias: 'test-rules',
description: 'Replace the grammar with the ambiguous test rules, defined and documented in \'ambiguityTests.js\', to check the accuracy of this algorithm.',
type: 'boolean',
},
'q': {
alias: 'quiet',
description: 'Suppress program output.',
type: 'boolean',
},
})
.help('h', 'Display this screen.').alias('h', 'help')
.check(function (argv, options) {
if (isNaN(argv.treeSymLimit)) {
throw 'TypeError: \'--tree-sym-limit\' is not a number: ' + argv.treeSymLimit
}
if (argv.testRules && argv.treeSymLimit < 9) {
throw 'Error: \'--tree-sym-limit\' must be >= 9 when passing \'--test-rules\''
}
return true
})
// Fail on unrecognized arguments.
.strict()
.wrap(Math.min(yargs.terminalWidth(), 95))
.argv
// Modify stack trace format to stylize output when printing.
util.prettifyStackTrace()
var semantic = require('../grammar/semantic')
// If `--test-rules` is passed, use the ambiguous test rules to check the
// accuracy of this algorithm.
var grammar = argv.testRules ? require('./ambiguityTests') : require('../grammar.json')
/**
* Initialize the semantics of rules in `grammar` for parsing by replacing
* identical semantic functions, semantic nodes, and semantic arrays with
* references to the same object.
*/
require('../parse/initSemantics')(grammar.ruleSets, grammar.semantics)
var ruleSets = grammar.ruleSets
util.time('Ambiguity check')
/**
* Do not inspect transpositions because any ambiguity they create is
* evident in the original rules from which they were derived. Remove rules
* to avoid checking each rule multiple times within the recrusive function,
* `buildPath()`.
*/
deleteTranspositionRules(ruleSets)
// The found instances of ambiguity (to sort and print at end).
var ambiguityToPrint = []
// Construct all possible paths from `nontermSym`.
for (var nontermSym in ruleSets) {
searchPaths(nontermSym)
}
if (!argv.quiet) {
printFoundAmbiguity(ambiguityToPrint)
}
if (argv.testRules) {
util.logSuccess('All tests passed.')
}
util.log('Tree symbols limit:', argv.treeSymLimit)
util.timeEnd('Ambiguity check')
util.countEndAll()
/**
* Checks for ambiguity created by `nontermSym`'s rules. Compares paths
* created by each rule from `nontermSym` to paths created by `nontermSym`'s
* other rules. Does not compare paths that the same initial rule produces
* because if ambiguity exists there, then it is caused by another symbol.
*
* Initializes the paths from `nontermSym`, but calls `buildPath()` to
* recursively expand the paths.
*
* @private
* @static
* @param {string} nontermSym The nonterminal symbol from which to search for
* ambiguity.
*/
function searchPaths(nontermSym) {
// The rules `nontermSym` produces from which to expand.
var rules = ruleSets[nontermSym]
var rulesLen = rules.length
/**
* Exit if `nontermSym` produces only one (non-transposition) rule because
* at least two rules are required for ambiguity to exist.
*
* If `--semantic-check` is `true`, then build and inspect every path.
*/
if (!argv.semanticCheck && rulesLen === 1) return
/**
* The store of all paths from `nontermSym`. Each index contains a set of
* arrays of paths, one set for each rule from `nontermSym`. Each set is a
* map of terminal strings to the arrays of paths.
*/
var pathTab = []
var rootPath = {
// The previous symbol whose rules this path can expand from.
curSym: undefined,
/**
* The linked list of yet-to-parse second nodes of previous binary rules
* and conjugative text objects of previous insertion rules. When
* `curSym` is `undefined` after reaching a terminal symbol, inspect
* `nextItemList` to complete the binary rules and conjugate the text
* objects.
*/
nextItemList: undefined,
// The reverse linked list of yet-to-reduce semantics.
semanticList: undefined,
// The path's display text.
text: [],
// The reverse linked list of person-number properties to conjugate text
// objects.
personNumberList: undefined,
// The grammatical properties to conjugate text of terminal rules in
// `curNode.subs`.
gramProps: undefined,
// The string of terminal symbols in this path.
terminals: '',
// The number of symbols used by this path, to ensure below `--tree-sym-
// limit`.
symCount: 1,
// The path's RHS symbols. Combines with `prev` to form a reverse linked
// list from which to construct a path's parse tree graph
// representation.
rule: { rhs: [ nontermSym ] },
// The pointer to the previous path. This is used by
// `linkedListToGraph()` to construct a parse tree graph representation
// from this path.
prev: undefined,
}
for (var r = 0; r < rulesLen; ++r) {
/**
* Paths each root rule of `nontermSym` produces are stored in separate
* sets of paths. Those sets map strings of terminal symbols to arrays
* of paths.
*/
var pathSets = {}
pathTab.push(pathSets)
/**
* Recursively construct all possible expansions of `rootPath` using
* this rule, and add the new paths to `pathTab` for use by
* `findAmbiguity()` will use to search for ambiguous pairs.
*/
buildPath(pathSets, rootPath, rules[r])
}
// Search for ambiguity after constructing all paths.
if (!argv.semanticCheck) {
findAmbiguity(pathTab)
}
}
/**
* Recursively constructs all possible expansions of `prevPath` using `rule`,
* which its rightmost nonterminal symbol produced. Adds the new paths to
* `pathSets` for use by `findAmbiguity()` to search for ambiguous pairs.
*
* @private
* @static
* @param {Object} pathSets The map of terminal strings to arrays of paths for
* a single root rule that produced `prevPath`.
* @param {Object} prevPath The path to expand.
* @param {Object} rule The rule with which to expand `prevPath`.
*/
function buildPath(pathSets, prevPath, rule) {
// Create a new path by expanding `prevPath` with one of its productions,
// `rule`.
var newPath = createPath(prevPath, rule)
// Discard if semantically illegal parse.
if (newPath === -1) return
/**
* If `--semantic-check` is `true`, then check every path for illegal //
* semantics when forcefully and completely reduced (i.e., reduced
* irrespective of parsing state and semantic argument requirements). This
* exposes illegal semantics that should be detected and discarded
* earlier.
*/
if (argv.semanticCheck && completeSemanticTree(newPath.semanticList, newPath) === -1) {
return
}
/**
* Add new path to set of paths from this root rule with these terminal
* symbols.
*
* `--complete-trees` specifies only examining completely-reduced parse
* trees.
*/
if (!argv.completeTrees || !newPath.curSym) {
var paths = pathSets[newPath.terminals]
if (paths) {
paths.push(newPath)
} else {
pathSets[newPath.terminals] = [ newPath ]
}
}
/**
* If the path has not reached all terminal symbols (i.e., has a
* `curSym`), and is below `--tree-sym-limit` (otherwise will build
* infinite paths), then continue to expand path.
*/
if (newPath.curSym && newPath.symCount < argv.treeSymLimit) {
// The rules `newPath.curSym` produces from which to expand.
var rules = ruleSets[newPath.curSym]
var rulesLen = rules.length
// Recursively expand `newPath`.
for (var r = 0; r < rulesLen; ++r) {
buildPath(pathSets, newPath, rules[r])
}
}
}
/**
* Creates a new path by expanding `prevPath` with `rule`.
*
* @private
* @static
* @param {Object} prevPath The previous path from which to expand.
* @param {Object} rule The rule `prevPath`'s last symbol produces.
* @returns {Object|number} Returns the new path if semantically legal, else
* `-1`.
*/
function createPath(prevPath, rule) {
var prevNextItemList = prevPath.nextItemList
var newPath = {
// The previous symbol whose rules this path can expand from.
curSym: undefined,
/**
* The linked list of yet-to-parse second nodes of previous binary rules
* and conjugative text objects of previous insertion rules. When
* `curSym` is `undefined` after reaching a terminal symbol, inspect
* `nextItemList` to complete the binary rules and conjugate the text
* objects.
*/
nextItemList: prevPath.nextItemList,
// The reverse linked list of yet-to-reduce semantics.
semanticList: undefined,
// The path's display text.
text: prevPath.text,
// The reverse linked list of person-number properties to conjugate text
// objects.
personNumberList: prevPath.personNumberList,
// The grammatical properties to conjugate text of terminal rules in
// `curNode.subs`.
gramProps: undefined,
// The string of terminal symbols in this path.
terminals: prevPath.terminals,
// The number of symbols used by this path excluding `<blank>`, to ensure
// below `--tree-sym-limit`.
symCount: prevPath.symCount + (rule.insertedSymIdx === undefined ? rule.rhs.length : 1),
// The path's RHS symbols. Combines with `prev` to form a reverse linked
// list from which to construct a path's parse tree graph representation.
rule: rule,
// The pointer to the previous path. This is used by `linkedListToGraph()`
// to construct a parse tree graph representation from this path.
prev: prevPath,
}
// Nonterminal rule.
if (!rule.isTerminal && !rule.rhsDoesNotProduceText) {
// Append `rule`'s semantics, if any, to `prevPath.semanticList`.
newPath.semanticList = appendSemantic(prevPath.semanticList, prevNextItemList ? prevNextItemList.symCount : 0, rule)
// Discard if semantically illegal parse.
if (newPath.semanticList === -1) return -1
// The next nonterminal symbol this path can expand from.
newPath.curSym = rule.rhs[0]
/**
* The grammatical properties (`case`, `tense`, and `acceptedTense`)
* used to conjugate terminal rules `newPath.curNode` (and its sibling
* node if binary) produces. Only occurs on nonterminal rules.
*/
newPath.gramProps = rule.gramProps
// Append person-number property to linked list for conjugation of next
// terminal symbol if it is a verb.
if (rule.personNumber) {
var nextItemListSize = prevNextItemList ? prevNextItemList.size : -1
var prev = prevPath.personNumberList
newPath.personNumberList = {
// The person-number property for conjugation.
personNumber: rule.personNumber,
/**
* The number of items in `newPath.nextItemList` at the position of
* the person-number property's definition in the parse tree. Used
* to determine if the following branches, which are associated with
* this person-number property, are complete and that this property
* can conjugate any successive terminal symbols for verbs.
*/
nextItemListSize: nextItemListSize,
// The previous person-number property, not saved if for a previously
// completed subtree.
prev: prev && prev.nextItemListSize <= nextItemListSize ? prev : undefined,
}
}
// Non-edit rule.
if (rule.insertedSymIdx === undefined) {
if (rule.rhs.length === 2) {
/**
* All binary rules are nonterminal rules. Prepend the second RHS
* symbol to `nextItemList`, and complete the rule after completing
* the branch the first RHS symbol produces.
*/
if (prevNextItemList) {
newPath.nextItemList = {
// The second symbol of this binary rule to parse after completing
// the first symbol's branch.
sym: rule.rhs[1],
/**
* The path's grammatical properties (`case`, `tense`, and
* `acceptedTense`) used to conjugate terminal rules `node`
* produces.
*/
gramProps: newPath.gramProps,
/**
* The number of symbols in the `nextItemList` that can produce
* a semantic. This excludes other symbols and conjugative text.
* Used to determine if a RHS semantic is complete (no more
* semantics will follow it) and can be reduced with the
* preceding LHS semantic.
*
* If `rule.secondRHSCanProduceSemantic` is `false`, then there
* will never be a semantic down the second branch of this
* binary rule, and a RHS semantic in the first branch can
* freely reduce with any preceding LHS semantic found before
* this rule. Else, prevent the first branch's RHS semantic(s)
* from reducing with LHS semantics found before this rule.
*/
symCount: prevNextItemList.symCount + Number(rule.secondRHSCanProduceSemantic),
// The number of items in `nextItemList`.
size: prevNextItemList.size + 1,
// The next item that follows after completing this branch,
// created from the previous binary or insertion rule.
next: prevNextItemList,
}
} else {
newPath.nextItemList = {
sym: rule.rhs[1],
gramProps: newPath.gramProps,
symCount: Number(rule.secondRHSCanProduceSemantic),
size: 1,
}
}
}
}
/**
* Insertion rule.
*
* Insertions only exist on nonterminal rules because they can only be
* built from binary rules. This might change if we enable terminal
* symbols to be in a RHS with another terminal or nonterminal symbol
* (or multiple).
*/
else {
/**
* Insertions always have text. Edit rules can be made from insertions
* and lack text, but they behave as normal rules (with
* `insertedSymIdx`).
*/
if (rule.insertedSymIdx === 1) {
/**
* Will conjugate text after completing first branch in this binary
* reduction. Used in nominative case, which relies on person-number
* in the first branch (verb precedes subject).
*/
if (prevNextItemList) {
newPath.nextItemList = {
/**
* The display text to append after completing the first branch
* and determining the person-number property for conjugation,
* if necessary.
*/
text: rule.text,
/**
* The number of nodes in the `nextItemList` that can produce a
* semantic. This excludes other nodes and conjugative text.
* Used to determine if a RHS semantic is complete (no more
* semantics will follow it) and can be reduced with the
* preceding LHS semantic.
*/
symCount: prevNextItemList.symCount,
// The number of items in `nextItemList`.
size: prevNextItemList.size + 1,
// The next item that follows after completing this branch,
// created from the previous binary or insertion rule.
next: prevNextItemList,
}
} else {
newPath.nextItemList = {
text: rule.text,
symCount: 0,
size: 1,
}
}
} else {
// Copy `newPath.text` to avoid mutating the array shared with
// multiple paths.
newPath.text = newPath.text.slice()
/**
* Append text, if any, to the previous path's text, performing any
* necessary person-number conjugation.
*
* Do not pass the parent rule's `gramProps` because that
* conjugation was performed during the insertion rule's
* compilation.
*/
newPath.text.push(conjugateText(rule.text, newPath.personNumberList))
}
}
}
// Terminal rule.
else {
// Append `sub`'s RHS semantics, if any, to `prevPath.semanticList` and
// then reduce up to the first incompletely reduced node.
newPath.semanticList = reduceSemanticTree(prevPath.semanticList, prevNextItemList ? prevNextItemList.symCount : 0, rule.semantic)
/**
* Discard if semantically illegal parse.
*
* This prevents certain instances of ambiguity from being printed.
* Although those parse trees would also be discarded in `pfsearch`,
* they are still being constructed by `Parser` and their offending
* rules should be examined.
*/
if (newPath.semanticList === -1) return -1
// Append terminal symbol.
newPath.terminals += ' ' + rule.rhs[0]
// Prevent copying `newPath.text` multiple times.
var textCopied = false
// Append terminal rule text, if any; otherwise it is a stop word.
if (rule.text) {
// Copy `newPath.text` to avoid mutating the array shared with multiple
// paths.
newPath.text = newPath.text.slice()
textCopied = true
newPath.text.push(conjugateText(rule.text, newPath.personNumberList, prevPath.gramProps, rule.tense))
} else if (rule.isPlaceholder) {
newPath.text = newPath.text.slice()
textCopied = true
// Add placeholder terminal symbol, which normally is be replaced with
// input.
newPath.text.push(rule.rhs[0])
}
// The most recent yet-to-parse node of a previous binary rule or a
// conjugative text object of a previous insertion rule.
var nextItemList = newPath.nextItemList
// The most recent person-number property.
var personNumberList = newPath.personNumberList
/**
* After reaching the end of a branch, get the next node in
* `newPath.nextItemList` while conjugating any preceding inserted text
* objects. In `pfsearch`, this operation occurs right before expanding
* a path instead of when the terminal rule is reached, as here, to
* avoid work on paths whose cost prevents them from ever being popped
* from the min-heap.
*/
while (nextItemList) {
var text = nextItemList.text
// Stop at a node.
if (!text) break
if (!textCopied) {
// Copy `newPath.text` to avoid mutating the array shared with
// multiple paths.
newPath.text = newPath.text.slice()
textCopied = true
}
// Remove person-number properties for previously completed subtrees.
personNumberList = unwindPersonNumberList(personNumberList, nextItemList.size)
/**
* Append text from insertions of the second of two RHS symbols,
* performing any necessary conjugation. Conjugation occurs in the
* nominative case, which relies on the person-number of the first
* branch (verb precedes subject).
*
* Do not pass the parent rule's `gramProps` because that conjugation
* was performed in the compilation of the insertion rule.
*/
newPath.text.push(conjugateText(text, personNumberList))
nextItemList = nextItemList.next
}
if (nextItemList) {
// Get the second symbol of the most recent incomplete binary rule.
newPath.curSym = nextItemList.sym
newPath.nextItemList = nextItemList.next
// Remove person-number properties for previously completed subtrees.
newPath.personNumberList = unwindPersonNumberList(personNumberList, nextItemList.size)
/**
* The path's grammatical properties (`case`, `tense`, and
* `acceptedTense`) used to conjugate the second symbol of this binary
* rule, if applicable (i.e., a terminal rule).
*/
newPath.gramProps = nextItemList.gramProps
} else {
// No symbols remain.
newPath.nextItemList = undefined
}
}
return newPath
}
/**
* Finds and prints ambiguity created by paths `nontermSym` produces.
*
* Ambiguity exists if multiple paths exist to the same rightmost symbols,
* and the resulting semantic trees and/or display texts are
* indistinguishable. If ambiguity is found among a pair of paths, prints
* the parse trees, semantic trees, and display texts for those paths to
* show the necessary changes to make to the grammar
*
* Compares paths that different root rules produces, where `nontermSym` is
* the root symbol. Does not compare paths from the same root rule, because
* any ambiguity that exists there is caused by a symbol other than this
* root symbol.
*
* By default, prints only one instance of ambiguity found between a pair of
* root rules. If `--find-all` is `true`, then prints every distinct pair of
* ambiguous trees found. Often, the former is sufficient for determining
* the necessary changes to make to the grammar. The latter, however, can be
* helpful as the grammatical change required might not be in the root rule,
* but rather in a subsequent rule only demonstrated when used with this
* root rule. For certain cases with `--find-all`, such as recursive rules
* (i.e., a rule whose RHS contains the LHS), an excessive number of
* ambiguity instances are printed.
*
* @private
* @static
* @param {Object} pathTab The set of paths a single nonterminal symbol
* produces.
*/
function findAmbiguity(pathTab) {
var foundAmbiguity = false
/**
* If `--find-all` is passed, then track distinct pairs of ambiguous trees
* to prevent printing the same instance of ambiguity multiple times when
* found in multiple pairs of trees.
*/
if (argv.findAll) {
var ambigPairs = []
}
// Check for ambiguity among pairs of paths created by different root rules.
for (var a = 0, pathTabLen = pathTab.length; a < pathTabLen; ++a) {
var pathSetsA = pathTab[a]
for (var b = a + 1; b < pathTabLen; ++b) {
var pathSetsB = pathTab[b]
// Check each set of paths produced from this root rule (i.e., index `a`
// of `pathTab`) organized by their terminal symbols.
for (var terminals in pathSetsA) {
var pathsB = pathSetsB[terminals]
// Check if paths exist from this root rule (i.e., index `b` of
// `pathTab`) with these terminal symbols.
if (!pathsB) continue
var pathsBLen = pathsB.length
var pathsA = pathSetsA[terminals]
/**
* Sort paths by decreasing size to print the smallest (and
* simplest) pair of ambiguous trees for this pair of root rules.
* (When `--find-all` is omitted and ambiguity exists, only a single
* (i.e., the first found) pair of ambiguous trees is printed for
* each pair of root rules.)
*/
pathsA.sort(function (a, b) {
return a.symCount - b.symCount
})
// Compare paths among this pair of root rules which have identical
// terminal rules.
for (var p = 0, pathsALen = pathsA.length; p < pathsALen; ++p) {
var pathA = pathsA[p]
var curSym = pathA.curSym
var nextItemList = pathA.nextItemList
for (var o = 0; o < pathsBLen; ++o) {
var pathB = pathsB[o]
/**
* `terminals`, `curSym`, and `nextItemList` together are the
* rightmost symbols of the root symbol. If no nonterminal
* symbols remain to be reduced (as is always true with
* `--complete-trees`), then the rightmost symbols form what
* would be the parse input.
*/
if (pathB.curSym === curSym && nextSymsEqual(pathB.nextItemList, nextItemList)) {
// Save the following properties to prevent repeating the
// operations for multiple comparisons.
if (!pathA.textAndSyms) {
/**
* Completely reduce semantic trees irrespective of parsing
* state and semantic argument requirements. This is
* necessary for comparisons.
*/
pathA.semanticTree = completeSemanticTree(pathA.semanticList, pathA)
// Discard if semantic is illegal.
if (pathA.semanticTree === -1) continue
/**
* Concatenate each path's display texts, text arrays of
* yet-to-reduce insertion rules, and yet-to-reduce
* nonterminal symbols. Merge adjacent strings to properly
* compare text items spanning multiple terminal rules;
* e.g., XY -> "x" "y" equals Z -> "x y".
*
* Include yet-to-reduce nonterminal symbols to prevent
* merging non-adjacent insertion texts. These nonterminal
* symbols have already been identified as identical to the
* other path.
*/
pathA.textAndSyms = concatTextAndNextSyms(pathA)
}
// Save the following properties to prevent repeating the
// operations for multiple comparisons.
if (!pathB.textAndSyms) {
// Completely reduce semantic trees irrespective of parsing
// state and semantic argument requirements.
pathB.semanticTree = completeSemanticTree(pathB.semanticList, pathB)
// Discard if semantic is illegal.
if (pathB.semanticTree === -1) continue
/**
* Concatenate each path's display texts, text arrays of
* yet- to-reduce insertion rules, and yet-to-reduce
* nonterminal symbols.
*/
pathB.textAndSyms = concatTextAndNextSyms(pathB)
}
// Check if semantic trees are identical. A pair of paths is
// ambiguous even if semantics of both are `undefined`.
var semanticsEquivalent = semantic.arraysEqual(pathA.semanticTree, pathB.semanticTree)
// Check if display texts, including conjugative text objects
// and insertion texts of yet-to-reduce rules, are identical.
var textsEquivalent = textsEqual(pathA.textAndSyms, pathB.textAndSyms)
/**
* A pair of paths is ambiguous when their rightmost symbols
* are identical and their semantics and/or identical display
* texts are identical.
*/
if (semanticsEquivalent || textsEquivalent) {
// The pair is semantically and/or textually
// indistinguishable.
foundAmbiguity = true
/**
* Convert a reverse linked list of path nodes, each
* containing the RHS symbols a rule used in the path's
* construction, to a parse tree.
*/
var treeA = linkedListToGraph(pathA)
var treeB = linkedListToGraph(pathB)
/**
* Remove the rightmost portions of the pair of trees that
* the pair have in common. This trims the trees up to the
* portions created by the rules causing the ambiguity.
*/
diffTrees(treeA, treeB)
/**
* Print instance of ambiguity if either are true:
* 1. `--find-all` is omitted: Then, this is the first (and
* last) instance of ambiguity found to have been created
* by this pair of root rules.
* 2. `--find-all` is passed and this instance of ambiguity
* has not been seen: Confirmed by checking if this pair,
* after being processed by `diffTrees()`, already exists
* in previously seen pairs in `ambigPairs`. The same
* instance of ambiguity can be found in multiple pairs of
* trees when the pairs are distinguished by rules that
* come after the rules creating ambiguity.
*/
if (!argv.findAll || !pairExists(ambigPairs, treeA, treeB)) {
if (!argv.quiet) {
/**
* Accumulate instances of ambiguity in
* `ambiguityToPrint` to allow for sorting all results
* before printing, which enables better comparisons of
* output from multiple runs.
*/
ambiguityToPrint.push({
terminals: pathA.terminals.slice(1),
textA: pathA.textAndSyms,
semanticA: pathA.semanticTree === -1 ? -1 : (pathA.semanticTree ? semantic.toStylizedString(pathA.semanticTree) : undefined),
treeA: treeA,
textB: pathB.textAndSyms,
semanticB: pathB.semanticTree === -1 ? -1 : (pathB.semanticTree ? semantic.toStylizedString(pathB.semanticTree) : undefined),
treeB: treeB,
})
}
if (argv.findAll) {
// Save this distinct pair of ambiguous trees to prevent
// printing it multiple times.
ambigPairs.push([ treeA, treeB ])
} else {
// Only print one instance of ambiguity for this pair of
// root rules.
break
}
}
}
}
}
if (o < pathsBLen) break
}
if (p < pathsALen) break
}
}
}
// If `--test-rules` is passed, then use the ambiguous test rules to check
// the accuracy of this algorithm.
if (argv.testRules) {
if (!foundAmbiguity && /^\[ambig-/.test(nontermSym)) {
util.logError('Ambiguity not found for ambiguous test rule:', util.stylize(nontermSym))
process.exit(1)
} else if (foundAmbiguity && /^\[unambig-/.test(nontermSym)) {
util.logError('Ambiguity found for unambiguous test rule:', util.stylize(nontermSym))
process.exit(1)
}
}
}
/**
* Checks if `nextItemList` lists `a` and `b` are equivalent by comparing
* the linked lists of symbols and conjugative text, ignoring the instances
* of text.
*
* @private
* @static
* @param {Object} a The `nextItemList` list to compare.
* @param {Object} b The other `nextItemList` list to compare.
* @returns {boolean} Returns `true` if the lists' symbols, ignoring
* instances of text, are equivalent, else `false`.
*/
function nextSymsEqual(a, b) {
// Ignore instances of conjugative text.
while (a && !a.sym) {
a = a.next
}
// Ignore instances of conjugative text.
while (b && !b.sym) {
b = b.next
}
// Same linked list items or both `undefined`; i.e., reached the ends of
// both lists without finding a difference.
if (a === b) return true
// One of the lists is longer than the other.
if (!a || !b) return false
// Check if symbols are identical.
if (a.sym !== b.sym) return false
// Examine previous item in list.
return nextSymsEqual(a.next, b.next)
}
/**
* Compares two paths' `nextItemList` linked lists of symbols and
* conjugative text, ignoring the instances of symbols, to determine if the
* text values are equivalent.
*
* This function was deprecated in favor of comparing the paths' output of
* `concatTextAndNextSyms()`
*
* @private
* @static
* @param {Object} a The `nextItemList` list to compare.
* @param {Object} b The other `nextItemList` list to compare.
* @returns {boolean} Returns `true` if the lists' text, ignoring instances
* of symbols, are equivalent, else `false`.
*/
function nextTextsEqual(a, b) {
// Ignore instances of yet-to-reduce symbols.
while (a && !a.text) {
a = a.next
}
// Ignore instances of yet-to-reduce symbols.
while (b && !b.text) {
b = b.next
}
// Same linked list items or both `undefined`; i.e., reached the ends of
// both lists without finding a difference.
if (a === b) return true
// One of the lists is longer than the other.
if (!a || !b) return false
// Check if text values are identical.
if (!textsEqual(a.text, b.text)) return false
// Examine previous item in list.
return nextTextsEqual(a.next, b.next)
}
/**
* Concatenates a path's display text, text arrays of yet-to-reduce
* insertion rules, and yet-to-reduce nonterminal symbols. Merges adjacent
* strings to properly compare text items spanning multiple terminal rules;
* e.g., XY -> "x" "y" equals Z -> "x y".
*
* The display text can include unconjugated text objects because a path's
* root symbol can occur after where the necessary grammatical property
* occurs.
*
* Includes yet-to-reduce nonterminal symbols to prevent merging
* non-adjacent insertion texts. These nonterminal symbols have already been
* identified as identical to the other path being compared with this path.
*
* @private
* @static
* @param {Object} path The path whose value to concatenate.
* @returns {Array} Returns a new array with concatenated values.
*/
function concatTextAndNextSyms(path) {
// Do not mutate `text` because it can be shared with other paths.
var items = path.text.slice()
// Include yet-to-reduce nonterminal symbols to prevent merging non-adjacent
// insertion texts.
if (path.curSym) {
items.push(path.curSym)
}
var item = path.nextItemList
while (item) {
var itemText = item.text
if (itemText instanceof Array) {
// Merge contents of insertion text arrays.
Array.prototype.push.apply(items, itemText)
} else {
// Include yet-to-reduce nonterminal symbols and text arrays of yet-to-
// reduce insertion rules.
items.push(item.sym || itemText)
}
item = item.next
}
// Merge adjacent strings. Can not use `Array.prototype.join()` because
// `items` can contain conjugative text objects.
for (var t = 1; t < items.length; ++t) {
var item = items[t]
var prevIndex = t - 1
if (item.constructor === String && items[prevIndex].constructor === String) {
items[prevIndex] += ' ' + item