Repository navigation
Expand file tree
/
Copy pathHSPlusHSIIRCompiler.ts
More file actions
431 lines (402 loc) · 12.5 KB
/
Copy pathHSPlusHSIIRCompiler.ts
File metadata and controls
431 lines (402 loc) · 12.5 KB
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
/**
* HSPlusHSIIRCompiler
*
* A deliberately bounded sovereign lowering path for ordinary `.hsplus`
* systems components:
*
* canonical HoloScriptPlusParser
* -> normalized typed state-machine AST
* -> shared HSI-IR state-machine lowering
* -> HSIExactTrace
*
* The adapter does not parse a second language and does not execute raw
* JavaScript. Every unsupported construct fails admission instead of being
* dropped. This is a whole-document subset, not a claim of complete `.hsplus`
* lowering.
*/
import { HoloScriptPlusParser } from '../parser/HoloScriptPlusParser';
import type {
HoloAnimationInput,
HoloAnimationInputType,
HoloBinaryExpression,
HoloExpression,
HoloIdentifier,
HoloMemberExpression,
HoloStateMachine,
HoloStateTransition,
HoloState_Machine,
HoloUnaryExpression,
SourceRange,
} from '../parser/HoloCompositionTypes';
import { lowerStateMachineToHSIIR } from './HSIIRCompiler';
import {
HSIAdmissionError,
HSI_IR_SCHEMA_VERSION,
hsiSha256,
hsiSourceTextDigest,
type HSIIRDocument,
} from './HSIIRTypes';
export interface HSPlusHSIIRLoweringOptions {
/** Stable world/component name. Defaults to the sorted machine names. */
worldName?: string;
}
interface HSPlusProgramLike {
type: 'Program';
body: unknown[];
imports?: unknown[];
directives?: unknown[];
}
interface HSPlusStateMachineLike {
type: 'state-machine';
name: string;
initialState: string;
inputs?: unknown[];
listeners?: unknown[];
states?: unknown[];
transitions?: unknown[];
directives?: unknown[];
loc?: SourceRange;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function asProgram(value: unknown): HSPlusProgramLike {
if (!isRecord(value) || value.type !== 'Program' || !Array.isArray(value.body)) {
throw new HSIAdmissionError('parse-failed', 'canonical .hsplus parser returned no Program');
}
return value as unknown as HSPlusProgramLike;
}
function asStateMachine(value: unknown, ordinal: number): HSPlusStateMachineLike {
if (
!isRecord(value) ||
value.type !== 'state-machine' ||
typeof value.name !== 'string' ||
typeof value.initialState !== 'string'
) {
const type = isRecord(value) && typeof value.type === 'string' ? value.type : typeof value;
throw new HSIAdmissionError(
'unsupported-top-level',
`top-level declaration ${ordinal} is "${type}", not a state_machine`
);
}
return value as unknown as HSPlusStateMachineLike;
}
function assertOnlyKeys(
value: Record<string, unknown>,
allowed: ReadonlySet<string>,
where: string
): void {
const unsupported = Object.keys(value).filter((key) => !allowed.has(key));
if (unsupported.length > 0) {
throw new HSIAdmissionError(
'unsupported-value',
`${where}: unsupported field(s) ${unsupported.sort().join(', ')}`
);
}
}
function referenceExpression(reference: string): HoloIdentifier | HoloMemberExpression {
const parts = reference.split('.');
let expression: HoloIdentifier | HoloMemberExpression = {
type: 'Identifier',
name: parts.shift() ?? reference,
};
for (const property of parts) {
expression = {
type: 'MemberExpression',
object: expression,
property,
computed: false,
};
}
return expression;
}
function lowerParsedExpression(value: unknown, where: string): HoloExpression {
if (
value === null ||
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
) {
return { type: 'Literal', value };
}
if (!isRecord(value)) {
throw new HSIAdmissionError(
'unsupported-expression',
`${where}: expression is not a supported scalar or syntax node`
);
}
if (typeof value.__ref === 'string') {
assertOnlyKeys(value, new Set(['__ref']), where);
return referenceExpression(value.__ref);
}
if (value.type === 'binary') {
if (typeof value.operator !== 'string' || !('left' in value) || !('right' in value)) {
throw new HSIAdmissionError('unsupported-expression', `${where}: malformed binary guard`);
}
assertOnlyKeys(value, new Set(['type', 'operator', 'left', 'right']), where);
return {
type: 'BinaryExpression',
operator: value.operator,
left: lowerParsedExpression(value.left, where),
right: lowerParsedExpression(value.right, where),
} satisfies HoloBinaryExpression;
}
if (value.type === 'unary') {
if ((value.operator !== '!' && value.operator !== '-') || !('argument' in value)) {
throw new HSIAdmissionError('unsupported-expression', `${where}: unsupported unary guard`);
}
assertOnlyKeys(value, new Set(['type', 'operator', 'argument']), where);
return {
type: 'UnaryExpression',
operator: value.operator,
argument: lowerParsedExpression(value.argument, where),
} satisfies HoloUnaryExpression;
}
throw new HSIAdmissionError(
'unsupported-expression',
`${where}: parser node "${String(value.type ?? 'unknown')}" is outside the HSPlus HSI subset`
);
}
function inputDefaultMatches(type: HoloAnimationInputType, value: unknown): boolean {
if (value === undefined) return true;
if (type === 'bool' || type === 'trigger') return typeof value === 'boolean';
if (type === 'int') return typeof value === 'number' && Number.isInteger(value);
return typeof value === 'number' && Number.isFinite(value);
}
function normalizeInput(
machineName: string,
value: unknown,
seen: Set<string>
): HoloAnimationInput {
if (!isRecord(value) || typeof value.name !== 'string' || typeof value.inputType !== 'string') {
throw new HSIAdmissionError(
'invalid-input',
`state machine "${machineName}" contains a malformed input declaration`
);
}
assertOnlyKeys(
value,
new Set(['type', 'name', 'inputType', 'rawType', 'default']),
`state machine "${machineName}" input "${value.name}"`
);
if (seen.has(value.name)) {
throw new HSIAdmissionError(
'duplicate-input',
`state machine "${machineName}" declares input "${value.name}" twice`
);
}
seen.add(value.name);
const inputType = value.inputType;
if (
inputType !== 'bool' &&
inputType !== 'float' &&
inputType !== 'int' &&
inputType !== 'trigger'
) {
throw new HSIAdmissionError(
'unsupported-input-type',
`state machine "${machineName}" input "${value.name}" has unsupported type "${inputType}"`
);
}
if (!inputDefaultMatches(inputType, value.default)) {
throw new HSIAdmissionError(
'input-default-type',
`state machine "${machineName}" input "${value.name}" default does not match ${inputType}`
);
}
const input: HoloAnimationInput = {
type: 'AnimationInput',
name: value.name,
inputType,
};
if (typeof value.rawType === 'string') input.rawType = value.rawType;
if (typeof value.default === 'number' || typeof value.default === 'boolean') {
input.default = value.default;
}
return input;
}
function normalizeState(machineName: string, value: unknown, seen: Set<string>): HoloState_Machine {
if (!isRecord(value) || typeof value.name !== 'string') {
throw new HSIAdmissionError(
'invalid-state',
`state machine "${machineName}" contains a malformed state declaration`
);
}
assertOnlyKeys(
value,
new Set(['name', 'onEntry', 'onExit']),
`state machine "${machineName}" state "${value.name}"`
);
if (value.onEntry !== undefined || value.onExit !== undefined) {
throw new HSIAdmissionError(
'unsupported-value',
`state machine "${machineName}" state "${value.name}" carries lifecycle code outside the sovereign subset`
);
}
if (seen.has(value.name)) {
throw new HSIAdmissionError(
'duplicate-state',
`state machine "${machineName}" declares state "${value.name}" twice`
);
}
seen.add(value.name);
return {
type: 'State_Machine',
name: value.name,
actions: [],
transitions: [],
};
}
function normalizeTransition(
machineName: string,
value: unknown,
ordinal: number
): HoloStateTransition {
if (!isRecord(value) || typeof value.from !== 'string' || typeof value.to !== 'string') {
throw new HSIAdmissionError(
'invalid-transition',
`state machine "${machineName}" transition ${ordinal} is malformed`
);
}
assertOnlyKeys(
value,
new Set(['from', 'to', 'when']),
`state machine "${machineName}" transition ${ordinal}`
);
if (!('when' in value)) {
throw new HSIAdmissionError(
'admission-skewed',
`state machine "${machineName}" transition ${ordinal} has no typed guard`
);
}
return {
type: 'StateTransition',
from: value.from,
target: value.to,
condition: lowerParsedExpression(
value.when,
`transition:${machineName}.${value.from}->${value.to}#${ordinal}`
),
};
}
function normalizeMachine(node: HSPlusStateMachineLike): HoloStateMachine {
if ((node.directives?.length ?? 0) > 0) {
throw new HSIAdmissionError(
'unsupported-value',
`state machine "${node.name}" carries directives outside the sovereign subset`
);
}
if ((node.listeners?.length ?? 0) > 0) {
throw new HSIAdmissionError(
'unsupported-value',
`state machine "${node.name}" carries listeners outside the sovereign subset`
);
}
const inputNames = new Set<string>();
const stateNames = new Set<string>();
const inputs = (node.inputs ?? []).map((input) => normalizeInput(node.name, input, inputNames));
const states = Object.fromEntries(
(node.states ?? []).map((state) => {
const normalized = normalizeState(node.name, state, stateNames);
return [normalized.name, normalized];
})
);
const transitions = (node.transitions ?? []).map((transition, ordinal) =>
normalizeTransition(node.name, transition, ordinal)
);
return {
type: 'StateMachine',
name: node.name,
initialState: node.initialState,
inputs,
listeners: [],
states,
transitions,
loc: node.loc,
};
}
/**
* Lower a complete `.hsplus` source document containing only typed
* `state_machine` declarations into HSI-IR.
*
* Throws HSIAdmissionError for parse errors, unsupported declarations, erased
* semantics, invalid types, or graph skew. It never returns partial IR.
*/
export function lowerHSPlusProgramToHSIIR(
source: string,
options: HSPlusHSIIRLoweringOptions = {}
): HSIIRDocument {
const parser = new HoloScriptPlusParser({ strict: true });
const parsed = parser.parse(source);
if (!parsed.success || !parsed.ast) {
const details = parsed.errors
.map((error) => `${error.line}:${error.column} ${error.message}`)
.join('; ');
throw new HSIAdmissionError('parse-failed', details || 'canonical .hsplus parse failed');
}
const program = asProgram(parsed.ast);
if ((program.imports?.length ?? 0) > 0 || (program.directives?.length ?? 0) > 0) {
throw new HSIAdmissionError(
'unsupported-top-level',
'imports and global directives are outside the HSPlus HSI subset'
);
}
if (program.body.length === 0) {
throw new HSIAdmissionError('empty-world', '.hsplus document declares no state machines');
}
const names = new Set<string>();
const machines = program.body.map((node, ordinal) => {
const normalized = normalizeMachine(asStateMachine(node, ordinal));
if (names.has(normalized.name)) {
throw new HSIAdmissionError(
'duplicate-machine',
`.hsplus document declares state machine "${normalized.name}" twice`
);
}
names.add(normalized.name);
return lowerStateMachineToHSIIR(normalized);
});
machines.sort((left, right) => left.id.localeCompare(right.id));
const worldName =
options.worldName ??
machines
.map((machine) => machine.name)
.slice()
.sort()
.join('+');
const docWithoutDigest = {
schemaVersion: HSI_IR_SCHEMA_VERSION,
kind: 'HSIIR' as const,
world: {
name: worldName,
sourceDigest: hsiSourceTextDigest(source),
},
entities: [],
relations: [],
state: [],
observationPolicy: [],
eventHandlers: [],
machines,
predicates: [],
declaredUnknowns: [
'entities',
'event-handlers',
'lifecycle-hooks',
'predicates',
'relations',
'world-state',
],
provenance: {
compiler: 'HSIIRCompiler' as const,
sourceSurface: 'hsplus' as const,
},
};
const deterministicDigest = hsiSha256(docWithoutDigest);
return {
...docWithoutDigest,
provenance: {
...docWithoutDigest.provenance,
deterministicDigest,
},
};
}