-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path7guis.js
1245 lines (1138 loc) · 54 KB
/
7guis.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 dale = window.dale, teishi = window.teishi, lith = window.lith, c = window.c, B = window.B;
var type = teishi.type, clog = teishi.clog, inc = teishi.inc;
B.mount ('body', function () {
return [
['style', [
['body', {padding: 10}]
]],
['h1', ['7GUIs tasks, as described ', ['a', {href: 'https://7guis.github.io/7guis/tasks'}, 'here']]],
['br']
];
});
var views = {};
// *** COUNTER ***
views.counter = function () {
return B.view ('counter', function (counter) {
if (counter === undefined) counter = 0;
return ['div', [
['h2', 'Counter'],
['input', {readonly: true, value: counter}],
['button', {onclick: B.ev ('set', 'counter', counter + 1)}, 'Count']
]];
});
}
B.mount ('body', views.counter);
// *** TEMPERATURE CONVERTER ***
views.converter = function () {
return ['div', [
['h2', 'Temperature converter'],
B.view (['temperature', 'celsius'], function (celsius) {
return ['input', {
onchange: B.ev ('set', ['temperature', 'celsius']),
value: celsius
}];
}),
['label', ['LITERAL', ' Celsius = ']],
B.view (['temperature', 'fahrenheit'], function (fahrenheit) {
return ['input', {
onchange: B.ev ('set', ['temperature', 'fahrenheit']),
value: fahrenheit
}];
}),
['label', ['LITERAL', ' Fahrenheit']]
]];
}
B.respond ('change', ['temperature', /celsius|fahrenheit/], function (x, value) {
value = parseInt (value);
if (isNaN (value)) return;
if (x.path [1] === 'celsius') B.call (x, 'set', ['temperature', 'fahrenheit'], Math.round (value * 9/5 + 32));
if (x.path [1] === 'fahrenheit') B.call (x, 'set', ['temperature', 'celsius'], Math.round ((value - 32) * 5/9));
});
B.mount ('body', views.converter);
// *** FLIGHT BOOKER ***
views.booker = function () {
return ['div', [
['style', ['input.invalid', {'background-color': 'red'}]],
['h2', 'Flight booker'],
B.view (['flight', 'type'], function (type) {
return ['select', {value: type, onchange: B.ev ('set', ['flight', 'type'])}, [
['option', {value: 'one-way'}, 'one-way flight'],
['option', {value: 'return'}, 'return flight'],
]];
}),
['br'], ['br'],
B.view (['flight', 'departure'], function (departure) {
return ['input', {
'class': departure.input && ! departure.date ? 'invalid' : false,
value: departure.input,
onchange: B.ev ('set', ['flight', 'departure', 'input']),
oninput: B.ev ('set', ['flight', 'departure', 'input'])
}];
}),
['br'], ['br'],
B.view ([['flight', 'type'], ['flight', 'return']], function (type, Return) {
return ['input', {
'class': type === 'return' && Return.input && ! Return.date ? 'invalid' : false,
disabled: type !== 'return',
value: Return.input,
onchange: B.ev ('set', ['flight', 'return', 'input']),
oninput: B.ev ('set', ['flight', 'return', 'input'])
}];
}),
['br'], ['br'],
B.view ([['flight', 'type'], ['flight', 'departure', 'date'], ['flight', 'return', 'date']], function (type, departureDate, returnDate) {
var disabled;
if (type !== 'return') disabled = ! departureDate;
else disabled = ! departureDate || ! returnDate || returnDate <= departureDate;
return ['button', {disabled: disabled, onclick: B.ev ('flight', 'book')}, 'Book'];
})
]];
}
B.mrespond ([
['change', ['flight', /departure|return/, 'input'], function (x, value) {
var date = value.split ('.');
date = new Date (date [2] + '-' + date [1] + '-' + date [0]).getTime ();
if (isNaN (date)) return B.call (x, 'rem', ['flight', x.path [1]], 'date');
B.call (x, 'set', ['flight', x.path [1], 'date'], date);
}],
['flight', 'book', function (x) {
var message = 'You have booked a ' + (B.get ('flight', 'type') || 'one-way') + ' flight on ' + B.get ('flight', 'departure', 'input');
if (B.get ('flight', 'type') === 'return') message += ' returning on ' + B.get ('flight', 'return', 'input');
alert (message);
}],
]);
B.call ('set', ['flight', 'departure', 'input'], '01.01.2020');
B.call ('set', ['flight', 'return', 'input'], '01.01.2020');
B.mount ('body', views.booker);
// *** TIMER ***
views.timer = function () {
return ['div', [
['style', [
['div.progress', {'border': 'solid 1px black', 'height': 15, width: 150}, ['div', {'background-color': 'blue', height: 1}]]
]],
['h2', 'Timer'],
['label', {style: 'float: left'}, ['Elapsed time:', ['LITERAL', ' ']]],
['div', {'class': 'progress', style: 'float: left'}, B.view ('timer', function (timer) {
var width = Math.min (100, 100 * (timer.elapsed || 0) / timer.total);
return ['div', {style: 'width: ' + width + '%'}];
})],
['br'],
B.view ('timer', function (timer) {
return ['div', (timer.elapsed || 0) + 's'];
}),
['label', {style: 'float: left'}, ['Duration:', ['LITERAL', ' ']]],
B.view (['timer', 'total'], function (total) {
return ['input', {
type: 'range',
min: 0,
max: 60,
value: total,
oninput: B.ev ('update', 'timer', {raw: 'this.value'})
}]
}),
B.view ('timer', function (timer) {
var width = Math.min (100, 100 * (timer.elapsed || 0) / timer.total);
return ['div', {style: 'width: ' + width + '%'}];
}),
['br'],
['button', {onclick: B.ev ('set', ['timer', 'elapsed'], 0)}, 'Reset']
]];
}
B.mrespond ([
['update', 'timer', function (x, value) {
B.call (x, 'set', ['timer', 'total'], value);
}],
['timer', 'tick', function (x) {
var time = B.get ('timer', 'elapsed') || 0;
if (time > B.get ('timer', 'total')) return;
B.call (x, 'set', ['timer', 'elapsed'], (Math.round (time * 10) + 1) / 10);
}]
]);
setInterval (function () {
B.call ('timer', 'tick');
}, 100);
B.call ('set', ['timer', 'total'], 30);
B.mount ('body', views.timer);
// *** CRUD ***
views.crud = function () {
return ['div', [
['style', [
['li.selected', {'background-color': 'blue', color: 'white'}],
['div.left, div.right', {'float': 'left', padding: 10}],
['div.right label', {width: 100}],
['div.right input', {width: 100}],
['div.left ul', {'list-style-type': 'none', padding: 0, border: 'solid 1px black'}],
['div.left ul li', {padding: 5}],
]],
['h2', 'CRUD'],
['div', {class: 'left'}, [
['label', {style: 'float: left'}, ['Filter prefix:', ['LITERAL', ' ']]],
B.view (['crud', 'filter'], function (filter) {
return ['input', {style: 'float: left; width: 50px', value: filter, oninput: B.ev ('set', ['crud', 'filter'])}];
}),
['br'],
B.view ([['crud', 'people'], ['crud', 'filter'], ['crud', 'selected']], function (people, filter, selected) {
return ['ul', {style: 'height: 150px'}, dale.go (people, function (person, k) {
if (filter !== undefined && filter !== '' && ! person.surname.toLowerCase ().match (filter.toLowerCase ())) return;
return ['li', {'class': k === selected ? 'selected' : '', onclick: B.ev ('set', ['crud', 'selected'], k)}, person.surname + ', ' + person.name];
})];
}),
]],
['div', {class: 'right'}, [
['label', {style: 'float: left'}, ['Name:', ['LITERAL', ' ']]],
B.view (['crud', 'new', 'name'], function (name) {
return ['input', {value: name, oninput: B.ev ('set', ['crud', 'new', 'name'])}];
}),
['br'],
['label', {style: 'float: left'}, ['Surname:', ['LITERAL', ' ']]],
B.view (['crud', 'new', 'surname'], function (surname) {
return ['input', {value: surname, oninput: B.ev ('set', ['crud', 'new', 'surname'])}];
}),
]],
B.view ([['crud', 'new', 'name'], ['crud', 'new', 'surname'], ['crud', 'selected']], function (name, surname, selected) {
return ['div', {style: 'clear: both'}, [
['button', {disabled: (name || '').length === 0 || (surname || '').length === 0, onclick: B.ev ('add', ['crud', 'people'], {name: name, surname: surname})}, 'Create'],
['button', {disabled: selected === undefined, onclick: B.ev ('set', ['crud', 'people', selected || 0], {name: name, surname: surname})}, 'Update'],
['button', {disabled: selected === undefined, onclick: B.ev (['rem', ['crud', 'people'], selected], ['rem', 'crud', 'selected'], ['rem', 'crud', 'new'])}, 'Delete'],
]];
})
]]
}
B.respond ('change', ['crud', 'selected'], function (x) {
// We need to copy the object, otherwise changes to crud.new will be done to crud.people.SELECTED too.
B.call (x, 'set', ['crud', 'new'], teishi.copy (B.get ('crud', 'people', B.get ('crud', 'selected'))));
});
B.call ('set', ['crud', 'people'], [{name: 'Hans', surname: 'Emil'}, {name: 'Max', surname: 'Mustermann'}, {name: 'Roman', surname: 'Tisch'}]);
B.mount ('body', views.crud);
// *** CIRCLE DRAWER ***
views.drawer = function () {
return ['div', [
['style', [
['div.circles', {'width, height': 300, border: 'solid 1px black', margin: 10}, ['svg', {'width, height': 1}]]
]],
['h2', ['Circle drawer']],
['div', [
['button', {onclick: B.ev ('undo', 'history')}, 'Undo'],
['button', {onclick: B.ev ('redo', 'history')}, 'Redo']
]],
B.view ([['drawer', 'position'], ['drawer', 'history'], ['drawer', 'selected'], ['drawer', 'edit']], function (position, history, selected, edit) {
var circles = resolveCircles (position, history);
return ['div', {
'class': 'circles',
style: edit ? 'opacity: 0.5' : '',
onmousemove: edit ? undefined : B.ev ('move', 'mouse', {raw: 'event'}),
onclick: edit ? undefined : B.ev ('create', 'circle', {raw: 'event'})
}, ['LITERAL', '<svg>' + dale.go (circles, function (circle) {
var fill = circle.id === selected ? 'purple' : 'none';
// We stop propagation of the click to not draw another circle if we're selecting a circle to edit it. We return false to avoid the context menu from appearing.
var oncontextmenu = edit ? '' : 'event.stopPropagation (); ' + B.ev ('set', ['drawer', 'edit'], {id: circle.id, radius: circle.radius, x: circle.x, y: circle.y}).replace (/"/g, '\'') + ' return false';
return '<circle id="c' + circle.id + '" cx="' + circle.x + '" cy="' + circle.y + '" r="' + circle.radius + '" stroke="black" stroke-width="1" fill="' + fill + '" oncontextmenu="' + oncontextmenu + '"/>';
}).join ('\n')]];
}),
B.view (['drawer', 'edit'], function (edit) {
if (! edit) return ['span'];
return ['div', {'class': 'modal'}, [
['p', 'Adjust diameter of circle at (' + edit.x + ', ' + edit.y + ')'],
['input', {
type: 'range',
min: 0,
max: 150,
value: edit.radius,
oninput: B.ev (['resizeTemp', 'circle', edit.id, {raw: 'parseInt (this.value)'}], ['set', ['drawer', 'edit', 'radius'], {raw: 'parseInt (this.value)'}])
}],
['button', {onclick: B.ev ('resize', 'circle', edit.id, edit.radius)}, 'Done']
]];
})
]];
}
var resolveCircles = function (position, history) {
var circles = {};
dale.go (position === undefined ? history : history.slice (0, position), function (change) {
if (change.op === 'create') circles [change.id] = teishi.copy (change);
if (change.op === 'resize') circles [change.id].radius = change.radius;
});
return dale.go (circles, function (circle) {return circle});
}
var distance = function (p1, p2) {
return Math.pow (Math.pow (p1.x - p2.x, 2) + Math.pow (p1.y - p2.y, 2), 0.5);
}
B.mrespond ([
['append', 'history', function (x, change) {
var position = B.get ('drawer', 'position') || 0, history = B.get ('drawer', 'history') || [];
// We remove the history after the current position, if any.
history = history.slice (0, position);
history.push (change);
B.call (x, 'set', ['drawer', 'history'], history);
B.call (x, 'set', ['drawer', 'position'], position + 1);
}],
['create', 'circle', function (x, ev) {
B.call (x, 'append', 'history', {op: 'create', id: teishi.time (), radius: 20, x: ev.offsetX, y: ev.offsetY});
}],
['resize', 'circle', function (x, id, radius) {
B.call (x, 'rem', 'drawer', 'edit');
B.call (x, 'append', 'history', {op: 'resize', id: id, radius: radius});
}],
['resizeTemp', 'circle', function (x, id, radius) {
c ('#c' + id).setAttribute ('r', radius);
}],
['move', 'mouse', function (x, ev) {
// We slice circles to make a shallow copy of them, so we can sort the copied array of circles without affecting the order of the original one.
var circles = resolveCircles (B.get ('drawer', 'position'), B.get ('drawer', 'history')).slice ();
if (circles.length === 1) circles [0].d = distance ({x: ev.offsetX, y: ev.offsetY}, circles [0]);
else {
// We sort circles so that the closest one to the mouse is at the beginning of the array.
circles.sort (function (c1, c2) {
// We put the distances on the circles to already have them.
c1.d = distance ({x: ev.offsetX, y: ev.offsetY}, c1);
c2.d = distance ({x: ev.offsetX, y: ev.offsetY}, c2);
// If distances are the same, prefer the newest circle (largest id)
if (c1.d === c2.d) return c1.id - c2.id;
return c1.d - c2.d;
});
}
var selected = dale.stopNot (circles, undefined, function (circle) {
if (circle.d < circle.radius) return circle.id;
});
B.call (x, 'set', ['drawer', 'selected'], selected);
}],
['undo', 'history', function (x) {
var position = B.get ('drawer', 'position'), history = B.get ('drawer', 'history') || [];
if (history.length === 0) return;
B.call (x, 'set', ['drawer', 'position'], Math.max (0, position - 1));
}],
['redo', 'history', function (x) {
var position = B.get ('drawer', 'position'), history = B.get ('drawer', 'history') || [];
if (history.length === 0) return;
B.call (x, 'set', ['drawer', 'position'], Math.min (history.length, position + 1));
}]
]);
B.mount ('body', views.drawer);
// *** EARLEY PARSER ***
// This implementation of an Earley parser owes a debt of gratitude to Lurchmath's implementation of the Earley parser (https://github.com/lurchmath/earley-parser/blob/master/earley-parser.litcoffee), especially for the crucial bit of how to construct the parse tree inside the completer function.
// `input` is a string, `grammar` is an object represeting a grammar (see the examples below by way of definition)
// `options` is an optional argument with keys `printLogs` (by default `false`, if truthy you'll see a lot of debugging info that is useful to understand the parser), `skipCategories` (by default `false`, if truthy the parser will only add terminals to the parse tree) and `collapseBranches`, which will unwrap nested arrays of the form `[...[X]...]` into `[X]` (where `...` represents a number of `[` and `]`).
var earleyParser = function (input, grammar, options) {
options = options || {};
var k = {d: '•', a: '→', s: 'ə'};
var printState = function (state) {
return state [0] + ' ' + state [1] + ' ' + JSON.stringify (state [2]).replace (/"/g, '').replace (/,/g, ', ');
}
var printRule = function (rule) {
return rule [0] + k.a + rule [1];
}
var log = options.printLogs ? clog : function () {};
if (teishi.stop ('earleyParser', [
['input', input, 'string'],
['grammar', grammar, 'object'],
function () {
return [
dale.go (['terminals', 'nonterminals'], function (charType) {
return [
['grammar.' + charType, grammar [charType], 'array'],
function () {return ['grammar.' + charType + ' length', grammar [charType].length, {min: 1}, teishi.test.range]},
['grammar.' + charType, grammar [charType], 'string', 'each'],
dale.go (grammar [charType], function (character, k) {
return ['grammar.' + charType + ' [' + k + '] length', character.length, 1, teishi.test.equal];
}),
];
}),
['grammar.root', grammar.root, 'string'],
['grammar.root', grammar.root, grammar.nonterminals, 'oneOf', teishi.test.equal],
['grammar.rules', grammar.rules, 'array'],
['grammar.rules', grammar.rules, 'array', 'each'],
dale.go (grammar.rules, function (rule, k) {
return [
['grammar rule [k] length', rule.length, 2, teishi.test.equal],
['grammar rule [k]', rule, 'string', 'each'],
function () {return [
['grammar.rule [k] left side length', rule [0].length, 1, teishi.test.equal],
['grammar.rule [k] left side character', rule [0], grammar.nonterminals, 'oneOf', teishi.test.equal],
['grammar.rule [k] right side characters', rule [1].split (''), grammar.nonterminals.concat (grammar.terminals), 'eachOf', teishi.test.equal],
]}
];
})
];
},
])) return false;
var rootAtLeft = dale.stop (grammar.rules, true, function (rule) {
return rule [0] === grammar.root;
});
if (! rootAtLeft) return clog ('There must be at least one rule that has the root of the grammar at its left.');
var forbiddenCharacter = dale.stop (grammar.nonterminals.concat (grammar.terminals), true, function (character) {
return inc (dale.go (k, function (v2) {return v2}), character);
});
if (forbiddenCharacter) return clog ('The characters `•`, `→` and `ə` cannot be used in the grammar');
/*
We initialize `states`, an array that will have N+1 state sets (where N is the length of input).
A state set is an array of states.
A state is an array of the form `['X→...•...', INTEGER, [...]]`.
The first element of a state is a string starting with a nonterminal, an arrow pointing to the production rule, and then a dot denoting the marked character, which can be preceded or followed by terminals and nonterminals. For example, 'E→•E+T'. The marked character is the character to the *right* of the dot.
The second element of a state is the *origin position*, an integer that denotes the position in the input at which the matching of this production rule began.
The third element of a state is a parse tree, which is an array. For a parse tree (or a section of the parse tree) that is `[X, ...]`, the nonterminal X maps to all the other elements inside that array.
*/
var states = dale.go (dale.times (input.length + 1, 0), function (index) {
// The first state set (the one at position 0) is initialized with an initial state.
// Note we use `ə` as a special character to represent the beginning of the string.
if (index === 0) {
log ('adding initial state to 0', printState ([k.s + k.a + k.d + grammar.root, 0, []]));
return [[k.s + k.a + k.d + grammar.root, 0, []]];
}
// All other state sets start empty.
else return [];
});
var repeatedState = function (current, newState) {
return dale.stop (states [current], true, function (state) {
// We only compare the first two elements of a state to see if it's the same to another state - we ignore the partial parse tree in the comparison.
return teishi.eq (newState.slice (0, 2), state.slice (0, 2));
}) || false;
}
// This function returns a new string with the dot advanced by one position in the production rule.
var moveDot = function (string) {
var markedPosition = string.indexOf (k.d) + 2;
return string.slice (0, markedPosition).replace (k.d, '') + k.d + string.slice (markedPosition);
}
// The predictor is invoked when there's a nonterminal to the right of the dot.
// The predictor adds states to the current state set.
var predictor = function (current, state) {
var markedPosition = state [0].indexOf (k.d) + 1;
// Iterate the rules.
dale.go (grammar.rules, function (rule) {
if (rule [0] !== state [0] [markedPosition]) return;
// If the left side of the rule is the nonterminal X that is marked by the dot in state, we construct a new state with a production rule `X→•Y`, where Y is the right side of the production rule. The origin is set to `current`, which is the index of the current state set being processed. The parse tree itself is set to an empty array.
var newState = [rule [0] + k.a + k.d + rule [1], current, []];
if (repeatedState (current, newState)) return;
// If the state is not in the current state set, we add it.
log ('predictor adding to state set', current, printState (newState), 'from state', printState (state), 'and rule', printRule (rule));
states [current].push (newState);
});
}
// The scanner is invoked when there's a terminal to the right of the dot.
// The scanner adds states to the *next* state set.
var scanner = function (current, state) {
var markedPosition = state [0].indexOf (k.d) + 1;
if (input [current] !== state [0] [markedPosition]) return;
// If the character at index `current` of the input is equal to the marked character in the production rule, we construct a new state with the same production rule, except that we advance the dot by one character.
// The `origin` is the same in the new rule.
// The tree of the new state is a copy of the the tree of the current state; we then push the current nonterminal to the tree.
var tree = teishi.copy (state [2]);
tree.push (input [current]);
var newState = [moveDot (state [0]), state [1], teishi.copy (tree)];
if (repeatedState (current + 1, newState)) return;
// If the state is not in the next state set, we add it.
log ('scanner adding to state set', current + 1, printState (newState), 'from state', printState (state));
states [current + 1].push (newState);
}
// The completer is invoked when the dot is at the end of the production
// The completer adds states to the current state set.
var completer = function (current, state) {
// We iterate the state set k, where k is the `origin` of the state
dale.go (states [state [1]], function (State, i) {
if (State [0] [State [0].indexOf (k.d) + 1] !== state [0] [0]) return;
// If the character to the right of the dot is the nonterminal at the left of the state, we construct a new state.
// To construct the parse tree of the new state, we start by copying the parse tree of the state we passed as an argument.
var tree = teishi.copy (state [2]);
// If options.skipNonterminals is not set, we add the character at the left side of the state we passed as an argument to the beginning of the tree.
if (! options.skipNonterminals) tree.unshift (state [0] [0]);
// If options.collapseBranches is set, we unwrap the tree.
if (options.collapseBranches && tree.length === 1) tree = tree [0];
// We create a new tree by copying the tree of the state we're completing.
var tree2 = teishi.copy (State [2]);
// We then push to this tree the tree we made earlier with the nonterminal, plus the tree coming from the state passed as an argument.
tree2.push (tree);
var newState = [moveDot (State [0]), State [1], tree2];
if (repeatedState (current, newState)) return;
// If the state is not in the next state set, we add it.
log ('completer adding to state set', current, printState (newState), 'from state', printState (state), 'and previous state', printState (State));
states [current].push (newState);
});
}
var t = teishi.time (), current = 0;
// The `next` function is recursive and is in charge of either adding more states or deciding that we're done recognizing the input.
// The return value of `next` is irrelevant. All its work is done through reading and writing state to the `states` variable.
var next = function () {
log ('Processing state set', current);
// We note the number of current states at the beginning of the execution of `next`. This number will tell us later whether the current execution of `next` added more states to the current set of states.
var numberOfCurrentStates = states [current].length;
// For each of the current states:
dale.go (states [current], function (state, i) {
// The marked character is the character at the right of the dot.
var marked = state [0] [state [0].indexOf (k.d) + 1];
// If the marked character is a nonterminal, we invoke the predictor.
if (inc (grammar.nonterminals, marked)) return predictor (current, state, current + ':' + i);
// If the marked character is a terminal, we invoke the scanner.
if (inc (grammar.terminals, marked)) return scanner (current, state, current + ':' + i);
// If there is no marked character, the dot is at the end of the production rule. We invoke the completer.
// completer: dot at end of production
if (marked === undefined) return completer (current, state, current + ':' + i);
// No further cases are possible.
});
// If the number of current states increased during the current execution of `next`, we invoke `next` recursively.
if (states [current].length > numberOfCurrentStates) return next ();
// If we are here, the number of current states has not increased.
// If `current` is less than the length of the input, we increase `current` and invoke `next` recursively.
if (current < input.length) {
current++;
return next ();
}
// If we are here, we are on the Nth step, where N is the length of the input, and we also cannot add any further states. This means we're done recognizing.
// We check whether the input conforms to the grammar.
// We iterate the states on the current step until we find the first one that is a final state.
var tree = dale.stopNot (states [current], undefined, function (state, i) {
// If the start starts with ə and it comes from 0, this is a final state. We return `true` to indicate that it is a final state and stop the loop.
if (state [0] === k.s + k.a + grammar.root + k.d && state [1] === 0) return state [2];
});
// We remove the outermost part of the tree since there will always be an extra array wrapper at the top level.
if (tree) tree = tree [0];
var output = {valid: !! tree, input: input, length: input.length, time: Date.now () - t, tree: tree};
log ('Recognizer output', output);
return output;
}
return next ();
}
var grammars = {};
grammars.AE = {
terminals: ['a', '+', '*'],
nonterminals: ['E', 'T', 'P'],
root: 'E',
rules: [
['E', 'T'],
['E', 'E+T'],
['T', 'P'],
['T', 'T*P'],
['P', 'a']
]
}
grammars.UBDA = {
terminals: ['x'],
nonterminals: ['A'],
root: 'A',
rules: [
['A', 'x'],
['A', 'AA'],
]
}
grammars.BK = {
terminals: ['x'],
nonterminals: ['K', 'J', 'F', 'I'],
root: 'K',
rules: [
['K', ''],
['K', 'KJ'],
['J', 'F'],
['J', 'I'],
['F', 'x'],
['I', 'x'],
]
}
grammars.PAL = {
terminals: ['x'],
nonterminals: ['A'],
root: 'A',
rules: [
['A', 'x'],
['A', 'xAx']
]
}
grammars.G1 = {
terminals: ['a', 'b'],
nonterminals: ['S', 'A'],
root: 'S',
rules: [
['S', 'Ab'],
['A', 'a'],
['A', 'Ab']
]
}
grammars.G2 = {
terminals: ['a', 'b'],
nonterminals: ['S', 'B'],
root: 'S',
rules: [
['S', 'aB'],
['B', 'aB'],
['B', 'b']
]
}
grammars.G3 = {
terminals: ['a', 'b'],
nonterminals: ['S'],
root: 'S',
rules: [
['S', 'ab'],
['S', 'aSb']
]
}
grammars.G4 = {
terminals: ['a', 'b', 'c', 'd'],
nonterminals: ['S', 'A', 'B'],
root: 'S',
rules: [
['S', 'AB'],
['A', 'a'],
['A', 'Ab'],
['B', 'bc'],
['B', 'bB'],
['B', 'Bd']
]
}
grammars.PC = {
terminals: ['(', ')', 'p', 'q', 'r', '⊃', '∧', '∨', '˜', '`'],
nonterminals: ['F', 'C', 'S', 'P', 'U', 'L'],
root: 'F',
rules: [
['F', 'C'],
['F', 'S'],
['F', 'P'],
['F', 'U'],
['C', 'U⊃U'],
['U', '(F)'],
['U', '˜U'],
['U', 'L'],
['L', 'L`'],
['L', 'p'],
['L', 'q'],
['L', 'r'],
['S', 'U∨S'],
['S', 'U∨U'],
['P', 'U∧P'],
['P', 'U∧U']
]
}
grammars.GRE = {
terminals: ['a', 'b', 'd' ,'e'],
nonterminals: ['X', 'Y'],
root: 'X',
rules: [
['X', 'a'],
['X', 'Xb'],
['X', 'Ya'],
['Y', 'e'],
['Y', 'YdY']
]
}
grammars.NSE = {
terminals: ['a', 'b', 'c', 'd'],
nonterminals: ['S', 'A', 'B', 'C', 'D'],
root: 'S',
rules: [
['S', 'AB'],
['A', 'a'],
['A', 'SC'],
['B', 'b'],
['B', 'DB'],
['C', 'c'],
['D', 'd']
]
}
dale.go ([
['a+a*a', grammars.AE],
['xxxx', grammars.UBDA],
['', grammars.BK],
['xxxx', grammars.BK],
['x', grammars.PAL],
// The test below is the only test that should return `false`, since grammar PAL only accepts an input made of an odd number of `x`.
['xx', grammars.PAL, 'invalid'],
['abbb', grammars.G1],
['aaab', grammars.G2],
['aaabbb', grammars.G3],
['abbbcd', grammars.G4],
['p', grammars.PC],
['(p∧q)', grammars.PC],
['(p`∧q)∨r∨p∨q`', grammars.PC],
['p⊃((q⊃˜(r`∨(p∧q)))⊃(q`∨r))', grammars.PC],
['˜(˜p`∧(q∨r)∧p`)', grammars.PC],
['((p∧q)∨(q∧r)∨(r∧p`))⊃˜((p`∨q`)∧(r`∨p))', grammars.PC],
['ededea', grammars.GRE],
['ededeabbbb', grammars.GRE],
['ededeabbbbbbbbbb', grammars.GRE],
['ededeabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', grammars.GRE],
['ededededeabb', grammars.GRE],
['edededededededeabb', grammars.GRE],
['ededededededededeabb', grammars.GRE],
['adbcddb', grammars.NSE],
['adddbcbcdddbcddddb', grammars.NSE],
['addddddddddddddddddb', grammars.NSE],
['abcbcbcdddbcdbcddbcddddb', grammars.NSE],
['abcdbcddbcdddbcb', grammars.NSE],
], function (testCase) {
// UNCOMMENT TO TEST PARSER
/*
var result1 = earleyParser (testCase [0], testCase [1]);
var result2 = earleyParser (testCase [0], testCase [1], {skipNonterminals: true, collapseBranches: true});
if (testCase [2]) result1.valid = ! result1.valid;
if (testCase [2]) result2.valid = ! result2.valid;
if (! result1.valid) clog ('Invalid parse', result1);
if (! result2.valid) clog ('Invalid parse', result2);
*/
});
// *** CELLS ***
/*
Main refererences:
- https://www.artima.com/pins1ed/the-scells-spreadsheet.html (original specification and implementation)
- https://andrewgreenh.github.io/7guis/#/cells (a great React implementation)
What is allowed in a cell:
- Number
- Text
- Formula
A formula is an equals sign followed by one of the following:
- Number
- Coordinate (e.g.: "A1")
- Function application
A function application is one of the following functions:
- add : sums one or more arguments. Arguments can be numbers, the coordinate of a cell that has a number value, a range of cells that have number values, or a function application that returns a number.
- sub: subtracts the second argument from the first. The function only takes two arguments. Arguments can be numbers, the coordinate of a cell that has a number value, or a function application that returns a number (however, it cannot be a range).
- mul: multiplies one or more arguments. Arguments can be numbers, the coordinate of a cell that has a number value, a range of cells that have number values, or a function application that returns a number.
- div: divides the second argument into the first. The function only takes two arguments. Arguments can be numbers, the coordinate of a cell that has a number value, or a function application that returns a number (however, it cannot be a range).
- mod: takes the modulo second argument of the first. The function only takes two arguments. Arguments can be numbers, the coordinate of a cell that has a number value, or a function application that returns a number (however, it cannot be a range).
Note: the `sum` and `prod` operations of SCells are not implemented since we have modified `add` and `mul` to take multiple arguments.
*/
// We use Cyrillic capital letters for specifying nonterminals since we don't have a tokenizer and we want to use all ASCII letters as terminals
var cellsGrammar = {
terminals: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*_-()[]{}:., ='.split (''),
nonterminals: 'ЗЦБСКЛРЧВТХФЭИПпЯ'.split (''),
root: 'Я',
rules: []
};
// Ц: non-zero digit (1-9), З: digit (0-9)
// Б: letters (A-Z & a-z), C: symbols (A-Z, a-z, 0-9 & a bunch of symbols except equals)
dale.go (dale.times (10, 0), function (n) {
cellsGrammar.rules.push (['З', n + '']);
cellsGrammar.rules.push (['С', n + '']);
if (n !== 0) cellsGrammar.rules.push (['Ц', n + '']);
});
dale.go ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split (''), function (l) {
cellsGrammar.rules.push (['Б', l]);
cellsGrammar.rules.push (['Б', l.toLowerCase ()]);
cellsGrammar.rules.push (['С', l]);
cellsGrammar.rules.push (['С', l.toLowerCase ()]);
});
dale.go ('!@#$%^&*_-()[]{}:., '.split (''), function (s) {
cellsGrammar.rules.push (['С', s]);
});
cellsGrammar.rules = cellsGrammar.rules.concat ([
// К: coordinate ($?[A-Z]$?[1-9][0-0])
['К', 'БЧ'],
['К', '$БЧ'],
['К', 'Б$Ч'],
['К', '$Б$Ч'],
// Р: range (К:К)
['Р', 'К:К'],
// Ч: right-side number sequence ([0-9]+)
['Ч', 'З'],
['Ч', 'ЗЧ'],
// Л: left-side number sequence ([1-9][0-9]+)
['Л', 'Ц'],
['Л', 'ЦЧ'],
// В: numeric expression
['В', 'Л'],
['В', '-Л'],
['В', 'Л.Ч'],
['В', '-Л.Ч'],
// Т: text
['Т', 'С'],
['Т', 'СТ'],
// Х: optional whitespace
['Х', ''],
['Х', ' '],
['Х', ' Х'],
// Ф: formula: =coordinate, =number, =function application
['Ф', '=К'],
['Ф', '=В'],
['Ф', '=Э'],
// Э: function application
['Э', 'ИХ(ХПХ)Х'],
// П: parameter list
['П', 'п'],
['П', 'пХ,ХПХ'],
// п: parameter: number, coordinate, range, function application
['п', 'В'],
['п', 'К'],
['п', 'Р'],
['п', 'Э'],
// Я: cell: text, number, formula, empty
['Я', 'Т'],
['Я', 'В'],
['Я', 'Ф'],
['Я', '']
]);
// И: function name
dale.go (['add', 'sub', 'mul', 'div', 'mod'], function (functionName) {
return cellsGrammar.rules.push (['И', functionName]);
});
// list of references per cell: ['A1', 'A2']. These are *direct references* only! And if they are already in the references object, they are valid.
var resolveReferences = function (cell, references) {
var output = [];
var recurseReferences = function (cell, firstCall) {
if (inc (output, cell)) return;
if (! firstCall) output.push (cell);
dale.go (references [cell], function (cell) {
recurseReferences (cell);
});
}
recurseReferences (cell, true);
return output.sort ();
}
var flatten = function (tree) {
var output = '';
dale.go (tree, function (v) {
if (teishi.simple (v)) return output += v;
output += flatten (v);
});
return output;
}
var parseCellInput = function (input) {
return earleyParser (input, cellsGrammar, {collapseBranches: true}).tree;
}
var concatenate = function (fun, input) {
var output = '';
dale.go (input, function (v) {
v = fun (v);
output += type (v) === 'string' ? v : v.value;
});
return output;
}
var mapColumns = function (input) {
if (type (input) === 'string') return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf (input);
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' [input];
}
/*
`evaluate` takes a tree from a parsed input. The following can occur:
- If it's an invalid value, it returns an error.
- If it's text or number (or a formula that just contains a number), it returns it.
- If it's a coordinate, it resolves it or returns an error if there's a circular reference.
- If it's a function application it returns its value (resolving any references) and any possible references, or returns an error if there's a circular reference.
Something we haven't implemented but would be interesting to do: copy/paste with shifting of references. The basic idea would be to pass an offset to the function, so that it returns instead a shifted formula, rather than a value.
*/
var evaluate = function (tree, cell, references, rows, returnCoordinate) {
if (tree === undefined) return {error: 'Invalid input'};
// Character or digit
if (tree [0] === 'С' || tree [0] === 'Б' || tree [0] === 'З' || tree [0] === 'Ц') return {value: tree [1]};
// Left/right side of numeric sequence
if (tree [0] === 'Л' || tree [0] === 'Ч') return {value: concatenate (evaluate, tree.slice (1))};
// Text
if (tree [0] === 'Т') {
var value = concatenate (evaluate, tree.slice (1));
// If a number gets matched as text, return it as number. The cleaner alternative to this would be to prefer parse trees that return a number rather than a text, but I don't know how to go about this.
if (value.match (/^-?\d+(\.\d)?$/)) value = parseFloat (value);
return {value: value};
}
// Numeric expression
if (tree [0] === 'В') return {value: parseFloat (concatenate (function (part) {
if (part === '-' || part === '.') return part;
return evaluate (part);
}, tree.slice (1)))};
// Coordinate
if (tree [0] === 'К' || tree [0] === 'COORDINATE') {
var coordinate = tree [0] === 'COORDINATE' ? tree [1] : concatenate (function (part) {
if (part === '$') return '';
return evaluate (part);
}, tree.slice (1));
coordinate = coordinate.toUpperCase ();
if (returnCoordinate) return coordinate;
var referenceList = resolveReferences (coordinate, references);
if (cell === coordinate || inc (referenceList, cell)) return {error: 'Circular reference (' + coordinate + ')'};
try {
var cell = rows [parseInt (coordinate.slice (1)) - 1] [coordinate [0].toUpperCase ()];
}
catch (error) {
var cell = {value: ''};
}
if (cell.error) return {error: cell.error};
else return {value: cell.value, refs: [coordinate]};
}
// Range
if (tree [0] === 'Р') {
var coordA = evaluate (tree [1], cell, references, rows, true);
var coordB = evaluate (tree [3], cell, references, rows, true);
var cols = [coordA [0], coordB [0]];
var Rows = [parseInt (coordA.slice (1)), parseInt (coordB.slice (1))];
if (Rows [0] > Rows [1]) return {error: 'Invalid range'};
if (mapColumns (cols [0]) > mapColumns (cols [1])) return {error: 'Invalid range'};
var error, refs = [];
var values = dale.go (dale.times (1 + Rows [1] - Rows [0], Rows [0]), function (row) {
return dale.go (dale.times (1 + mapColumns (cols [1]) - mapColumns (cols [0]), mapColumns (cols [0])), function (colIndex) {
refs.push (mapColumns (colIndex) + row);
var result = evaluate (['COORDINATE', mapColumns (colIndex) + row], cell, references, rows);
if (result.error) return error = result.error;
return result.value;
});
});
return error ? {error: error} : {values: values, refs: refs};
}
// Cell
if (tree [0] === 'Я') {
if (tree.length === 1) return {value: ''};
return evaluate (tree [1], cell, references, rows);
}
// Formula
if (tree [0] === 'Ф') return evaluate (tree [2], cell, references, rows);
// Function name
if (tree [0] === 'И') return tree.slice (1).join ('');
// Filters out elements and flattens a list of parameters
var processParameterList = function (list, args) {
args = args || [];
dale.go (list, function (item) {
// We ignore whitespace, parentheses and commas
if (item === 'Х' || item === '(' || item === ')' || item === ',' || item [0] === 'Х') return;
if (item [0] === 'П') return processParameterList (item.slice (1), args);
if (item [0] === 'п') return processParameterList (item.slice (1), args);
// We are left with function names or function arguments. We push them to the argument list.
args.push (item);
});
return args;
}
// Function application
if (tree [0] === 'Э') {
var error, args = [], refs = [];
dale.stopNot (processParameterList (tree.slice (1)), undefined, function (v) {
var result = evaluate (v, cell, references, rows);
if (result.error) return error = result.error;
if (result.refs) refs = refs.concat (result.refs);
if (result.value) args.push (result.value);
else dale.go (result.values, function (row) {
dale.go (row, function (value) {
args.push (value);
});
});
});
if (error) return {error: error};
var functionName = evaluate (tree [1]);
if (functionName === 'add' || functionName === 'mul') {
// Because the grammar requires argument lists to have at least a single argument, we don't have to check whether args.length is greater than 0
result = functionName === 'add' ? 0 : 1;
dale.go (args, function (arg) {