-
Notifications
You must be signed in to change notification settings - Fork 21
/
jssm.js
1670 lines (1666 loc) · 56.6 KB
/
jssm.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
// whargarbl lots of these return arrays could/should be sets
import { reduce as reduce_to_639 } from 'reduce-to-639-1';
import { seq, weighted_rand_select, weighted_sample_select, histograph, weighted_histo_key, array_box_if_string, hook_name, named_hook_name } from './jssm_util';
import { shapes, gviz_shapes, named_colors } from './jssm_constants';
import { parse } from './jssm-dot';
import { version } from './version'; // replaced from package.js in build
import { JssmError } from './jssm_error';
/* eslint-disable complexity */
/*********
*
* Return the direction of an arrow - `right`, `left`, or `both`.
*
* ```typescript
* import { arrow_direction } from 'jssm';
*
* arrow_direction('->'); // 'right'
* arrow_direction('<~=>'); // 'both'
* ```
*
* @param arrow The arrow to be evaluated
*
*/
function arrow_direction(arrow) {
switch (String(arrow)) {
case '->':
case '→':
case '=>':
case '⇒':
case '~>':
case '↛':
return 'right';
case '<-':
case '←':
case '<=':
case '⇐':
case '<~':
case '↚':
return 'left';
case '<->':
case '↔':
case '<-=>':
case '←⇒':
case '←=>':
case '<-⇒':
case '<-~>':
case '←↛':
case '←~>':
case '<-↛':
case '<=>':
case '⇔':
case '<=->':
case '⇐→':
case '⇐->':
case '<=→':
case '<=~>':
case '⇐↛':
case '⇐~>':
case '<=↛':
case '<~>':
case '↮':
case '<~->':
case '↚→':
case '↚->':
case '<~→':
case '<~=>':
case '↚⇒':
case '↚=>':
case '<~⇒':
return 'both';
default:
throw new JssmError(undefined, `arrow_direction: unknown arrow type ${arrow}`);
}
}
/* eslint-enable complexity */
/* eslint-disable complexity */
/*********
*
* Return the direction of an arrow - `right`, `left`, or `both`.
*
* ```typescript
* import { arrow_left_kind } from 'jssm';
*
* arrow_left_kind('<-'); // 'legal'
* arrow_left_kind('<='); // 'main'
* arrow_left_kind('<~'); // 'forced'
* arrow_left_kind('<->'); // 'legal'
* arrow_left_kind('->'); // 'none'
* ```
*
* @param arrow The arrow to be evaluated
*
*/
function arrow_left_kind(arrow) {
switch (String(arrow)) {
case '->':
case '→':
case '=>':
case '⇒':
case '~>':
case '↛':
return 'none';
case '<-':
case '←':
case '<->':
case '↔':
case '<-=>':
case '←⇒':
case '<-~>':
case '←↛':
return 'legal';
case '<=':
case '⇐':
case '<=>':
case '⇔':
case '<=->':
case '⇐→':
case '<=~>':
case '⇐↛':
return 'main';
case '<~':
case '↚':
case '<~>':
case '↮':
case '<~->':
case '↚→':
case '<~=>':
case '↚⇒':
return 'forced';
default:
throw new JssmError(undefined, `arrow_direction: unknown arrow type ${arrow}`);
}
}
/* eslint-enable complexity */
/* eslint-disable complexity */
/*********
*
* Return the direction of an arrow - `right`, `left`, or `both`.
*
* ```typescript
* import { arrow_left_kind } from 'jssm';
*
* arrow_left_kind('->'); // 'legal'
* arrow_left_kind('=>'); // 'main'
* arrow_left_kind('~>'); // 'forced'
* arrow_left_kind('<->'); // 'legal'
* arrow_left_kind('<-'); // 'none'
* ```
*
* @param arrow The arrow to be evaluated
*
*/
function arrow_right_kind(arrow) {
switch (String(arrow)) {
case '<-':
case '←':
case '<=':
case '⇐':
case '<~':
case '↚':
return 'none';
case '->':
case '→':
case '<->':
case '↔':
case '<=->':
case '⇐→':
case '<~->':
case '↚→':
return 'legal';
case '=>':
case '⇒':
case '<=>':
case '⇔':
case '<-=>':
case '←⇒':
case '<~=>':
case '↚⇒':
return 'main';
case '~>':
case '↛':
case '<~>':
case '↮':
case '<-~>':
case '←↛':
case '<=~>':
case '⇐↛':
return 'forced';
default:
throw new JssmError(undefined, `arrow_direction: unknown arrow type ${arrow}`);
}
}
/* eslint-enable complexity */
/*********
*
* Internal method meant to perform factory assembly of an edge. Not meant for
* external use.
*
* @internal
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
// TODO add at-param to docblock
function makeTransition(this_se, from, to, isRight, _wasList, _wasIndex) {
const kind = isRight ? arrow_right_kind(this_se.kind) : arrow_left_kind(this_se.kind), edge = {
from,
to,
kind,
forced_only: kind === 'forced',
main_path: kind === 'main'
};
// if ((wasList !== undefined) && (wasIndex === undefined)) { throw new JssmError(undefined, `Must have an index if transition was in a list"); }
// if ((wasIndex !== undefined) && (wasList === undefined)) { throw new JssmError(undefined, `Must be in a list if transition has an index"); }
/*
if (typeof edge.to === 'object') {
if (edge.to.key === 'cycle') {
if (wasList === undefined) { throw new JssmError(undefined, "Must have a waslist if a to is type cycle"); }
const nextIndex = wrapBy(wasIndex, edge.to.value, wasList.length);
edge.to = wasList[nextIndex];
}
}
*/
const action = isRight ? 'r_action' : 'l_action', probability = isRight ? 'r_probability' : 'l_probability';
if (this_se[action]) {
edge.action = this_se[action];
}
if (this_se[probability]) {
edge.probability = this_se[probability];
}
return edge;
}
/*********
*
* This method wraps the parser call that comes from the peg grammar,
* {@link parse}. Generally neither this nor that should be used directly
* unless you mean to develop plugins or extensions for the machine.
*
* Parses the intermediate representation of a compiled string down to a
* machine configuration object. If you're using this (probably don't,) you're
* probably also using {@link compile} and {@link Machine.constructor}.
*
* ```typescript
* import { parse, compile, Machine } from 'jssm';
*
* const intermediate = wrap_parse('a -> b;', {});
* // [ {key:'transition', from:'a', se:{kind:'->',to:'b'}} ]
*
* const cfg = compile(intermediate);
* // { start_states:['a'], transitions: [{ from:'a', to:'b', kind:'legal', forced_only:false, main_path:false }] }
*
* const machine = new Machine(cfg);
* // Machine { _instance_name: undefined, _state: 'a', ...
* ```
*
* This method is mostly for plugin and intermediate tool authors, or people
* who need to work with the machine's intermediate representation.
*
* # Hey!
*
* Most people looking at this want either the `sm` operator or method `from`,
* which perform all the steps in the chain. The library's author mostly uses
* operator `sm`, and mostly falls back to `.from` when needing to parse
* strings dynamically instead of from template literals.
*
* Operator {@link sm}:
*
* ```typescript
* import { sm } from 'jssm';
*
* const switch = sm`on <=> off;`;
* ```
*
* Method {@link from}:
*
* ```typescript
* import * as jssm from 'jssm';
*
* const toggle = jssm.from('up <=> down;');
* ```
*
* `wrap_parse` itself is an internal convenience method for alting out an
* object as the options call. Not generally meant for external use.
*
* @param input The FSL code to be evaluated
*
* @param options Things to control about the instance
*
*/
function wrap_parse(input, options) {
return parse(input, options || {});
}
/*********
*
* Internal method performing one step in compiling rules for transitions. Not
* generally meant for external use.
*
* @internal
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
function compile_rule_transition_step(acc, from, to, this_se, next_se) {
const edges = [];
const uFrom = (Array.isArray(from) ? from : [from]), uTo = (Array.isArray(to) ? to : [to]);
uFrom.map((f) => {
uTo.map((t) => {
const right = makeTransition(this_se, f, t, true);
if (right.kind !== 'none') {
edges.push(right);
}
const left = makeTransition(this_se, t, f, false);
if (left.kind !== 'none') {
edges.push(left);
}
});
});
const new_acc = acc.concat(edges);
if (next_se) {
return compile_rule_transition_step(new_acc, to, next_se.to, next_se, next_se.se);
}
else {
return new_acc;
}
}
/*********
*
* Internal method performing one step in compiling rules for transitions. Not
* generally meant for external use.
*
* @internal
*
*/
function compile_rule_handle_transition(rule) {
return compile_rule_transition_step([], rule.from, rule.se.to, rule.se, rule.se.se);
}
/*********
*
* Internal method performing one step in compiling rules for transitions. Not
* generally meant for external use.
*
* @internal
*
*/
function compile_rule_handler(rule) {
if (rule.key === 'transition') {
return { agg_as: 'transition', val: compile_rule_handle_transition(rule) };
}
if (rule.key === 'machine_language') {
return { agg_as: 'machine_language', val: reduce_to_639(rule.value) };
}
if (rule.key === 'state_declaration') {
if (!rule.name) {
throw new JssmError(undefined, 'State declarations must have a name');
}
return { agg_as: 'state_declaration', val: { state: rule.name, declarations: rule.value } };
}
if (['arrange_declaration', 'arrange_start_declaration',
'arrange_end_declaration'].includes(rule.key)) {
return { agg_as: rule.key, val: [rule.value] };
}
const tautologies = [
'graph_layout', 'start_states', 'end_states', 'machine_name', 'machine_version',
'machine_comment', 'machine_author', 'machine_contributor', 'machine_definition',
'machine_reference', 'machine_license', 'fsl_version', 'state_config', 'theme',
'flow', 'dot_preamble'
];
if (tautologies.includes(rule.key)) {
return { agg_as: rule.key, val: rule.value };
}
throw new JssmError(undefined, `compile_rule_handler: Unknown rule: ${JSON.stringify(rule)}`);
}
/*********
*
* Compile a machine's JSON intermediate representation to a config object. If
* you're using this (probably don't,) you're probably also using
* {@link parse} to get the IR, and the object constructor
* {@link Machine.construct} to turn the config object into a workable machine.
*
* ```typescript
* import { parse, compile, Machine } from 'jssm';
*
* const intermediate = parse('a -> b;');
* // [ {key:'transition', from:'a', se:{kind:'->',to:'b'}} ]
*
* const cfg = compile(intermediate);
* // { start_states:['a'], transitions: [{ from:'a', to:'b', kind:'legal', forced_only:false, main_path:false }] }
*
* const machine = new Machine(cfg);
* // Machine { _instance_name: undefined, _state: 'a', ...
* ```
*
* This method is mostly for plugin and intermediate tool authors, or people
* who need to work with the machine's intermediate representation.
*
* # Hey!
*
* Most people looking at this want either the `sm` operator or method `from`,
* which perform all the steps in the chain. The library's author mostly uses
* operator `sm`, and mostly falls back to `.from` when needing to parse
* strings dynamically instead of from template literals.
*
* Operator {@link sm}:
*
* ```typescript
* import { sm } from 'jssm';
*
* const switch = sm`on <=> off;`;
* ```
*
* Method {@link from}:
*
* ```typescript
* import * as jssm from 'jssm';
*
* const toggle = jssm.from('up <=> down;');
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
* @param tree The parse tree to be boiled down into a machine config
*
*/
function compile(tree) {
const results = {
graph_layout: [],
transition: [],
start_states: [],
end_states: [],
state_config: [],
state_declaration: [],
fsl_version: [],
machine_author: [],
machine_comment: [],
machine_contributor: [],
machine_definition: [],
machine_language: [],
machine_license: [],
machine_name: [],
machine_reference: [],
theme: [],
flow: [],
dot_preamble: [],
arrange_declaration: [],
arrange_start_declaration: [],
arrange_end_declaration: [],
machine_version: []
};
tree.map((tr) => {
const rule = compile_rule_handler(tr), agg_as = rule.agg_as, val = rule.val; // TODO FIXME no any
results[agg_as] = results[agg_as].concat(val);
});
const assembled_transitions = [].concat(...results['transition']);
const result_cfg = {
start_states: results.start_states.length ? results.start_states : [assembled_transitions[0].from],
transitions: assembled_transitions
};
const oneOnlyKeys = [
'graph_layout', 'machine_name', 'machine_version', 'machine_comment',
'fsl_version', 'machine_license', 'machine_definition', 'machine_language',
'theme', 'flow', 'dot_preamble'
];
oneOnlyKeys.map((oneOnlyKey) => {
if (results[oneOnlyKey].length > 1) {
throw new JssmError(undefined, `May only have one ${oneOnlyKey} statement maximum: ${JSON.stringify(results[oneOnlyKey])}`);
}
else {
if (results[oneOnlyKey].length) {
result_cfg[oneOnlyKey] = results[oneOnlyKey][0];
}
}
});
['arrange_declaration', 'arrange_start_declaration', 'arrange_end_declaration',
'machine_author', 'machine_contributor', 'machine_reference', 'state_declaration'].map((multiKey) => {
if (results[multiKey].length) {
result_cfg[multiKey] = results[multiKey];
}
});
return result_cfg;
}
/*********
*
* An internal convenience wrapper for parsing then compiling a machine string.
* Not generally meant for external use. Please see {@link compile} or
* {@link sm}.
*
* @typeparam mDT The type of the machine data member; usually omitted
*
* @param plan The FSL code to be evaluated and built into a machine config
*
*/
function make(plan) {
return compile(wrap_parse(plan));
}
/*********
*
* An internal method meant to take a series of declarations and fold them into
* a single multi-faceted declaration, in the process of building a state. Not
* generally meant for external use.
*
* @internal
*
*/
function transfer_state_properties(state_decl) {
state_decl.declarations.map((d) => {
switch (d.key) {
case 'shape':
state_decl.shape = d.value;
break;
case 'color':
state_decl.color = d.value;
break;
case 'corners':
state_decl.corners = d.value;
break;
case 'linestyle':
state_decl.linestyle = d.value;
break;
case 'text-color':
state_decl.textColor = d.value;
break;
case 'background-color':
state_decl.backgroundColor = d.value;
break;
case 'border-color':
state_decl.borderColor = d.value;
break;
default: throw new JssmError(undefined, `Unknown state property: '${JSON.stringify(d)}'`);
}
});
return state_decl;
}
// TODO add a lotta docblock here
class Machine {
// whargarbl this badly needs to be broken up, monolith master
constructor({ start_states, complete = [], transitions, machine_author, machine_comment, machine_contributor, machine_definition, machine_language, machine_license, machine_name, machine_version, state_declaration, fsl_version, dot_preamble = undefined, arrange_declaration = [], arrange_start_declaration = [], arrange_end_declaration = [], theme = 'default', flow = 'down', graph_layout = 'dot', instance_name, data }) {
this._instance_name = instance_name;
this._state = start_states[0];
this._states = new Map();
this._state_declarations = new Map();
this._edges = [];
this._edge_map = new Map();
this._named_transitions = new Map();
this._actions = new Map();
this._reverse_actions = new Map();
this._reverse_action_targets = new Map(); // todo
this._machine_author = array_box_if_string(machine_author);
this._machine_comment = machine_comment;
this._machine_contributor = array_box_if_string(machine_contributor);
this._machine_definition = machine_definition;
this._machine_language = machine_language;
this._machine_license = machine_license;
this._machine_name = machine_name;
this._machine_version = machine_version;
this._raw_state_declaration = state_declaration || [];
this._fsl_version = fsl_version;
this._arrange_declaration = arrange_declaration;
this._arrange_start_declaration = arrange_start_declaration;
this._arrange_end_declaration = arrange_end_declaration;
this._dot_preamble = dot_preamble;
this._theme = theme;
this._flow = flow;
this._graph_layout = graph_layout;
this._has_hooks = false;
this._has_basic_hooks = false;
this._has_named_hooks = false;
this._has_entry_hooks = false;
this._has_exit_hooks = false;
this._has_global_action_hooks = false;
this._has_transition_hooks = true;
// no need for a boolean has any transition hook, as it's one or nothing, so just test that for undefinedness
this._hooks = new Map();
this._named_hooks = new Map();
this._entry_hooks = new Map();
this._exit_hooks = new Map();
this._global_action_hooks = new Map();
this._any_action_hook = undefined;
this._standard_transition_hook = undefined;
this._main_transition_hook = undefined;
this._forced_transition_hook = undefined;
this._any_transition_hook = undefined;
this._standard_transition_hook = undefined;
this._data = data;
if (state_declaration) {
state_declaration.map((state_decl) => {
if (this._state_declarations.has(state_decl.state)) { // no repeats
throw new JssmError(this, `Added the same state declaration twice: ${JSON.stringify(state_decl.state)}`);
}
this._state_declarations.set(state_decl.state, transfer_state_properties(state_decl));
});
}
transitions.map((tr) => {
if (tr.from === undefined) {
throw new JssmError(this, `transition must define 'from': ${JSON.stringify(tr)}`);
}
if (tr.to === undefined) {
throw new JssmError(this, `transition must define 'to': ${JSON.stringify(tr)}`);
}
// get the cursors. what a mess
const cursor_from = this._states.get(tr.from)
|| { name: tr.from, from: [], to: [], complete: complete.includes(tr.from) };
if (!(this._states.has(tr.from))) {
this._new_state(cursor_from);
}
const cursor_to = this._states.get(tr.to)
|| { name: tr.to, from: [], to: [], complete: complete.includes(tr.to) };
if (!(this._states.has(tr.to))) {
this._new_state(cursor_to);
}
// guard against existing connections being re-added
if (cursor_from.to.includes(tr.to)) {
throw new JssmError(this, `already has ${JSON.stringify(tr.from)} to ${JSON.stringify(tr.to)}`);
}
else {
cursor_from.to.push(tr.to);
cursor_to.from.push(tr.from);
}
// add the edge; note its id
this._edges.push(tr);
const thisEdgeId = this._edges.length - 1;
// guard against repeating a transition name
if (tr.name) {
if (this._named_transitions.has(tr.name)) {
throw new JssmError(this, `named transition "${JSON.stringify(tr.name)}" already created`);
}
else {
this._named_transitions.set(tr.name, thisEdgeId);
}
}
// set up the mapping, so that edges can be looked up by endpoint pairs
const from_mapping = this._edge_map.get(tr.from) || new Map();
if (!(this._edge_map.has(tr.from))) {
this._edge_map.set(tr.from, from_mapping);
}
// const to_mapping = from_mapping.get(tr.to);
from_mapping.set(tr.to, thisEdgeId); // already checked that this mapping doesn't exist, above
// set up the action mapping, so that actions can be looked up by origin
if (tr.action) {
// forward mapping first by action name
let actionMap = this._actions.get(tr.action);
if (!(actionMap)) {
actionMap = new Map();
this._actions.set(tr.action, actionMap);
}
if (actionMap.has(tr.from)) {
throw new JssmError(this, `action ${JSON.stringify(tr.action)} already attached to origin ${JSON.stringify(tr.from)}`);
}
else {
actionMap.set(tr.from, thisEdgeId);
}
// reverse mapping first by state origin name
let rActionMap = this._reverse_actions.get(tr.from);
if (!(rActionMap)) {
rActionMap = new Map();
this._reverse_actions.set(tr.from, rActionMap);
}
// no need to test for reverse mapping pre-presence;
// forward mapping already covers collisions
rActionMap.set(tr.action, thisEdgeId);
// reverse mapping first by state target name
if (!(this._reverse_action_targets.has(tr.to))) {
this._reverse_action_targets.set(tr.to, new Map());
}
/* todo comeback
fundamental problem is roActionMap needs to be a multimap
const roActionMap = this._reverse_action_targets.get(tr.to); // wasteful - already did has - refactor
if (roActionMap) {
if (roActionMap.has(tr.action)) {
throw new JssmError(this, `ro-action ${tr.to} already attached to action ${tr.action}`);
} else {
roActionMap.set(tr.action, thisEdgeId);
}
} else {
throw new JssmError(this, `should be impossible - flow doesn\'t know .set precedes .get yet again. severe error?');
}
*/
}
});
}
/********
*
* Internal method for fabricating states. Not meant for external use.
*
* @internal
*
*/
_new_state(state_config) {
if (this._states.has(state_config.name)) {
throw new JssmError(this, `state ${JSON.stringify(state_config.name)} already exists`);
}
this._states.set(state_config.name, state_config);
return state_config.name;
}
/*********
*
* Get the current state of a machine.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const switch = jssm.from('on <=> off;');
* console.log( switch.state() ); // 'on'
*
* switch.transition('off');
* console.log( switch.state() ); // 'off'
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
state() {
return this._state;
}
/* whargarbl todo major
when we reimplement this, reintroduce this change to the is_final call
is_changing(): boolean {
return true; // todo whargarbl
}
*/
/*********
*
* Get the current data of a machine.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const switch = jssm.from('on <=> off;', {data: 1});
* console.log( switch.data() ); // 1
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
data() {
return this._data;
}
/* whargarbl todo major
when we reimplement this, reintroduce this change to the is_final call
is_changing(): boolean {
return true; // todo whargarbl
}
*/
/********
*
* Check whether a given state is final (either has no exits or is marked
* `complete`.)
*
* ```typescript
* import { sm, state_is_final } from 'jssm';
*
* const final_test = sm`first -> second;`;
*
* console.log( final_test.state_is_final('first') ); // false
* console.log( final_test.state_is_final('second') ); // true
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
* @param whichState The name of the state to check for finality
*
*/
state_is_final(whichState) {
return ((this.state_is_terminal(whichState)) && (this.state_is_complete(whichState)));
}
/********
*
* Check whether the current state is final (either has no exits or is marked
* `complete`.)
*
* ```typescript
* import { sm, state_is_final } from 'jssm';
*
* const final_test = sm`first -> second;`;
*
* console.log( final_test.is_final() ); // false
* state.transition('second');
* console.log( final_test.is_final() ); // true
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
is_final() {
// return ((!this.is_changing()) && this.state_is_final(this.state()));
return this.state_is_final(this.state());
}
graph_layout() {
return this._graph_layout;
}
dot_preamble() {
return this._dot_preamble;
}
machine_author() {
return this._machine_author;
}
machine_comment() {
return this._machine_comment;
}
machine_contributor() {
return this._machine_contributor;
}
machine_definition() {
return this._machine_definition;
}
machine_language() {
return this._machine_language;
}
machine_license() {
return this._machine_license;
}
machine_name() {
return this._machine_name;
}
machine_version() {
return this._machine_version;
}
raw_state_declarations() {
return this._raw_state_declaration;
}
state_declaration(which) {
return this._state_declarations.get(which);
}
state_declarations() {
return this._state_declarations;
}
fsl_version() {
return this._fsl_version;
}
machine_state() {
return {
internal_state_impl_version: 1,
actions: this._actions,
edge_map: this._edge_map,
edges: this._edges,
named_transitions: this._named_transitions,
reverse_actions: this._reverse_actions,
// reverse_action_targets : this._reverse_action_targets,
state: this._state,
states: this._states
};
}
/*
load_machine_state(): boolean {
return false; // todo whargarbl
}
*/
/*********
*
* List all the states known by the machine. Please note that the order of
* these states is not guaranteed.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const switch = jssm.from('on <=> off;');
* console.log( switch.states() ); // ['on', 'off']
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
states() {
return Array.from(this._states.keys());
}
state_for(whichState) {
const state = this._states.get(whichState);
if (state) {
return state;
}
else {
throw new JssmError(this, 'No such state', { requested_state: whichState });
}
}
/*********
*
* Check whether the machine knows a given state.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const switch = jssm.from('on <=> off;');
*
* console.log( switch.has_state('off') ); // true
* console.log( switch.has_state('dance') ); // false
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
* @param whichState The state to be checked for extance
*
*/
has_state(whichState) {
return this._states.get(whichState) !== undefined;
}
/*********
*
* Lists all edges of a machine.
*
* ```typescript
* import { sm } from 'jssm';
*
* const lswitch = sm`on 'toggle' <=> 'toggle' off;`;
*
* lswitch.list_edges();
* [
* {
* from: 'on',
* to: 'off',
* kind: 'main',
* forced_only: false,
* main_path: true,
* action: 'toggle'
* },
* {
* from: 'off',
* to: 'on',
* kind: 'main',
* forced_only: false,
* main_path: true,
* action: 'toggle'
* }
* ]
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
list_edges() {
return this._edges;
}
list_named_transitions() {
return this._named_transitions;
}
list_actions() {
return Array.from(this._actions.keys());
}
theme() {
return this._theme; // constructor sets this to "default" otherwise
}
flow() {
return this._flow;
}
get_transition_by_state_names(from, to) {
const emg = this._edge_map.get(from);
if (emg) {
return emg.get(to);
}
else {
return undefined;
}
}
lookup_transition_for(from, to) {
const id = this.get_transition_by_state_names(from, to);
return ((id === undefined) || (id === null)) ? undefined : this._edges[id];
}
/********
*
* List all transitions attached to the current state, sorted by entrance and
* exit. The order of each sublist is not defined. A node could appear in
* both lists.
*
* ```typescript
* import { sm } from 'jssm';
*
* const light = sm`red 'next' -> green 'next' -> yellow 'next' -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;
*
* light.state(); // 'red'
* light.list_transitions(); // { entrances: [ 'yellow', 'off' ], exits: [ 'green', 'off' ] }
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
* @param whichState The state whose transitions to have listed
*
*/
list_transitions(whichState = this.state()) {
return { entrances: this.list_entrances(whichState), exits: this.list_exits(whichState) };
}
/********
*
* List all entrances attached to the current state. Please note that the
* order of the list is not defined.
*
* ```typescript
* import { sm } from 'jssm';
*
* const light = sm`red 'next' -> green 'next' -> yellow 'next' -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;
*
* light.state(); // 'red'
* light.list_entrances(); // [ 'yellow', 'off' ]
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
* @param whichState The state whose entrances to have listed
*
*/