-
Notifications
You must be signed in to change notification settings - Fork 5
/
semantic.js
1687 lines (1560 loc) · 64.1 KB
/
semantic.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
var util = require('../../util/util')
var grammarUtil = require('./grammarUtil')
/**
* The map of the grammar's semantic names to the semantics.
*
* @type {Object.<string, Object[]>}
*/
exports._semantics = {}
/**
* The map of semantic names to definition lines (file-path + line-number).
* For use in error messages.
*
* @type {Object.<string, string>}
*/
exports._defLines = {}
/**
* The operator semantics used throughout this module, including in
* `semantic.reduce()`, `reduceUnion()`, `semantic.isIllegalRHS()`, and
* `hasSemantic()`.
*/
var intersectSemantic
var unionSemantic
var notSemantic
/**
* If not currently building the grammar via `buildGrammar`, then load the
* `intersect()`, `union()`, and `not()` semantics from the grammar file,
* which works for equality comparisons because of `initSemantics`.
*/
if (require.main.filename !== require.resolve('./buildGrammar')) {
// Map to `exports._semantics` to enable `semantic.stringToObject()`.
exports._semantics = require('../grammar.json').semantics
intersectSemantic = exports._semantics.intersect
unionSemantic = exports._semantics.union
notSemantic = exports._semantics.not
}
/**
* Creates and adds a new semantic function or semantic argument to the
* grammar.
*
* `pfsearch` uses semantics, which are associated with grammar rules, to
* construct a semantic tree for each parse tree. Each semantic tree is a
* lambda calculus representation of the meaning of its associated parse
* tree's display text. With lambda calculus's discrete representation,
* however, there is no notion of similarity or the fuzziness of language,
* unlike vector spaces (i.e., long lists of numbers).
*
* @static
* @memberOf semantic
* @param {Object} options The options object.
* @returns {Object[]} Returns the new semantic.
*/
exports.new = function (options) {
var semanticArray = options.isArg ? newSemanticArgument(options) : newSemanticFunction(options)
var semanticDef = semanticArray[0].semantic
var semanticName = semanticDef.name
// Check for duplicity after invoking `util.illFormedOpts()` on `options` in
// the appropriate instantiation function above.
if (grammarUtil.isDuplicateName(semanticName, exports._defLines, 'semantic')) {
throw new Error('Duplicate semantic name')
}
// Save instantiation file path and line number for error reporting.
exports._defLines[semanticName] = util.getModuleCallerLocation()
// Save semantics for use elsewhere in this module.
if (semanticName === 'intersect') {
intersectSemantic = semanticDef
} else if (semanticName === 'union') {
unionSemantic = semanticDef
} else if (semanticName === 'not') {
notSemantic = semanticDef
}
return semanticArray
}
/**
* Creates a new semantic function to add to the grammar.
*
* `options.forbidsMultipleIntersection` is for use when a database object
* can only have one value for a specific property (e.g., "repos only
* created by 1 person"), and must forbid multiple instances of the
* corresponding semantic function within another semantic's arguments
* (irrespective of child semantics). Otherwise, an intersection of objects
* with different values for this property will return an empty set.
*
* @private
* @static
* @param {Object} options The options object.
* @param {string} options.name The unique semantic name.
* @param {number} options.cost The cost penalty added to rules that use
* this semantic.
* @param {number} options.minParams The minimum number of arguments this
* semantic function can accept.
* @param {number} options.maxPamrams The maximum number of arguments this
* semantic function can accept.
* @param {boolean} [options.forbidsMultipleIntersection] Specify forbidding
* multiple instantces of this semantic function in the arguments of an
* `intersect()`, irrespective of this semantic's arguments.
* @param {Object[]} [options.requires] A separate semantic that `pfsearch`
* requires is within the same instance of `intersect()` as this semantic,
* else rejects the semantic tree.
* @param {boolean} [options.isPeople] Specify this semantic represents a
* set of people and can serve as the antecedent for an anaphoric, plural
* (grammatical number) expression.
* @returns {Object[]} Returns the new semantic function.
*/
var semanticFunctionSchema = {
name: { type: String, required: true },
cost: { type: Number, required: true },
minParams: { type: Number, required: true },
maxParams: { type: Number, required: true },
forbidsMultipleIntersection: Boolean,
requires: Array,
isPeople: Boolean,
}
function newSemanticFunction(options) {
if (util.illFormedOpts(semanticFunctionSchema, options)) {
throw new Error('Ill-formed semantic function')
}
if (options.minParams > options.maxParams) {
util.logErrorAndPath('Semantic minParams > maxParams:', options)
throw new Error('Ill-formed semantic function')
}
var requiredSemantic = options.requires
if (requiredSemantic) {
if (!exports.isReduced(requiredSemantic)) {
util.logError('Required semantic is not reduced:', requiredSemantic)
util.logPathAndObject(options)
throw new Error('Ill-formed semantic function')
}
if (requiredSemantic.length > 1) {
util.logError('Required semantic contains multiple semantic trees:', requiredSemantic)
util.logPathAndObject(options)
throw new Error('Ill-formed semantic function')
}
requiredSemantic = requiredSemantic[0]
}
var semanticName = grammarUtil.formatStringForName(options.name)
var semanticDef = exports._semantics[semanticName] = {
name: semanticName,
cost: options.cost,
minParams: options.minParams,
maxParams: options.maxParams,
forbidsMultipleIntersection: options.forbidsMultipleIntersection,
requires: requiredSemantic,
}
if (options.isPeople) {
/**
* The person-number with which to resolve plural, anaphoric expressions
* (in `pfsearch`), where this semantic is the antecedent.
*
* Individual entities have a `anaphoraPersonNumber` property of
* 'threeSg', which `Parser.prototype.getSemanticArg()` assigns to new
* semantic arguments it created for entities matched in input.
*/
semanticDef.anaphoraPersonNumber = 'threePl'
}
/**
* An `Array` is necessary for `semantic.arraysEqual()`, generating a
* non-reduced semantic tree for a rule (i.e., behaving as a non-reduced
* RHS semantic), and general consistency.
*/
return [ {
semantic: semanticDef,
children: [],
} ]
}
/**
* Creates a semantic argument to add to the grammar.
*
* @private
* @static
* @param {Object} options The options object.
* @param {boolean} options.isArg Specify this is a semantic argument.
* @param {string} options.name The unique semantic name.
* @param {number} options.cost The cost penalty added to rules that use
* this semantic.
* @returns {Object[]} Returns the new semantic argument.
*/
var semanticArgumentSchema = {
isArg: { type: Boolean, required: true },
name: { type: String, required: true },
cost: { type: Number, required: true },
}
function newSemanticArgument(options) {
if (util.illFormedOpts(semanticArgumentSchema, options)) {
throw new Error('Ill-formed semantic argument')
}
var semanticName = grammarUtil.formatStringForName(options.name)
var semanticDef = exports._semantics[semanticName] = {
isArg: true,
name: semanticName,
cost: options.cost,
}
return [ {
semantic: semanticDef,
} ]
}
/**
* Recursively sums the costs of all semantics in `semanticNodeArray`.
*
* @static
* @memberOf semantic
* @param {Object[]} semanticNodeArray The semantic array to sum.
* @returns {number} Returns the sum of the semantic costs in
* `semanticNodeArray`.
*/
exports.sumCosts = function (semanticNodeArray) {
return semanticNodeArray.reduce(function (accum, node) {
return accum + node.semantic.cost + (node.children ? exports.sumCosts(node.children) : 0)
}, 0)
}
/**
* Merges two reduced (RHS) semantic arrays, `a` and `b`, into a new array,
* if the merge is semantically legal. Else, returns `-1`.
*
* Note: It is faster to return `-1` and check the return value up the stack
* than to throw an exception to catch up the stack.
*
* @static
* @memberOf semantic
* @param {Object[]} a The semantic array to merge.
* @param {Object[]} b The other semantic array to merge.
* @returns {Object[]|number} Returns the new, merged semantic if
* semantically legal, else `-1`.
*/
exports.mergeRHS = function (a, b) {
// Check if semantic merge is legal.
if (exports.isIllegalRHS(a, b)) {
return -1
}
/**
* Do not sort because will be sorted when added to a LHS.
*
* `Array.prototype.concat()` is faster than `Array.prototype.slice()` +
* `Array.prototype.push.apply()`.
*/
return a.concat(b)
}
/**
* Checks if reduced (RHS) semantic node arrays `a` and `b` are forbidden to
* merge as a single set of RHS semantic arguments.
*
* The following invalidates semantic arrays:
* • Duplicate semantics.
* • Contradictory negations.
*
* It is necessary to prevent contradictory and duplicate semantics, even
* when explicitly input by the user, to prevent undesirable semantics as
* suggestions. In addition, algebraically simplifying the semantics's logic
* enables `pfsearch` to correctly identify semantically identical parse
* trees (whose logical equivalence would be undetectable in their
* unsimplified forms).
*
* @static
* @memberOf semantic
* @param {Object[]} a The semantic node array to inspect.
* @param {Object[]} b The other semantic node array to inspect.
* @returns {boolean} Returns `true` if the semantics are forbidden to
* merge, else `false`.
*/
exports.isIllegalRHS = function (a, b) {
var bLen = b.length
for (var i = 0, aLen = a.length; i < aLen; ++i) {
var semanticNodeA = a[i]
var semanticA = semanticNodeA.semantic
var semanticAIsNegation = semanticA === notSemantic
for (var j = 0; j < bLen; ++j) {
var semanticNodeB = b[j]
var semanticB = semanticNodeB.semantic
// Prevent contradiction with `not()` semantic.
if (semanticAIsNegation && exports.nodesEqual(semanticNodeA.children[0], semanticNodeB)) {
return true
}
// Prevent contradiction with `not()` semantic.
if (semanticB === notSemantic && exports.nodesEqual(semanticNodeA, semanticNodeB.children[0])) {
return true
}
// Prevent duplicate semantic nodes using a deep comparison.
if (exports.nodesEqual(semanticNodeA, semanticNodeB)) {
return true
}
}
}
return false
}
/**
* Checks if `semanticList.prev.semantic` is `intersect()` and
* `semanticList.semantic` contains a semantic identical to
* `newLHSSemanticNodeArray` for which multiple instances of that semantic
* function (irrespective of children) are forbidden within the same set of
* `intersect()` arguments.
*
* This check behaves as a semantic lookahead that enables its parse tree's
* rejection without having to complete `newLHSSemanticNodeArray` and wait
* for its reduction with `prevLHSSemanticNodeArray` in `semantic.reduce()`
* to reject the tree for this reason.
*
* @static
* @memberOf semantic
* @param {Object} semanticList The semantic linked list to inspect.
* @param {Object[]} newLHSSemanticNodeArray The new semantic, yet to be
* reduced, which will eventually be concatenated with
* `semanticList.semantic` as semantic arguments and reduced with
* `semanticList.prev.semantic`.
* @returns {boolean} Returns `true` if `semanticList.prev.semantic` is
* `intersect()` and `semanticList.semantic` contains a semantic identical
* to `newLHSSemanticNodeArray` for which multiple instances are forbidden
* within `intersect()`, else `false`.
*/
exports.isForbiddenMultiple = function (semanticList, newLHSSemanticNodeArray) {
/**
* The outer LHS semantic must be `intersect()` for its arguments (which
* will be a merge of `rhsSemanticNodeArray` and
* `newLHSSemanticNodeArray`) to be in logical violation.
*/
if (semanticList.prev.semantic[0].semantic === intersectSemantic) {
var rhsSemanticNodeArray = semanticList.semantic
// `newLHSSemanticNodeArray` will only ever have one semantic (which has
// `yet to be reduced).
var lhsSemantic = newLHSSemanticNodeArray[0].semantic
/**
* Check if multiple instances of `lhsSemantic` are forbidden within the
* same set of `intersect()` arguments; e.g., `users-gender()` has only
* one mode of being.
*/
if (lhsSemantic.forbidsMultipleIntersection) {
for (var s = 0, rhsLen = rhsSemanticNodeArray.length; s < rhsLen; ++s) {
if (rhsSemanticNodeArray[s].semantic === lhsSemantic) {
return true
}
}
}
}
return false
}
/**
* Checks for multiple instances of the same semantic function marked
* `forbidsMultipleIntersection` in `rhsSemanticNodeArray`.
*
* For use by `semantic.reduce()` when the LHS semantic is `intersect()` and
* `rhsSemanticNodeArray` is to become its semantic arguments when reduced.
*
* @private
* @static
* @param {Object[]} rhsSemanticNodeArray The semantic node array to check.
* @returns {boolean} Returns `true` if `rhsSemanticNodeArray` contains
* multiple instances of the same semantic function marked
* `forbidsMultipleIntersection`, else `false`.
*/
function hasForbiddenMultiple(rhsSemanticNodeArray) {
for (var s = 0, rhsLen = rhsSemanticNodeArray.length; s < rhsLen; ++s) {
var semanticNode = rhsSemanticNodeArray[s]
var semanticDef = semanticNode.semantic
if (semanticDef.forbidsMultipleIntersection) {
for (var j = s + 1; j < rhsLen; ++j) {
if (rhsSemanticNodeArray[j].semantic === semanticDef) {
return true
}
}
}
}
return false
}
/**
* Performs a deep comparison between two semantic nodes, `a` and `b`, to
* determine if they are equivalent.
*
* Requires invoking `initSemantics` on the semantics beforehand, which
* enables comparing semantics by reference instead of their `name`
* properties. In addition, `initSemantics` accelerates semantic comparisons
* by replacing identical semantic trees in the grammar with references to a
* single object.
*
* @static
* @memberOf semantic
* @param {Object} a The semantic node to compare.
* @param {Object} b The other semantic node to compare.
* @returns {boolean} Returns `true` if the semantics are equivalent, else
* `false`.
*/
exports.nodesEqual = function (a, b) {
// Identical semantics or both `undefined`.
if (a === b) {
return true
}
// One of two is `undefined`.
if (!a || !b) {
return false
}
if (a.semantic !== b.semantic) {
return false
}
if (a.children && b.children) {
// Both are semantic functions.
return exports.arraysEqual(a.children, b.children)
} else if (a.children || b.children) {
// One is a semantic function and other is a semantic argument.
return false
}
// This is never reached.
return true
}
/**
* Performs a deep comparison between two semantic node arrays, `a` and `b`,
* to determine if they are equivalent. Each semantic in the arrays is a
* reduced (i.e., RHS) semantic.
*
* Requires invoking `initSemantics` on the semantics beforehand, which
* enables comparing semantics by reference instead of their `name`
* properties. In addition, `initSemantics` accelerates semantic comparisons
* by replacing identical semantic trees in the grammar with references to a
* single object.
*
* @static
* @memberOf semantic
* @param {Object[]} a The semantic node array to compare.
* @param {Object[]} b The other semantic node array to compare.
* @returns {boolean} Returns `true` if the semantic arrays are equivalent,
* else `false`.
*/
exports.arraysEqual = function (a, b) {
// Identical semantic arrays or both `undefined`.
if (a === b) {
return true
}
// One of two is `undefined`.
if (!a || !b) {
return false
}
var aLen = a.length
if (aLen !== b.length) {
return false
}
for (var i = 0; i < aLen; ++i) {
if (!exports.nodesEqual(a[i], b[i])) {
return false
}
}
// Semantic arrays are identical.
return true
}
/**
* Applies a completed semantic rule (`lhsSemanticNodeArray` ->
* `rhsSemanticNodeArray`) to a more recent semantic tree
* (`rhsSemanticNodeArray`), joining them together as one semantic tree with
* `lhsSemanticNodeArray` as the new root semantic function.
*
* @static
* @memberOf semantic
* @param {Object[]} lhsSemanticNodeArray The LHS non-reduced semantic node
* array.
* @param {Object[]} rhsSemanticNodeArray The RHS reduced semantic semantic
* node array, to be semantic arguments for `lhsSemanticNodeArray`.
* @returns {Object[]|number} Returns the new, reduced semantic if
* semantically legal, else `-1`.
*/
exports.reduce = function (lhsSemanticNodeArray, rhsSemanticNodeArray) {
if (lhsSemanticNodeArray.length !== 1) {
util.logError('Semantic reduction: lhsSemanticNodeArray.length !== 1')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
var lhsSemanticNode = lhsSemanticNodeArray[0]
var lhsSemantic = lhsSemanticNode.semantic
var rhsLen = rhsSemanticNodeArray.length
if (lhsSemantic === intersectSemantic) {
// Check LHS `intersect()` semantics lack semantic arguments.
if (lhsSemanticNode.children.length > 0) {
util.logError('Semantic reduction: LHS `intersect()` has children')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
/**
* Reject if `rhsSemanticNodeArray` contains a semantic that `requires`
* another semantic not within this semantic tree.
*
* This check must occur at `intersect()`, else would incorrectly reject
* semantics such as the following (because the required semantic is not
* within `not()`):
* `not(repositories-visibility(public)),repositories-created(me)`
*
* This check must occur before the `rhsLen === 1` check below, which
* would require waiting for the next `intersect()` to perform this
* check, because a semantic tree can lack instances of `intersect()`
* altogether.
*/
if (isMissingRequiredSemantic(rhsSemanticNodeArray)) {
return -1
}
/**
* Discard LHS `intersect()` when `rhsSemanticNodeArray` contains only
* one semantic node.
*
* Copy and extend the semantic node in `rhsSemanticNodeArray` if it is
* either either `union()` or `intersect()` with the property
* `isComplete`, which indicates to `reducedUnion()` that
* `rhsSemanticNodeArray` reached its parent `intersect()`. If
* `rhsSemanticNodeArray` does not contain either specified semantic
* function, return the array unchanged.
*
* • If `rhsSemanticNodeArray` contains `union()`, assign `isComplete`
* to the semantic node to prevent future `reduceUnion()` invocations
* from moving the `union()` semantic node too far up its semantic tree.
* If the node already has `isComplete`, mark instances of `intersect()`
* among its children with `isComplete` to prevent `reduceUnion()` from
* incorrectly distributing the LHS semantic that follows the `union()`
* among the arguments of its `intersect()` children.
*
* • If `rhsSemanticNodeArray` contains `intersect()`, assign
* `isComplete` to the semantic node to prevent future `reduceUnion()`
* invocations from incorrectly distributing the LHS semantic that
* follows a future `union()` semantic among the arguments of instances
* of `intersect()` within the `union()` semantic.
*
* Need not check multi-node RHS arrays for semantics to mark complete.
*/
if (rhsLen === 1) {
return completeSingleNodeConjunctionSemantic(rhsSemanticNodeArray)
}
/**
* When LHS is `intersect()`, prevent multiple instances of the same
* semantic function marked `forbidsMultipleIntersection` (e.g.,
* `users-gender()`) within its arguments, `rhsSemanticNodeArray`.
*
* Only perform `forbidsMultipleIntersection` check when LHS is
* `intersect()`, instead of for any semantic array (via
* `semantic.mergeRHS()`) to allow for when LHS is `union()`, which is
* logically valid.
*/
if (hasForbiddenMultiple(rhsSemanticNodeArray)) {
return -1
}
}
/**
* Reduce `lhsSemanticNodeArray` with the `rhsSemanticNodeArray` `union()`
* semantic node by distributing the LHS semantic, `lhsSemanticNodeArray`,
* among the `union()` semantic arguments, `rhsSemanticNode.children`,
* creating a new semantic tree with `union()` as the root.
*
* Invoke `reduceUnion()` after the `intersect()` check, which invokes
* `completeSingleNodeConjunctionSemantic()` to assign properties
* indicating reaching a conjunction's root. Invoke before traversing
* `lhsSemanticNodeArray` children, if any, to properly distribute all of
* `lhsSemanticNodeArray` among the `union()` arguments.
*
* Use `else if` because if the preceding conditional check passed (i.e.,
* `lhsSemantic` is `intersect()`), the method would have returned if
* `rhsLen` is 1.
*/
else if (rhsLen === 1) {
var rhsSemanticNode = rhsSemanticNodeArray[0]
if (rhsSemanticNode.semantic === unionSemantic && !rhsSemanticNode.isComplete) {
return reduceUnion(lhsSemanticNodeArray, rhsSemanticNode)
}
}
/**
* When `lhsSemanticNode` has semantic arguments, insert
* `rhsSemanticNodeArray` at innermost semantic function by recursively
* reducing `lhsSemanticNode.children` with `rhsSemanticNodeArray`, and
* replacing `rhsSemanticNodeArray` with the resulting semantic tree.
*
* This operation rebuilds the `lhsSemanticNodeArray` semantic tree while
* unwrapping, duplicating LHS semantic functions if necessary. For example:
* LHS: `not(repos-liked())` -> LHS: `not()`
* RHS: `[ 1, 2 ]` -> RHS: `repos-liked(1),repos-liked(2)`
* -> `not(repos-liked(1)),not(repos-liked(2))`
*
* After replacing `rhsSemanticNodeArray` with `lhsSemanticNode.children`,
* reduced with the original `rhsSemanticNodeArray`, this function caries on
* reducing the LHS semantic node with the new `rhsSemanticNodeArray`,
* ignoring the original children on `lhsSemanticNode`.
*
* Invoke after invoking `reduceUnion()`, which properly moves a `union()`
* semantic up a semantic tree and distributes the entire
* `lhsSemanticNodeArray`, including its semantic children, among the
* `union()` arguments. For example:
* "repos Danny or Aang do not like"
* LHS: `not(repos-liked())`
* RHS: `union(0,1)`
* -> union(not(repos-liked(0)),not(repos-liked(1)))`
*/
if (lhsSemanticNode.children.length > 0) {
/**
* Replace `rhsSemanticNodeArray` with result of reduction of
* `lhsSemanticNode.children` with `rhsSemanticNodeArray`. Going
* forward, ignore `lhsSemanticNode.children` by only referencing
* `lhsSemanticNode.semantic`.
*/
rhsSemanticNodeArray = exports.reduce(lhsSemanticNode.children, rhsSemanticNodeArray)
// Reject for semantic violations found with `lhsSemanticNode.children`
// and `rhsSemanticNodeArray`.
if (rhsSemanticNodeArray === -1) {
return -1
}
// Update `rhsLen`, which might have increased by duplicating semantic
// children for multiple nodes in `rhsSemanticNodeArray`.
rhsLen = rhsSemanticNodeArray.length
}
// Check RHS semantic array satisfies the LHS semantic's minimum argument
// requirement.
if (rhsLen < lhsSemantic.minParams) {
util.logError('Semantic reduction: rhsSemanticNodeArray.length < lhsSemantic.minParams')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
if (rhsLen > lhsSemantic.maxParams) {
/**
* When `lhsSemanticNodeArray` has `maxParams` of 1 and
* `rhsSemanticNodeArray` contains > 1 semantic nodes, reduce a
* duplicate of the LHS semantic node with each RHS semantic node, and
* create a merged semantic node array.
*
* Ignore any children `lhsSemanticNodeArray` might have, because if any
* they were reduced with `rhsSemanticNodeArray` above.
*/
return copyLHSAndReduce(lhsSemanticNodeArray, rhsSemanticNodeArray)
}
/**
* Reduce `lhsSemanticNodeArray` with `rhsSemanticNodeArray`, whose number
* of semantic nodes is within the LHS semantic node's `maxParams` bound.
*
* Ignore any children `lhsSemanticNodeArray` may have, using only the LHS
* semantic node's function.
*
* If `lhsSemanticNodeArray` is a `union()` semantic node, first invokes
* `flattenUnion(rhsSemanticNodeArray)` to remove redundant instances of
* nested `union()` semantics to enable proper semantic duplicity
* detection.
*/
return baseReduce(lhsSemanticNodeArray, rhsSemanticNodeArray)
}
/**
* Reduces `lhsSemanticNodeArray`, which has `maxParams` of 1, with
* `rhsSemanticNodeArray`, which contains > 1 semantic nodes by reducing a
* duplicate of the LHS semantic node with each RHS semantic node, and
* creating a merged semantic node array.
*
* For example:
* "repos liked by Danny and Aang"
* LHS: `repos-liked()`
* RHS: `[ 0, 1 ]`
* -> `repos-liked(0),repos-liked(1)`
*
* Ignores any children `lhsSemanticNodeArray` may have, using only the LHS
* semantic node's function.
*
* @private
* @static
* @param {Object[]} lhsSemanticNodeArray The LHS semantic node array with
* `maxParams` 1.
* @param {Object[]} rhsSemanticNodeArray The RHS semantic node array with > 1
* semantic nodes.
* @returns {Object[]} Returns the new semantic array from reducing
* `lhsSemanticNodeArray` with `rhsSemanticNodeArray`.
*/
function copyLHSAndReduce(lhsSemanticNodeArray, rhsSemanticNodeArray) {
if (lhsSemanticNodeArray.length !== 1) {
util.logError('Semantic reduction: lhsSemanticNodeArray.length !== 1')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
var lhsSemantic = lhsSemanticNodeArray[0].semantic
var rhsLen = rhsSemanticNodeArray.length
/**
* Check `rhsSemanticNodeArray` has more semantic nodes than the
* `lhsSemanticNodeArray` `maxParams` bound, requiring
* `lhsSemanticNodeArray` be copied for each `rhsSemanticNodeArray`
* semantic node. Else, `baseReduce()` should have been used.
*/
if (rhsLen <= lhsSemantic.maxParams) {
util.logError('`copyLHSAndReduce()` invoked with RHS semantic within LHS `maxParams` bound. Use `baseReduce()` instead.')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
/**
* Check `lhsSemantic.maxParams` is 1.
*
* If allowing `lhsSemantic.maxParams` > 1, would require dividing RHS
* semantic nodes into groups among multiple LHS semantic nodes; e.g., 4
* RHS semantic nodes halved for 2 LHS semantic nodes.
*
* This is not supported because it enables a grammar designed to expect a
* specific positioning of RHS semantic nodes within an array before the
* array's reduction (and sorting). Though possible, such a design is too
* complex and should be discouraged because an alternative,
* straightforward semantic rule structure is always possible.
*/
if (lhsSemantic.maxParams !== 1) {
util.logError('Semantic reduction: rhsSemanticNodeArray.length > lhsSemanticNodeArray.maxParams && lhsSemanticNodeArray.maxParams !== 1')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
/**
* Copy the LHS semantic for each RHS semantic node. For example:
* "repos liked by Danny and Aang"
* LHS: `repos-liked()`
* RHS: `[ 0, 1 ]`
* -> `repos-liked(0),repos-liked(1)`
*/
var newLHSSemanticNodeArray = []
for (var s = 0; s < rhsLen; ++s) {
var rhsSemanticNode = rhsSemanticNodeArray[s]
// Check for `union()` without `isComplete` in the RHS, as opposed to
// being passed to `reduceUnion()` when RHS has length of 1.
if (rhsSemanticNode.semantic === unionSemantic && !rhsSemanticNode.isComplete) {
util.logError('Semantic reduction: incomplete `union()` in semantic RHS with length > 1')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
newLHSSemanticNodeArray[s] = {
semantic: lhsSemantic,
children: [ rhsSemanticNode ],
}
}
// Need not sort `newLHSSemanticNodeArray`, which will be sorted when
// reduced as a RHS semantic array.
return newLHSSemanticNodeArray
}
/**
* Reduces `lhsSemanticNodeArray` with `rhsSemanticNodeArray`, whose number of
* semantic nodes is within the `lhsSemanticNodeArray` `maxParams` bound.
*
* For example:
* LHS: `intersect()`
* RHS: `repos-liked(1),repos-liked(2)`
* -> `intersect(repos-liked(1),repos-liked(2))`
*
* If `lhsSemanticNodeArray` is a `union()` semantic node, first invokes
* `flattenUnion(rhsSemanticNodeArray)` to remove redundant instances of
* nested `union()` semantics to enable proper semantic duplicity detection.
*
* Ignores any children `lhsSemanticNodeArray` may have, using only the LHS
* semantic node's function.
*
* @private
* @static
* @param {Object[]} lhsSemanticNodeArray The LHS semantic node array.
* @param {Object[]} rhsSemanticNodeArray The RHS semantic node array to
* reduce with `lhsSemanticNodeArray`.
* @returns {Object[]|number} Returns the new semantic array from reducing
* `lhsSemanticNodeArray` with `rhsSemanticNodeArray`, if legal, else -1.
*/
function baseReduce(lhsSemanticNodeArray, rhsSemanticNodeArray) {
if (lhsSemanticNodeArray.length !== 1) {
util.logError('Semantic reduction: lhsSemanticNodeArray.length !== 1')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
var lhsSemantic = lhsSemanticNodeArray[0].semantic
/**
* Check `rhsSemanticNodeArray` has fewer semantic nodes than the
* `lhsSemanticNodeArray` `maxParams` bound. Else, `copyLHSAndReduce()`
* should have been used.
*/
if (rhsSemanticNodeArray.length > lhsSemantic.maxParams) {
util.logError('`baseReduce()` invoked with RHS semantic that exceeds LHS `maxParams` bound. Use `copyLHSAndReduce()` instead.')
util.dir(lhsSemanticNodeArray, rhsSemanticNodeArray)
throw new Error('Semantic reduction error')
}
if (lhsSemantic === unionSemantic) {
/**
* If `lhsSemantic` is a `union()` semantic node, replace instances of
* `union()` semantic nodes within the first (most shallow) level of
* `rhsSemanticNodeArray` with their child semantic nodes, if any. This
* removes logically redundant instances of nested `union()` semantics,
* which enables detecting duplicate semantics within
* `rhsSemanticNodeArray`.
*/
rhsSemanticNodeArray = flattenUnion(rhsSemanticNodeArray)
// Return `-1` if the flattened semantic array is semantically illegal.
if (rhsSemanticNodeArray === -1) {
return -1
}
}
// Return an array because it becomes another semantic node's `children`.
return [ {
semantic: lhsSemantic,
// Mutating the shared `rhsSemanticNodeArray` array is inconsequential
// because all instances must be sorted identically eventually.
children: rhsSemanticNodeArray.sort(exports.compare),
} ]
}
/**
* Checks if `semanticArray` contains a semantic that `requires` another
* semantic not found elsewhere within `semanticArray`, stopping before
* instances of the `intersect()` semantic.
*
* This check must occur at `intersect()`, else would incorrectly reject
* semantics such as the following (because the required semantic is not
* within `not()`):
* `not(repositories-visibility(public)),repositories-created(me)`
*
* @private
* @static
* @param {Object[]} semanticArray The LHS semantic to check for required
* semantics.
* @returns {Boolean} Returns `true` if `semanticArray` is missing a
* required semantic, else `false`.
*/
function isMissingRequiredSemantic(semanticArray, _baseSemanticArray) {
var baseSemanticArray = _baseSemanticArray || semanticArray
for (var s = 0, semanticArrayLen = semanticArray.length; s < semanticArrayLen; ++s) {
var semanticNode = semanticArray[s]
var semantic = semanticNode.semantic
// Bind check at `intersect()` semantic.
if (semantic !== intersectSemantic) {
if (semantic.requires && !hasSemantic(baseSemanticArray, semantic.requires)) {
return true
}
/**
* Check for child semantics that require semantics within the initial
* semantic array (i.e., as opposed to checking the same semantic
* children array for required semantics).
*/
if (semanticNode.children && isMissingRequiredSemantic(semanticNode.children, baseSemanticArray)) {
return true
}
}
}
return false
}
/**
* Checks if `semanticNodeArray` contains `semanticNode`, stopping before
* instances of the `intersect()` and `not()` semantics.
*
* @private
* @static
* @param {Object[]} semanticNodeArray The LHS semantic to check for
* `semanticNode`.
* @param {Object} semanticNode The semantic node (from a semantic tree) to
* find.
* @returns {Boolean} Returns `true` if semanticNodeArray` contains
* `semanticNode`, else `false`.
*/
function hasSemantic(semanticNodeArray, semanticNode) {
for (var s = 0, semanticArrayLen = semanticNodeArray.length; s < semanticArrayLen; ++s) {
var otherSemanticNode = semanticNodeArray[s]
/**
* Bind check at `intersect()` and `not()` semantics. The `not()`
* semantic before the required semantics violates the logic by
* inversion; e.g., "public repos that are not mine".
*/
if (otherSemanticNode.semantic !== intersectSemantic && otherSemanticNode.semantic !== notSemantic) {
if (exports.nodesEqual(otherSemanticNode, semanticNode)) {
return true
}
// Check child semantics for `semanticNode`.
if (otherSemanticNode.children && hasSemantic(otherSemanticNode.children, semanticNode)) {
return true
}
}
}
return false
}
/**
* Copies and extends the semantic node in `semanticNodeArray` if it is
* either `union()` or `intersect()` with the property `isComplete`, which
* indicates to `reducedUnion()` that `semanticNodeArray` reached its parent
* `intersect()`. If `semanticNodeArray` does not contain either specified
* semantic function, returns the array unchanged.
*
* Invoke from `semantic.reduce()` upon reducing the LHS `intersect()` with
* the single-node RHS `semanticNodeArray`.
*
* If `semanticNodeArray` contains `union()`, assigns `isComplete` to the
* semantic node to prevent future `reduceUnion()` invocations from moving
* the `union()` semantic node too far up its semantic tree. If the node
* already has `isComplete`, marks instances of `intersect()` among its
* children with `isComplete` to prevent future `reduceUnion()` invocations
* from incorrectly distributing the LHS semantic that follows the `union()`
* among the arguments of its `intersect()` children.
*
* If `semanticNodeArray` contains `intersect()`, assigns `isComplete` to
* the semantic node to prevent future `reduceUnion()` invocations from
* incorrectly distributing the LHS semantic that follows a future `union()`
* semantic among the arguments of instances of `intersect()` within the
* `union()` semantic.
*
* This function does not mutate `semanticNodeArray`, which is a shared
* resource; rather, it copies the array if changes are needed, else returns
* the original array.
*
* @private
* @static
* @param {Object[]} semanticNodeArray The single node semantic array in
* which to copy and mark complete an instance of `union()` or
* `intersect()`, if any.
* @returns {Object[]} Returns a copy of `semanticNodeArray` with its node
* extended with the `isComplete` property, if applicable, else
* `semanticNodeArray` unchanged.
*/
function completeSingleNodeConjunctionSemantic(semanticNodeArray) {
if (semanticNodeArray.length !== 1) {
util.logError('completeSingleNodeConjunctionSemantic: Invoked with multi-node semantic array:', semanticNodeArray)
throw new Error('Ill-formed semantic reduction')
}
var semanticNode = semanticNodeArray[0]
/**
* If `semanticNode` is a `union()` semantic, assign `isComplete` to the
* node to prevent future `reduceUnion()` invocations from moving the
* `union()` semantic node too far up its semantic tree.
*
* If the node already has `isComplete`, mark instances of `intersect()`
* among `semanticNode.children` with `isComplete` to prevent future
* `reduceUnion()` invocations from incorrectly distributing the LHS
* semantic that follows the `union()` among the arguments of `intersect()`
* children in `semanticNode.children`.
*
* In the grammar, rules with the `union()` semantic follow the LHS semantic
* function to which they apply. `reduceUnion()` moves instances of
* `union()` up a semantic tree and distributes the outer LHS semantic
* function(s) among the `union()` semantic arguments. For example:
* LHS: `lhsFunc()`
* RHS: `union(0,intersect(1,followers(me)))`