-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
329 lines (252 loc) · 9.45 KB
/
lib.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
import {grammar} from 'ohm-js';
import {createMachine} from 'xstate';
function ok(passed, msg) {
if (passed) return;
throw new Error(msg);
}
function nok(failed, msg) {
if (failed) throw new Error(msg);
}
const g = grammar(String.raw`
XMachina {
Machine = "machine" id "{" References States "}"
References = ListOf<Reference, "">
Reference = id "=" refid
refid = "__REF__" digit+ "__"
States = ListOf<State, "">
State = StateType "state" id "{" Events "}" -- typed
| "state" id "{" Events "}" -- untyped
StateType = "initial" | "final"
Events = Event*
Event = EventId ":" NonemptyListOf<Rules, "|">
Rules = rule_id+
EventId = "[" upper (upper | digit | "_")* "]" -- regular
| "[" ">" "]" -- entry
| "[" "<" "]" -- exit
| "[" "-" "]" -- always
| "[" "@" digit+ "]" -- delay
rule_id = lower (~(rule_meta end) (alnum | "_" | "-"))* rule_meta?
rule_meta = "?"
id = letter (alnum | "_" | "-")+
}
`);
const dict = new Map();
dict.set("?" , "guard" );
dict.set("*entry*" , "entry" );
dict.set("*exit*" , "exit" );
dict.set("*always*", "always" );
function build_rules(ruleset) {
const ret =
( ruleset
. map(rules => {
const q =
( rules
. reduce( (acc, r) => {
acc[r.type].push(r.id);
return acc;
}
, {guard: [], target: [], action: []}));
nok(q.guard.length > 1, 'cannot have more than one guard');
nok(q.target.length > 1, 'cannot have more than one target');
const g = q.guard[0];
const t = q.target[0];
const a = ( q.action.length > 1 ? q.action
: q.action.length == 1 ? q.action[0]
: null);
const ret = {};
if (g) ret.cond = g;
if (t) ret.target = t;
if (a) ret.actions = a;
return ret;
}));
return ret.length > 1 ? ret : ret[0];
}
const s = g.createSemantics();
s.addOperation('eval',
{
Machine(_1, _id, _2, _refs, _states, _3) {
const id = _id.eval();
const refs = _refs.eval();
let states = _states.eval();
const state_ids = new Set(states.map(s => s.id));
ok(states.length > 0, 'machine has no states'); // TODO: fix with grammar
let initial = states.filter(state => state.type == "initial");
ok(initial.length != 0, 'machine does not have an initial state');
ok(initial.length == 1, 'machine has more than one initial state');
// Goes over ALL the rules and identify them
// We need to know if a rule is meant as a target,
// an action or a guard.
( states
. flatMap(s =>
[].concat( s.events?.entry ?? []
, s.events?.exit ?? []
, s.events?.always ?? []
, s.events?.after ?? []
, s.events?.event ?? []))
. flatMap(xs =>
[].concat(...xs.rules))
. filter(r =>
r.type == null)
. forEach(rule => {
rule.type = ( state_ids.has(rule.id) ? 'target'
: 'action');
}));
states =
( states
. reduce( (m, s) => {
const {id, type, events} = s;
m[id] = {};
if (type == 'final') m[id].type = type;
if (!events) return m;
nok(events.entry?.length > 1, 'cannot have more than one "entry" statement.');
nok(events.exit?.length > 1, 'cannot have more than one "exit" statement.');
nok(events.always?.length > 1, 'cannot have more than one "always" statement.');
if (events.entry) m[id].entry = build_rules(events.entry[0].rules);
if (events.exit) m[id].exit = build_rules(events.exit[0].rules);
if (events.always) m[id].always = build_rules(events.always[0].rules);
if (events.event) m[id].on = ( events
. event
. reduce( (acc, e) => {
acc[e.id] = build_rules(e.rules);
return acc;
}
, {}));
if (events.after) m[id].after = ( events
. after
. reduce( (acc, e) => {
acc[e.id] = build_rules(e.rules);
return acc;
}
, {}));
return m;
}
, {}));
initial = initial[0].id;
return ({ refs: ( Object
. values(refs)
. reduce( (acc, r) => {
acc[r.id] = r;
return acc;
}
, {}))
, mdef: { predictableActionArguments: true
, id
, initial
, states}});
}
, References(list) {
return ( list
. asIteration()
. children
. reduce( (m, r) =>
Object.assign(m, r.eval())
, {}));
}
, Reference(_name, _1, _refid) {
const refid = _refid.eval();
const refname = _name.eval();
return ({[refname]: { id: refid
, name: refname
, type: null /* TBD */}});
}
, refid(_1, _d, _2) {
return `__REF__${_d.sourceString}__`;
}
, States(xs) {
const states = ( xs
. asIteration()
. children
. map(state => state.eval()));
return states.length > 0 ? states : null; // FIXME: grammar should forbid this
}
, State_typed(_type, _1, _id, _2, _events, _3) {
let type = _type.eval();
let id = _id.eval();
let events = _events.eval();
return ({id, type, events});
}
, State_untyped(_1, _id, _2, _events, _3) {
let id = _id.eval();
let events = _events.eval();
return ({id, events});
}
, StateType(type) {
return type.sourceString;
}
, Events(xs) {
if (xs.children.length == 0) return null;
return ( xs
. children
. reduce( (acc, x) => {
const ev = x.eval();
const {type} = ev;
acc[type] ??= [];
acc[type].push(ev);
return acc;
}
, {}));
}
, Event(_ev, _1, _rules) {
const ev = _ev.eval();
ev.rules = _rules.asIteration().children.map(r => r.eval());
return ev;
}
, EventId_regular(_1, head, tail, _2) {
const id = head.sourceString + tail.sourceString;
return {type: 'event', id};
}
, EventId_entry(_1, _2, _3) {
return {type: 'entry'};
}
, EventId_exit(_1, _2, _3) {
return {type: 'exit'};
}
, EventId_always(_1, _2, _3) {
return {type: 'always'};
}
, EventId_delay(_1, _2, id, _3) {
// TODO: _id could also be a property in 'machine.options.delays'.
return {type: 'after', id: parseInt(id.sourceString, 10)};
}
, Rules(_rules) {
return _rules.children.map(r => r.eval());
}
, rule_id(_head, _body, _meta) {
const id = _head.sourceString + _body.sourceString;
const type = dict.get(_meta.sourceString);
return ({type, id});
}
, id(head, body) {
return head.sourceString + body.sourceString;
}
});
export function compile(source) {
const result = g.match(source);
ok(result.succeeded(), 'syntax error');
const adapter = s(result);
return adapter.eval();
}
const rkey = n => `__REF__${String(n).padStart(3, '0')}__`;
export function xmachina(strs, ...refs) {
// reconstructs the source string by replacing
// interpolated references with ids.
const dsl = ( strs
. slice(1)
. reduce( (acc, s, i) => acc + rkey(i) + s
, strs[0]));
const {refs: meta, mdef} = compile(dsl);
const machine =
createMachine( mdef
, ( refs
. reduce( (acc, r, i) => {
const k = rkey(i);
const t = meta[k].type;
const n = ( t == 'action' ? 'actions'
: 'guards');
acc[n] ??= {};
acc[n][meta[k].name] = r;
return acc;
}
, {})));
return machine;
}