-
Notifications
You must be signed in to change notification settings - Fork 21
/
jssm.js
665 lines (450 loc) · 19.4 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
// whargarbl lots of these return arrays could/should be sets
// @flow
import type {
JssmGenericState, JssmGenericConfig,
JssmTransition, JssmTransitionList,
JssmMachineInternalState,
JssmParseTree,
JssmCompileSe, JssmCompileSeStart, JssmCompileRule,
JssmArrow, JssmArrowDirection, JssmArrowKind
} from './jssm-types';
import { seq, weighted_rand_select, weighted_sample_select, histograph, weighted_histo_key } from './jssm-util.js';
const parse : <NT, DT>(string) => JssmParseTree<NT> = require('./jssm-dot.js').parse; // eslint-disable-line flowtype/no-weak-types // todo whargarbl remove any
const version : null = null; // replaced from package.js in build
function arrow_direction(arrow : JssmArrow) : JssmArrowDirection {
switch ( String(arrow) ) {
case '->' : case '=>' : case '~>' :
return 'right';
case '<-' : case '<=' : case '<~' :
return 'left';
case '<->': case '<-=>': case '<-~>':
case '<=>': case '<=->': case '<=~>':
case '<~>': case '<~->': case '<~=>':
return 'both';
default:
throw new Error(`arrow_direction: unknown arrow type ${arrow}`);
}
}
function arrow_left_kind(arrow : JssmArrow) : JssmArrowKind {
switch ( String(arrow) ) {
case '->': case '=>' : case '~>':
return 'none';
case '<-': case '<->': case '<-=>': case '<-~>':
return 'legal';
case '<=': case '<=>': case '<=->': case '<=~>':
return 'main';
case '<~': case '<~>': case '<~->': case '<~=>':
return 'forced';
default:
throw new Error(`arrow_direction: unknown arrow type ${arrow}`);
}
}
function arrow_right_kind(arrow : JssmArrow) : JssmArrowKind {
switch ( String(arrow) ) {
case '<-': case '<=' : case '<~':
return 'none';
case '->': case '<->': case '<=->': case '<~->':
return 'legal';
case '=>': case '<=>': case '<-=>': case '<~=>':
return 'main';
case '~>': case '<~>': case '<-~>': case '<=~>':
return 'forced';
default:
throw new Error(`arrow_direction: unknown arrow type ${arrow}`);
}
}
function compile_rule_transition_step<mNT>(acc : Array<mixed>, from : mNT, to : mNT, se : JssmCompileSe<mNT>) : mixed { // todo flow describe the parser representation of a transition step extension
const new_acc : Array<mixed> = acc.concat({ from, to }); // todo whargarbl can do better than array mixed
if (se) {
return compile_rule_transition_step(new_acc, to, se.to, se.se);
} else {
return new_acc;
}
}
function compile_rule_handle_transition<mNT>(rule : JssmCompileSeStart<mNT>) : mixed { // todo flow describe the parser representation of a transition
return compile_rule_transition_step([], rule.from, rule.se.to, rule.se.se);
}
function compile_rule_handler<mNT>(rule : JssmCompileSeStart<mNT>) : JssmCompileRule { // todo flow describe the output of the parser
if (rule.key === 'transition') { return { agg_as: 'transition', val: compile_rule_handle_transition(rule) }; }
throw new Error(`compile_rule_handler: Unknown rule: ${JSON.stringify(rule)}`);
}
function compile<mNT, mDT>(tree : JssmParseTree<mNT>) : JssmGenericConfig<mNT, mDT> { // todo flow describe the output of the parser
const results : {transition:Array< JssmTransition<mNT, mDT> >} = {
transition: []
};
tree.map( (tr : JssmCompileSeStart<mNT>) => {
const rule : JssmCompileRule = compile_rule_handler(tr),
agg_as : string = rule.agg_as,
val : mixed = rule.val; // todo better types
results[agg_as] = results[agg_as].concat(val);
});
const assembled_transitions : Array< JssmTransition<mNT, mDT> > = [].concat(... results['transition']);
const result_cfg : JssmGenericConfig<mNT, mDT> = {
initial_state : assembled_transitions[0].from,
transitions : assembled_transitions
};
return result_cfg;
}
class Machine<mNT, mDT> {
_state : mNT;
_states : Map<mNT, JssmGenericState<mNT>>;
_edges : Array<JssmTransition<mNT, mDT>>;
_edge_map : Map<mNT, Map<mNT, number>>;
_named_transitions : Map<mNT, number>;
_actions : Map<mNT, Map<mNT, number>>;
_reverse_actions : Map<mNT, Map<mNT, number>>;
_reverse_action_targets : Map<mNT, Map<mNT, number>>;
// whargarbl this badly needs to be broken up, monolith master
constructor({ initial_state, complete=[], transitions } : JssmGenericConfig<mNT, mDT>) {
this._state = initial_state;
this._states = 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
transitions.map( (tr:JssmTransition<mNT, mDT>) => {
if (tr.from === undefined) { throw new Error(`transition must define 'from': ${JSON.stringify(tr)}`); }
if (tr.to === undefined) { throw new Error(`transition must define 'to': ${ JSON.stringify(tr)}`); }
// get the cursors. what a mess
const cursor_from : JssmGenericState<mNT>
= 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 : JssmGenericState<mNT>
= 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 Error(`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 : number = this._edges.length - 1;
// guard against repeating a transition name
if (tr.name) {
if (this._named_transitions.has(tr.name)) {
throw new Error(`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 : Map<mNT, number> = 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 : ?Map<mNT, number> = this._actions.get(tr.action);
if (!(actionMap)) {
actionMap = new Map();
this._actions.set(tr.action, actionMap);
}
if (actionMap.has(tr.from)) {
throw new Error(`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 : ?Map<mNT, number> = 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 Error(`ro-action ${tr.to} already attached to action ${tr.action}`);
} else {
roActionMap.set(tr.action, thisEdgeId);
}
} else {
throw new Error('should be impossible - flow doesn\'t know .set precedes .get yet again. severe error?');
}
*/
}
});
}
_new_state(state_config : JssmGenericState<mNT>) : mNT { // whargarbl get that state_config any under control
if (this._states.has(state_config.name)) {
throw new Error(`state ${JSON.stringify(state_config.name)} already exists`);
}
this._states.set(state_config.name, state_config);
return state_config.name;
}
state() : mNT {
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
}
*/
state_is_final(whichState : mNT) : boolean {
return ( (this.state_is_terminal(whichState)) && (this.state_is_complete(whichState)) );
}
is_final() : boolean {
// return ((!this.is_changing()) && this.state_is_final(this.state()));
return this.state_is_final(this.state());
}
machine_state() : JssmMachineInternalState<mNT, mDT> {
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
}
*/
states() : Array<mNT> {
return [... this._states.keys()];
}
state_for(whichState : mNT) : JssmGenericState<mNT> {
const state : ?JssmGenericState<mNT> = this._states.get(whichState);
if (state) { return state; }
else { throw new Error(`no such state ${JSON.stringify(state)}`); }
}
list_edges() : Array< JssmTransition<mNT, mDT> > {
return this._edges;
}
list_named_transitions() : Map<mNT, number> {
return this._named_transitions;
}
list_actions() : Array<mNT> {
return [... this._actions.keys()];
}
get_transition_by_state_names(from: mNT, to: mNT) : ?number {
const emg : ?Map<mNT, number> = this._edge_map.get(from);
if (emg) {
return emg.get(to);
} else {
return undefined;
}
}
lookup_transition_for(from: mNT, to: mNT) : ?JssmTransition<mNT, mDT> {
const id : ?number = this.get_transition_by_state_names(from, to);
return ((id === undefined) || (id === null))? undefined : this._edges[id];
}
list_transitions(whichState : mNT = this.state()) : JssmTransitionList<mNT> {
return {entrances: this.list_entrances(whichState), exits: this.list_exits(whichState)};
}
list_entrances(whichState : mNT = this.state()) : Array<mNT> {
return (this._states.get(whichState) || {}).from || [];
}
list_exits(whichState : mNT = this.state()) : Array<mNT> {
return (this._states.get(whichState) || {}).to || [];
}
probable_exits_for(whichState : mNT) : Array< JssmTransition<mNT, mDT> > {
const wstate : ?JssmGenericState<mNT> = this._states.get(whichState);
if (!(wstate)) { throw new Error(`No such state ${JSON.stringify(whichState)} in probable_exits_for`); }
const wstate_to : Array< mNT > = wstate.to,
wtf : Array< JssmTransition<mNT, mDT> >
= wstate_to
.map( (ws) : ?JssmTransition<mNT, mDT> => this.lookup_transition_for(this.state(), ws))
.filter(Boolean);
return wtf;
}
probabilistic_transition() : boolean {
const selected : JssmTransition<mNT, mDT> = weighted_rand_select(this.probable_exits_for(this.state()));
return this.transition( selected.to );
}
probabilistic_walk(n : number) : Array<mNT> {
return seq(n)
.map(() : mNT => {
const state_was : mNT = this.state();
this.probabilistic_transition();
return state_was;
})
.concat([this.state()]);
}
probabilistic_histo_walk(n : number) : Map<mNT, number> {
return histograph(this.probabilistic_walk(n));
}
actions(whichState : mNT = this.state() ) : Array<mNT> {
const wstate : ?Map<mNT, number> = this._reverse_actions.get(whichState);
if (wstate) { return [... wstate.keys()]; }
else { throw new Error(`No such state ${JSON.stringify(whichState)}`); }
}
list_states_having_action(whichState : mNT) : Array<mNT> {
const wstate : ?Map<mNT, number> = this._actions.get(whichState);
if (wstate) { return [... wstate.keys()]; }
else { throw new Error(`No such state ${JSON.stringify(whichState)}`); }
}
// comeback
/*
list_entrance_actions(whichState : mNT = this.state() ) : Array<mNT> {
return [... (this._reverse_action_targets.get(whichState) || new Map()).values()] // wasteful
.map( (edgeId:any) => (this._edges[edgeId] : any)) // whargarbl burn out any
.filter( (o:any) => o.to === whichState)
.map( filtered => filtered.from );
}
*/
list_exit_actions(whichState : mNT = this.state() ) : Array<?mNT> { // these are mNT, not ?mNT
const ra_base : ?Map<mNT, number> = this._reverse_actions.get(whichState);
if (!(ra_base)) { throw new Error(`No such state ${JSON.stringify(whichState)}`); }
return [... ra_base.values()]
.map ( (edgeId:number) : JssmTransition<mNT, mDT> => this._edges[edgeId] )
.filter ( (o:JssmTransition<mNT, mDT>) : boolean => o.from === whichState )
.map ( (filtered : JssmTransition<mNT, mDT>) : ?mNT => filtered.action );
}
probable_action_exits(whichState : mNT = this.state() ) : Array<mixed> { // these are mNT
const ra_base : ?Map<mNT, number> = this._reverse_actions.get(whichState);
if (!(ra_base)) { throw new Error(`No such state ${JSON.stringify(whichState)}`); }
return [... ra_base.values()]
.map ( (edgeId:number) : JssmTransition<mNT, mDT> => this._edges[edgeId] )
.filter ( (o:JssmTransition<mNT, mDT>) : boolean => o.from === whichState )
.map ( (filtered) : mixed => ( { action : filtered.action,
probability : filtered.probability } )
);
}
is_unenterable(whichState : mNT) : boolean {
// whargarbl should throw on unknown state
return this.list_entrances(whichState).length === 0;
}
has_unenterables() : boolean {
return this.states().some( (x) : boolean => this.is_unenterable(x));
}
is_terminal() : boolean {
return this.state_is_terminal(this.state());
}
state_is_terminal(whichState : mNT) : boolean {
// whargarbl should throw on unknown state
return this.list_exits(whichState).length === 0;
}
has_terminals() : boolean {
return this.states().some( (x) : boolean => this.state_is_terminal(x));
}
is_complete() : boolean {
return this.state_is_complete(this.state());
}
state_is_complete(whichState : mNT) : boolean {
const wstate : ?JssmGenericState<mNT> = this._states.get(whichState);
if (wstate) { return wstate.complete; }
else { throw new Error(`No such state ${JSON.stringify(whichState)}`); }
}
has_completes() : boolean {
return this.states().some( (x) : boolean => this.state_is_complete(x) );
}
action(name : mNT, newData? : mDT) : boolean {
// todo whargarbl implement hooks
// todo whargarbl implement data stuff
// todo major incomplete whargarbl comeback
if (this.valid_action(name, newData)) {
const edge : JssmTransition<mNT, mDT> = this.current_action_edge_for(name);
this._state = edge.to;
return true;
} else {
return false;
}
}
transition(newState : mNT, newData? : mDT) : boolean {
// todo whargarbl implement hooks
// todo whargarbl implement data stuff
// todo major incomplete whargarbl comeback
if (this.valid_transition(newState, newData)) {
this._state = newState;
return true;
} else {
return false;
}
}
/* whargarbl reintroduce after valid_force_transition is re-enabled
// can leave machine in inconsistent state. generally do not use
force_transition(newState : mNT, newData? : mDT) : boolean {
// todo whargarbl implement hooks
// todo whargarbl implement data stuff
// todo major incomplete whargarbl comeback
if (this.valid_force_transition(newState, newData)) {
this._state = newState;
return true;
} else {
return false;
}
}
*/
current_action_for(action : mNT) : number | void {
const action_base : ?Map<mNT, number> = this._actions.get(action);
return action_base? action_base.get(this.state()) : undefined;
}
current_action_edge_for(action : mNT) : JssmTransition<mNT, mDT> {
const idx : ?number = this.current_action_for(action);
if ((idx === undefined) || (idx === null)) { throw new Error(`No such action ${JSON.stringify(action)}`); }
return this._edges[idx];
}
valid_action(action : mNT, _newData? : mDT) : boolean { // todo comeback unignore newData
// todo whargarbl implement hooks
// todo whargarbl implement data stuff
// todo major incomplete whargarbl comeback
return this.current_action_for(action) !== undefined;
}
valid_transition(newState : mNT, _newData? : mDT) : boolean { // todo comeback unignore newData
// todo whargarbl implement hooks
// todo whargarbl implement data stuff
// todo major incomplete whargarbl comeback
return (this.lookup_transition_for(this.state(), newState) !== undefined);
}
/* todo whargarbl re-enable force_transition/1 after implementing this
valid_force_transition(newState : mNT, newData? : mDT) : boolean {
return false; // major todo whargarbl
}
*/
}
function sm<mNT, mDT>(template_strings : Array<string> /* , arguments */) : Machine<mNT, mDT> {
// foo`a${1}b${2}c` will come in as (['a','b','c'],1,2)
// this includes when a and c are empty strings
// therefore template_strings will always have one more el than template_args
// therefore map the smaller container and toss the last one on on the way out
return new Machine(compile(parse(template_strings.reduce(
// in general avoiding `arguments` is smart. however with the template
// string notation, as designed, it's not really worth the hassle
/* eslint-disable fp/no-arguments */
/* eslint-disable prefer-rest-params */
(acc, val, idx) : string => `${acc}${arguments[idx]}${val}` // arguments[0] is never loaded, so args doesn't need to be gated
/* eslint-enable prefer-rest-params */
/* eslint-enable fp/no-arguments */
))));
}
export {
version,
Machine,
parse,
compile,
sm,
arrow_direction,
arrow_left_kind,
arrow_right_kind,
// todo whargarbl these should be exported to a utility library
seq, weighted_rand_select, histograph, weighted_sample_select, weighted_histo_key
};