@appling/codegen-go 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/index.js CHANGED
@@ -1,10 +1,8 @@
1
- import { camel, enumConstant, goExpr, pascal, qualify } from './golang.js';
1
+ import { coveredByScenarios, scenarioCall, Simulator, throughPath, UNKNOWN } from '@appling/model';
2
+ import { accessFile, accessOf, accessSteps, actorFields, actorFieldType, tenantOf, tenantPaths } from './access.js';
3
+ import { camel, enumConstant, goExpr, goTerm, pascal, PRIMITIVES, qualify } from './golang.js';
2
4
  const DECIMAL = 'github.com/shopspring/decimal';
3
- const PRIMITIVES = {
4
- String: ['string'], Text: ['string'], Int: ['int64'], Bool: ['bool'], File: ['string'], Uuid: ['string'],
5
- Decimal: ['decimal.Decimal', DECIMAL], Money: ['decimal.Decimal', DECIMAL],
6
- Date: ['time.Time', 'time'], DateTime: ['time.Time', 'time'], Duration: ['time.Duration', 'time']
7
- };
5
+ const OPERATIONS = ['read', 'create', 'update', 'delete'];
8
6
  const extension = {
9
7
  name: '@appling/codegen-go',
10
8
  test: ['go', 'test', './...'],
@@ -27,25 +25,35 @@ const extension = {
27
25
  case 'Event': return [structStep(node, context, 'events.go')];
28
26
  case 'ErrorDecl': return [goFile(node.module, 'errors.go', context, new Set(['errors']), `// ${errorName(node)} is the declared error ${node.qn}.\nvar ${errorName(node)} = errors.New(${JSON.stringify(last(node.qn))})`)];
29
27
  case 'Field': return fieldSteps(node, context);
30
- case 'Invariant': return [...(validation(node, context) ? [] : [task(`check the invariant "${node.data.label}" in Validate: ${node.props.condition}`)]), ...testSteps(node, context)];
31
- case 'Policy': return [task(`enforce the policy ${node.qn}: ${node.props.condition}`), ...testSteps(node, context)];
28
+ case 'Invariant': return [...(validation(node, context) ? [] : [task(`check the invariant "${node.data.label}" in Validate: ${node.props.condition}`)]), ...invariantTestSteps(node, context)];
29
+ case 'Policy': return [...policySteps(node, context), ...policyTestSteps(node, context)];
30
+ case 'Role':
31
+ case 'Actor':
32
+ case 'Tenant':
33
+ return accessSteps(node, context);
32
34
  case 'Action': return actionSteps(node, context);
33
35
  case 'Machine': return machineSteps(node, context);
34
- case 'Transition': return testSteps(node, context);
36
+ case 'Transition': return covered(context).has(node.qn) ? [] : transitionTestSteps(node, context);
37
+ case 'Scenario': return scenarioSteps(node, context);
35
38
  case 'EnumLiteral':
36
39
  case 'Param':
37
40
  case 'SetEffect':
38
41
  case 'CreateEffect':
39
42
  case 'EmitEffect':
43
+ case 'ForEffect':
44
+ case 'UpdateEffect':
45
+ case 'DeleteEffect':
40
46
  case 'ExternalOperation':
41
47
  case 'ProjectionField':
42
48
  case 'Endpoint':
43
49
  return [];
50
+ case 'Query': return [...guardSteps(node, context), ...queryFilterSteps(node, context), task(`implement the query ${last(node.qn)} on top of the generated domain package, with the storage, HTTP and scheduling libraries of your choice`)];
51
+ case 'UseCase':
52
+ return [...guardSteps(node, context), task(`implement the use case ${last(node.qn)} on top of the generated domain package, with the storage, HTTP and scheduling libraries of your choice`)];
53
+ case 'External':
54
+ return [leftToCode(`implement a client for ${last(node.qn)} with the HTTP library of your choice`)];
44
55
  case 'Job':
45
- case 'Query':
46
56
  case 'Projection':
47
- case 'External':
48
- case 'UseCase':
49
57
  case 'Interface':
50
58
  case 'Page':
51
59
  case 'Navigation':
@@ -70,6 +78,9 @@ function structStep(node, context, file) {
70
78
  }
71
79
  /** An entity becomes a struct with an ID, a constructor with the defaults, methods for derived fields, and Validate for the invariants. */
72
80
  function entitySteps(entity, context) {
81
+ return [entityStep(entity, context), ...guardSteps(entity, context)];
82
+ }
83
+ function entityStep(entity, context) {
73
84
  const imports = new Set();
74
85
  const name = last(entity.qn);
75
86
  const receiver = name.charAt(0).toLowerCase();
@@ -93,12 +104,20 @@ function entitySteps(entity, context) {
93
104
  });
94
105
  imports.add('errors');
95
106
  lines.push('', `// Validate checks the invariants of ${name}.`, `func (${receiver} *${name}) Validate() error {`, '\tvar errs []error', ...checks, '\treturn errors.Join(errs...)', '}');
96
- return [goFile(entity.module, 'types.go', context, imports, lines.join('\n'))];
107
+ const path = tenantPaths(context).get(entity.qn);
108
+ if (path) {
109
+ const tenant = tenantOf(context);
110
+ const hops = path.map((_, i) => [receiver, ...path.slice(0, i + 1).map(f => pascal(last(f.qn)))].join('.'));
111
+ lines.push('', `// TenantID returns the ID of the ${tenant.data.entity} this ${name} belongs to, for the tenant ${tenant.qn}.`, `func (${receiver} *${name}) TenantID() (int64, bool) {`, ...(hops.length ? [`\tif ${hops.map(h => `${h} == nil`).join(' || ')} {`, '\t\treturn 0, false', '\t}'] : []), `\treturn ${hops.at(-1) ?? receiver}.ID, true`, '}');
112
+ }
113
+ return goFile(entity.module, 'types.go', context, imports, lines.join('\n'));
97
114
  }
98
115
  function fieldSteps(field, context) {
99
116
  const owner = context.node(parentOf(field.qn));
100
117
  if (owner.kind === 'Event' || owner.kind === 'ValueType')
101
118
  return [];
119
+ if (owner.kind === 'Actor')
120
+ return actorFieldType(field, context, new Set()) ? [] : [task(`add the field ${last(field.qn)} of ${owner.qn} to the Actor of the access package; enums and value types have no form there yet`)];
102
121
  if (owner.kind !== 'Entity')
103
122
  return undefined;
104
123
  const scope = { ...goScope(owner, context, new Set()), self: 'x' };
@@ -119,12 +138,22 @@ function validation(invariant, context) {
119
138
  * checks the current state, effects change the record, and emitted events are returned.
120
139
  */
121
140
  function actionSteps(action, context) {
141
+ const { step, tasks } = actionCode(action, context);
142
+ return [step, ...guardSteps(action, context), ...tasks, ...(covered(context).has(action.qn) ? [] : testSteps(action, context))];
143
+ }
144
+ /** The generated function of an action, the tasks for what it leaves out, and what it takes besides the record and the inputs. */
145
+ function actionCode(action, context) {
122
146
  const imports = new Set();
123
147
  const entity = action.data.entity ? context.node(action.data.entity) : undefined;
124
148
  const self = entity ? camel(last(entity.qn)) : undefined;
125
149
  const scope = { ...goScope(action, context, imports), self };
126
150
  const tasks = [];
127
151
  const body = ['var events []any'];
152
+ const guard = guardOf(action, context);
153
+ if (guard) {
154
+ imports.add('fmt');
155
+ body.push(`if !actor.IsSystem() && !${guard.name}(${['actor', ...guard.args].join(', ')}) {`, `\treturn nil, fmt.Errorf("%w: ${last(action.qn)}", ${accessIn(scope, 'ErrForbidden')})`, '}');
156
+ }
128
157
  (action.data.preconditions ?? []).forEach((precondition, i) => {
129
158
  const condition = goExpr(precondition.condition, scope);
130
159
  const text = action.props.preconditions[i];
@@ -138,19 +167,174 @@ function actionSteps(action, context) {
138
167
  body.push(`if !(${condition}) {`, `\treturn nil, ${error}`, '}');
139
168
  });
140
169
  const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
170
+ const creating = storing(action);
141
171
  if (transitions.length && self)
142
- body.push(...transitionSwitch(transitions, self, last(action.qn), scope, context, tasks));
143
- for (const effect of context.children(action.qn).filter(c => c.kind.endsWith('Effect')))
144
- body.push(...effectLines(effect, self, scope, context, tasks));
172
+ body.push(...transitionSwitch(transitions, self, last(action.qn), scope, context, tasks, creating));
173
+ body.push(...effectBlock(action, self, scope, context, tasks, creating));
145
174
  body.push('return events, nil');
175
+ const takesActor = !!guard || enforced(context);
146
176
  const params = [
147
- ...(entity ? [`${self} *${last(entity.qn)}`] : []),
148
- ...context.children(action.qn).filter(c => c.kind === 'Param').map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`)
177
+ ...(takesActor ? [`actor ${accessIn(scope, 'Actor')}`] : []),
178
+ ...(entity ? [`${self} ${typeOf({ $type: 'TypeRef', decl: entity.qn }, scope)}`] : []),
179
+ ...context.children(action.qn).filter(c => c.kind === 'Param').map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`),
180
+ ...stores(creating).map(([name, e]) => `${name} func(${typeOf({ $type: 'TypeRef', decl: e.qn }, scope)}) error`)
149
181
  ];
150
- const code = [`// ${last(action.qn)} is the action ${action.qn}. It returns the events it emits.`, `func ${last(action.qn)}(${params.join(', ')}) ([]any, error) {`, ...body.map(l => `\t${l}`), '}'].join('\n');
151
- return [goFile(action.module, 'actions.go', context, imports, code), ...tasks, ...testSteps(action, context)];
182
+ const stored = stores(creating).length ? ` The records it creates, updates or deletes go to the store functions, which write them.` : '';
183
+ const code = [`// ${last(action.qn)} is the action ${action.qn}. It returns the events it emits.${stored}`, `func ${last(action.qn)}(${params.join(', ')}) ([]any, error) {`, ...body.map(l => `\t${l}`), '}'].join('\n');
184
+ return { step: goFile(action.module, 'actions.go', context, imports, code), tasks, takesActor, creates: stores(creating).map(([, e]) => e) };
185
+ }
186
+ /**
187
+ * `In<Query>` in the module's `queries.go`: whether a record is among the query's results for its inputs, by the
188
+ * filter. Loading, sorting and paging stay with the storage, the query's task; nothing when the filter does not translate.
189
+ */
190
+ function queryFilterSteps(query, context) {
191
+ if (!query.data.filter)
192
+ return [];
193
+ const imports = new Set();
194
+ const entity = context.node(query.data.entity);
195
+ const self = camel(last(entity.qn));
196
+ const scope = { ...goScope(query, context, imports), self };
197
+ const condition = goExpr(query.data.filter, scope);
198
+ if (!condition)
199
+ return [];
200
+ const params = [
201
+ `${self} ${typeOf({ $type: 'TypeRef', decl: entity.qn }, scope)}`,
202
+ ...context.children(query.qn).filter(c => c.kind === 'Param').map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`)
203
+ ];
204
+ const code = [
205
+ `// In${last(query.qn)} reports whether a record is among the results of the query ${query.qn}${params.length > 1 ? ' for the inputs' : ''}.`,
206
+ `func In${last(query.qn)}(${params.join(', ')}) bool {`,
207
+ `\treturn ${condition}`,
208
+ '}'
209
+ ].join('\n');
210
+ return [goFile(query.module, 'queries.go', context, imports, code)];
211
+ }
212
+ /**
213
+ * The exported check of an element, when one applies. Once the model has any policy, every entity gets
214
+ * `Can<Op><Entity>`, every action `Can<Action>` (its entity's update check and its own policies; an action
215
+ * without an entity that only creates records leaves the check to the create check of the created entity),
216
+ * and every query `Can<Query>` (its entity's read check and its own policies); what no policy covers is
217
+ * denied. A use case gets `Can<UseCase>` for its own policies. Without policies, only the tenant guards actions.
218
+ */
219
+ function guardOf(owner, context) {
220
+ const own = policiesOf(owner, context);
221
+ const entityQn = owner.kind === 'Entity' ? owner.qn : owner.data.entity;
222
+ const entity = entityQn ? context.node(entityQn) : undefined;
223
+ const applies = own.length > 0 || (enforced(context)
224
+ ? owner.kind === 'Entity' || owner.kind === 'Query' || (owner.kind === 'Action' && (!!entity || !creates(owner, context)))
225
+ : owner.kind === 'Action' && !!entity && tenantPaths(context).has(entity.qn));
226
+ if (!applies)
227
+ return undefined;
228
+ const params = owner.kind === 'Action' || owner.kind === 'UseCase' || owner.kind === 'Query' ? context.children(owner.qn).filter(c => c.kind === 'Param') : [];
229
+ return { entity, params, args: [...(entity ? [camel(last(entity.qn))] : []), ...params.map(p => camel(last(p.qn)))], name: `Can${last(owner.qn)}` };
152
230
  }
153
- function transitionSwitch(transitions, self, label, scope, context, tasks) {
231
+ /** Whether the model has any policy: then an operation that no policy covers is denied. */
232
+ function enforced(context) {
233
+ return context.graph.nodes.some(n => n.kind === 'Policy');
234
+ }
235
+ /** Whether an action, or a transition it runs, creates a record. */
236
+ function creates(action, context) {
237
+ const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
238
+ return [action, ...transitions].some(n => context.children(n.qn).some(c => c.kind === 'CreateEffect'));
239
+ }
240
+ function policiesOf(owner, context) {
241
+ return context.children(owner.qn).filter(c => c.kind === 'Policy');
242
+ }
243
+ function guardSignature(guard, scope) {
244
+ return [
245
+ `actor ${accessIn(scope, 'Actor')}`,
246
+ ...(guard.entity ? [`${camel(last(guard.entity.qn))} ${typeOf({ $type: 'TypeRef', decl: guard.entity.qn }, scope)}`] : []),
247
+ ...guard.params.map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`)
248
+ ].join(', ');
249
+ }
250
+ /**
251
+ * The exported checks of an element in its module's `policies.go`, combining its policies (and, for an action
252
+ * or a query, the update or read check of its entity, or the tenant) with `&&`, false when there is nothing to
253
+ * combine. An entity gets one per operation, false where no policy grants it, and one per operation and field
254
+ * that a field policy narrows.
255
+ */
256
+ function guardSteps(owner, context) {
257
+ const guard = guardOf(owner, context);
258
+ if (!guard)
259
+ return [];
260
+ const imports = new Set();
261
+ const scope = goScope(owner, context, imports);
262
+ const signature = guardSignature(guard, scope);
263
+ const args = ['actor', ...guard.args].join(', ');
264
+ const record = guard.entity && camel(last(guard.entity.qn));
265
+ const tenant = guard.entity && tenantPaths(context).has(guard.entity.qn) ? `${accessIn(scope, 'InTenant')}(actor, ${record})` : undefined;
266
+ const policies = policiesOf(owner, context);
267
+ const call = (policy) => `${policyName(policy, context)}(${args})`;
268
+ const blocks = [];
269
+ if (owner.kind === 'Entity') {
270
+ const name = last(owner.qn);
271
+ for (const op of OPERATIONS) {
272
+ const covering = policies.filter(p => covers(p, op) && !p.data.fields?.length);
273
+ const parts = covering.length ? [...(tenant ? [tenant] : []), ...covering.map(call)] : ['false'];
274
+ blocks.push([
275
+ `// Can${pascal(op)}${name} reports whether the policies of ${owner.qn} let the actor ${op} the record${covering.length ? '' : `; no policy grants ${op}`}.`,
276
+ `func Can${pascal(op)}${name}(${signature}) bool {`, `\treturn ${parts.join(' && ')}`, '}'
277
+ ].join('\n'));
278
+ const fields = [...new Set(policies.filter(p => covers(p, op)).flatMap(p => (p.data.fields ?? [])))];
279
+ for (const field of fields) {
280
+ const narrowing = policies.filter(p => covers(p, op) && (p.data.fields ?? []).includes(field));
281
+ blocks.push([
282
+ `// Can${pascal(op)}${name}${pascal(last(field))} reports whether the actor may ${op} the field ${last(field)} of the record.`,
283
+ `func Can${pascal(op)}${name}${pascal(last(field))}(${signature}) bool {`, `\treturn ${[`Can${pascal(op)}${name}(${args})`, ...narrowing.map(call)].join(' && ')}`, '}'
284
+ ].join('\n'));
285
+ }
286
+ }
287
+ }
288
+ else {
289
+ const op = owner.kind === 'Query' ? 'Read' : 'Update';
290
+ const entity = guard.entity;
291
+ const inherited = entity && owner.kind !== 'UseCase' && enforced(context)
292
+ ? [`${entity.module === owner.module ? '' : `${qualifyModule(entity.module, scope)}.`}Can${op}${last(entity.qn)}(actor, ${record})`]
293
+ : tenant ? [tenant] : [];
294
+ const what = owner.kind === 'Query' ? `read a record through ${owner.qn}` : `run ${owner.qn}`;
295
+ const parts = [...inherited, ...policies.map(call)];
296
+ blocks.push([
297
+ `// ${guard.name} reports whether the actor may ${what}${inherited.length ? `, including the ${inherited[0] === tenant ? 'tenant' : op.toLowerCase()} check of ${entity.qn}` : ''}${parts.length ? '' : '; no policy grants it'}.`,
298
+ `func ${guard.name}(${signature}) bool {`, `\treturn ${parts.length ? parts.join(' && ') : 'false'}`, '}'
299
+ ].join('\n'));
300
+ }
301
+ return [goFile(owner.module, 'policies.go', context, imports, blocks.join('\n\n')), accessFile(context, accessOf(context))];
302
+ }
303
+ /** One function per policy, `<owner>Policy<Operations>`, with the arguments of its element's check; false with a task when Go cannot say the condition. */
304
+ function policySteps(policy, context) {
305
+ const guard = guardOf(context.node(parentOf(policy.qn)), context);
306
+ const imports = new Set();
307
+ const scope = { ...goScope(policy, context, imports), self: guard.entity && camel(last(guard.entity.qn)), actor: 'actor' };
308
+ const condition = goExpr(policy.data.condition, scope);
309
+ const name = policyName(policy, context);
310
+ const code = [
311
+ `// ${name} is the policy ${policy.qn}: ${policy.props.condition}`,
312
+ `func ${name}(${guardSignature(guard, scope)}) bool {`,
313
+ `\treturn ${condition ?? 'false'}`,
314
+ '}'
315
+ ].join('\n');
316
+ return [goFile(policy.module, 'policies.go', context, imports, code), ...(condition ? [] : [task(`implement the policy ${policy.qn} in ${name}: ${policy.props.condition}`)])];
317
+ }
318
+ function policyName(policy, context) {
319
+ const owner = parentOf(policy.qn);
320
+ const words = /\[(.*)\]$/.exec(policy.qn)[1].split(/[^A-Za-z0-9]+/).filter(Boolean).map(pascal).join('');
321
+ const same = policiesOf(context.node(owner), context).filter(p => p.qn === policy.qn);
322
+ return `${camel(last(owner))}Policy${words}${same.length > 1 ? same.indexOf(policy) + 1 : ''}`;
323
+ }
324
+ function covers(policy, op) {
325
+ const operations = policy.data.operations;
326
+ return !operations?.length || operations.includes(op);
327
+ }
328
+ /** A name from the access package, imported. */
329
+ function accessIn(scope, name) {
330
+ scope.imports.add(scope.access.path);
331
+ return `${scope.access.pkg}.${name}`;
332
+ }
333
+ function qualifyModule(module, scope) {
334
+ scope.imports.add(scope.importOf(module));
335
+ return module.split('.').pop();
336
+ }
337
+ function transitionSwitch(transitions, self, label, scope, context, tasks, creating) {
154
338
  const machine = context.node(parentOf(transitions[0].qn));
155
339
  const field = context.node(machine.data.field);
156
340
  const enumNode = context.node(field.data.type.decl);
@@ -167,8 +351,7 @@ function transitionSwitch(transitions, self, label, scope, context, tasks) {
167
351
  tasks.push(task(`check the guard ${transition.props.guard} of ${last(transition.qn)}`));
168
352
  }
169
353
  lines.push(`case ${condition}:`);
170
- for (const effect of context.children(transition.qn))
171
- lines.push(...effectLines(effect, self, scope, context, tasks).map(l => `\t${l}`));
354
+ lines.push(...effectBlock(transition, self, scope, context, tasks, creating).map(l => `\t${l}`));
172
355
  lines.push(`\t${state} = ${enumConstant(context.node(`${enumNode.qn}.${transition.data.to}`), scope)}`);
173
356
  }
174
357
  scope.imports.add('fmt');
@@ -177,29 +360,179 @@ function transitionSwitch(transitions, self, label, scope, context, tasks) {
177
360
  lines.push('default:', `\treturn nil, fmt.Errorf("%w: ${label} from %s", ${invalid}, ${state})`, '}');
178
361
  return lines;
179
362
  }
180
- function effectLines(effect, self, scope, context, tasks) {
363
+ function storing(action) {
364
+ return { action: last(action.qn), entities: new Map(), updates: new Map(), deletes: new Map() };
365
+ }
366
+ /** The store functions an action takes, in order: creates, updates, deletes. */
367
+ function stores(creating) {
368
+ return [['create', creating.entities], ['update', creating.updates], ['delete', creating.deletes]]
369
+ .flatMap(([verb, map]) => [...map.values()].map(e => [`${verb}${last(e.qn)}`, e]));
370
+ }
371
+ /** The effects below an action, a transition or a loop in order; an `as` name is a variable for the effects after it. */
372
+ function effectBlock(owner, self, scope, context, tasks, creating) {
373
+ const lines = [];
374
+ let current = scope;
375
+ for (const effect of context.children(owner.qn).filter(c => c.kind.endsWith('Effect'))) {
376
+ lines.push(...effectLines(effect, self, current, context, tasks, creating));
377
+ const variable = effect.data.variable;
378
+ if (effect.kind === 'CreateEffect' && variable)
379
+ current = { ...current, vars: new Map([...(current.vars ?? []), [variable, 'other']]) };
380
+ }
381
+ return lines;
382
+ }
383
+ function effectLines(effect, self, scope, context, tasks, creating) {
384
+ if (effect.kind === 'ForEffect') {
385
+ const variable = effect.data.variable;
386
+ if (!self) {
387
+ tasks.push(task(`apply the effect ${last(effect.qn)}`));
388
+ return [];
389
+ }
390
+ const body = effectBlock(effect, self, { ...scope, vars: new Map([...(scope.vars ?? []), [variable, 'other']]) }, context, tasks, creating);
391
+ const used = body.some(l => new RegExp(`\\b${variable}\\b`).test(l));
392
+ return [`for ${used ? `_, ${variable} := ` : ''}range ${self}.${pascal(last(effect.data.collection))} {`, ...body.map(l => `\t${l}`), '}'];
393
+ }
394
+ if (effect.kind === 'UpdateEffect' || effect.kind === 'DeleteEffect')
395
+ return recordLines(effect, self, scope, context, tasks, creating);
181
396
  if (effect.kind === 'SetEffect') {
182
397
  const field = context.node(effect.data.field);
183
- const value = goExpr(effect.data.value, scope);
184
- if (!value || !self) {
398
+ const value = self && assigned(field, effect.data.value, scope);
399
+ if (!value) {
185
400
  tasks.push(task(`apply the effect set ${last(field.qn)} = ${effect.props.value}`));
186
401
  return [];
187
402
  }
188
- const code = coerce(value, field);
189
- return [`${self}.${pascal(last(field.qn))} = ${field.data.type.optional ? `ptr(${code})` : code}`];
403
+ return [`${self}.${pascal(last(field.qn))} = ${value}`];
190
404
  }
191
405
  if (effect.kind === 'EmitEffect') {
192
406
  const event = context.node(effect.data.event);
193
- const assignments = (effect.data.assignments ?? []).map(a => [a.name, goExpr(a.value, scope)]);
194
- if (assignments.some(([, v]) => !v)) {
195
- tasks.push(task(`emit ${last(event.qn)}`));
407
+ const given = new Map((effect.data.assignments ?? []).map(a => [a.name, a.value]));
408
+ const values = [];
409
+ const missing = [];
410
+ for (const field of fieldsOf(event, context).filter(f => !f.data.derived)) {
411
+ const type = field.data.type;
412
+ const expr = given.get(last(field.qn));
413
+ const value = expr && assigned(field, expr, scope);
414
+ if (value)
415
+ values.push(`${pascal(last(field.qn))}: ${value}`);
416
+ else if (expr || (!type.optional && !type.many))
417
+ missing.push(last(field.qn));
418
+ }
419
+ if (missing.length) {
420
+ tasks.push(task(`emit ${last(event.qn)} with its fields ${missing.join(', ')}, which the model does not give or Go cannot say`));
196
421
  return [];
197
422
  }
198
- return [`events = append(events, ${qualify(event, scope)}{${assignments.map(([n, v]) => `${pascal(n)}: ${v}`).join(', ')}})`];
423
+ return [`events = append(events, ${qualify(event, scope)}{${values.join(', ')}})`];
424
+ }
425
+ if (effect.kind === 'CreateEffect') {
426
+ const entity = context.node(effect.data.entity);
427
+ const lines = creating && createLines(effect, entity, scope, context, creating);
428
+ if (lines)
429
+ return lines;
430
+ const check = enforced(context) && runByActor(effect, context) ? `, after checking ${entity.module === scope.pkg ? '' : `${pkgOf(entity.module)}.`}CanCreate${last(entity.qn)}(actor, record)` : '';
431
+ tasks.push(task(`create the ${last(entity.qn)} through your storage layer${check}`));
432
+ return [];
199
433
  }
200
434
  tasks.push(task(`apply the effect ${last(effect.qn)}, for example through your storage layer`));
201
435
  return [];
202
436
  }
437
+ /**
438
+ * `update <path>` sets the fields of the related record and hands it to `update<Entity>`, `delete <path>` and
439
+ * `delete self` hand the record to `delete<Entity>`; once the model has policies, the actor needs the entity's
440
+ * update or delete check first. An optional path changes nothing when it is nil. Outside actions, a task.
441
+ */
442
+ function recordLines(effect, self, scope, context, tasks, creating) {
443
+ const entity = context.node(effect.data.entity);
444
+ const operation = effect.kind === 'UpdateEffect' ? 'update' : 'delete';
445
+ const target = effect.data.target;
446
+ const path = effect.data.self ? self : target && goTerm(target, scope)?.raw;
447
+ const sets = [];
448
+ for (const set of operation === 'update' ? context.children(effect.qn).filter(c => c.kind === 'SetEffect') : []) {
449
+ const field = context.node(set.data.field);
450
+ const value = entity && assigned(field, throughPath(set.data.value, entity.qn, target), scope);
451
+ if (!value)
452
+ break;
453
+ sets.push(`${path}.${pascal(last(field.qn))} = ${value}`);
454
+ }
455
+ const complete = operation === 'delete' || sets.length === context.children(effect.qn).filter(c => c.kind === 'SetEffect').length;
456
+ if (!creating || !entity || !path || !complete) {
457
+ tasks.push(task(`apply the effect ${last(effect.qn)}: ${operation} ${effect.data.self ? 'self' : effect.props.target}, for example through your storage layer`));
458
+ return [];
459
+ }
460
+ (operation === 'update' ? creating.updates : creating.deletes).set(entity.qn, entity);
461
+ const check = enforced(context) ? [
462
+ `if !actor.IsSystem() && !${entity.module === effect.module ? '' : `${qualifyModule(entity.module, scope)}.`}Can${pascal(operation)}${last(entity.qn)}(actor, ${path}) {`,
463
+ `\treturn nil, fmt.Errorf("%w: ${creating.action}", ${accessIn(scope, 'ErrForbidden')})`,
464
+ '}'
465
+ ] : [];
466
+ if (check.length)
467
+ scope.imports.add('fmt');
468
+ const write = [...check, ...sets, `if err := ${operation}${last(entity.qn)}(${path}); err != nil {`, '\treturn nil, err', '}'];
469
+ return target?.type.endsWith('?') ? [`if ${path} != nil {`, ...write.map(l => `\t${l}`), '}'] : write;
470
+ }
471
+ /**
472
+ * A create effect in an action: a block that builds the record with `New<Entity>` and the given fields, checks
473
+ * `CanCreate<Entity>` once the model has policies, and hands the record to `create<Entity>`. Undefined when a
474
+ * required field without default is not given or a value does not translate.
475
+ */
476
+ function createLines(effect, entity, scope, context, creating) {
477
+ const given = new Map((effect.data.assignments ?? []).map(a => [a.name, a.value]));
478
+ // A named row stays a variable for the effects after it; an unnamed one lives in its own block.
479
+ const variable = effect.data.variable;
480
+ const record = variable ?? 'created';
481
+ const lines = [];
482
+ for (const field of fieldsOf(entity, context).filter(f => !f.data.derived)) {
483
+ const type = field.data.type;
484
+ const expr = given.get(last(field.qn));
485
+ if (!expr) {
486
+ if (!type.optional && !type.many && !field.data.default)
487
+ return undefined;
488
+ continue;
489
+ }
490
+ const value = assigned(field, expr, scope);
491
+ if (!value)
492
+ return undefined;
493
+ lines.push(`${record}.${pascal(last(field.qn))} = ${value}`);
494
+ }
495
+ const name = qualify(entity, scope);
496
+ const constructor = name.includes('.') ? name.replace(/\.(\w+)$/, '.New$1') : `New${name}`;
497
+ const check = enforced(context) ? [
498
+ `if !actor.IsSystem() && !${entity.module === effect.module ? '' : `${qualifyModule(entity.module, scope)}.`}CanCreate${last(entity.qn)}(actor, ${record}) {`,
499
+ `\treturn nil, fmt.Errorf("%w: ${creating.action}", ${accessIn(scope, 'ErrForbidden')})`,
500
+ '}'
501
+ ] : [];
502
+ if (check.length)
503
+ scope.imports.add('fmt');
504
+ creating.entities.set(entity.qn, entity);
505
+ const code = [`${record} := ${constructor}()`, ...lines, ...check, `if err := create${last(entity.qn)}(${record}); err != nil {`, '\treturn nil, err', '}'];
506
+ return variable ? code : ['{', ...code.map(l => `\t${l}`), '}'];
507
+ }
508
+ /** Whether an effect runs in an action, which takes the actor, rather than in a transition on an event. */
509
+ function runByActor(effect, context) {
510
+ let owner = context.node(effect.qn.slice(0, effect.qn.lastIndexOf('.effect[')));
511
+ while (owner?.kind.endsWith('Effect'))
512
+ owner = context.node(owner.qn.slice(0, owner.qn.lastIndexOf('.effect[')));
513
+ return owner?.kind === 'Action' || (owner?.kind === 'Transition' && !!owner.data.action);
514
+ }
515
+ /**
516
+ * An expression as the value of a field: records are pointers already, an optional field takes a pointer as it
517
+ * is and a value through `ptr`, and number literals become decimals for decimal fields.
518
+ */
519
+ function assigned(field, expr, scope) {
520
+ const term = goTerm(expr, scope);
521
+ if (!term)
522
+ return undefined;
523
+ const type = field.data.type;
524
+ const entity = !!type.decl && scope.node(type.decl)?.kind === 'Entity';
525
+ if (term.null)
526
+ return type.optional || type.many || entity ? 'nil' : undefined;
527
+ if (term.empty && type.many)
528
+ return `${typeOf(type, scope)}{}`;
529
+ if (entity || type.many)
530
+ return term.raw;
531
+ // An untyped constant would make `ptr` return *int.
532
+ if (type.optional)
533
+ return term.pointer ? term.raw : `ptr${type.primitive === 'Int' ? '[int64]' : ''}(${coerce(term.value, field)})`;
534
+ return coerce(term.value, field);
535
+ }
203
536
  /** Transitions on an event become a function that applies them to the record the event carries. */
204
537
  function machineSteps(machine, context) {
205
538
  const field = context.node(machine.data.field);
@@ -225,10 +558,405 @@ function machineSteps(machine, context) {
225
558
  }
226
559
  /** A skipped test per case of a rule in the module's test file; writing its body is a registry task. */
227
560
  function testSteps(node, context) {
228
- const name = `Test${pascal(last(parentOf(node.qn)))}${pascal(String(node.data.label ?? last(node.qn)).replace(/[^A-Za-z0-9]+/g, '_'))}`.replace(/_/g, '');
561
+ const name = testName(node);
229
562
  const code = `func ${name}(t *testing.T) {\n\tt.Skip(${JSON.stringify(`registry task: ${node.qn}`)})\n}`;
230
563
  return [goFile(node.module, `${pkgOf(node.module)}_test.go`, context, new Set(['testing']), code), task(`write the test ${name}`)];
231
564
  }
565
+ const POLICY_CASES = ['allows permitted actors', 'denies other actors'];
566
+ /**
567
+ * The test of a policy on a whole entity whose condition reads the actor only through `actor.is(...)`: the
568
+ * entity's valid record and `access.New<Actor>()` of a declared actor go to `Can<Op><Entity>`. `allows permitted
569
+ * actors` takes the first actor the simulator proves this policy lets through and asserts every operation whose
570
+ * whole record policies all read the actor that way and grant it; `denies other actors` takes the first actor the
571
+ * simulator proves this policy keeps out and refutes every operation it covers (the checks combine with `&&`).
572
+ * A case without such an actor stays skipped as a task; field policies, policies on other elements and a condition
573
+ * that reads more of the actor or that Go cannot say keep the whole test skipped.
574
+ */
575
+ function policyTestSteps(policy, context) {
576
+ const entity = context.node(parentOf(policy.qn));
577
+ if (entity?.kind !== 'Entity' || (policy.data.fields ?? []).length)
578
+ return testSteps(policy, context);
579
+ const wholes = policiesOf(entity, context).filter(p => !(p.data.fields ?? []).length);
580
+ const record = camel(last(entity.qn));
581
+ const dry = { ...goScope(entity, context, new Set()), self: record, actor: 'actor' };
582
+ const checkable = (p) => onlyActorKinds(p.data.condition, context) && !!goExpr(p.data.condition, dry);
583
+ if (!checkable(policy))
584
+ return testSteps(policy, context);
585
+ const valid = validRecord(entity, context);
586
+ if (!valid)
587
+ return testSteps(policy, context);
588
+ const imports = new Set(['testing']);
589
+ const scope = goScope(policy, context, imports);
590
+ const sim = simulator(context);
591
+ const verdict = (p, actor) => sim.evaluate(p.data.condition, { self: valid.record, actor: { actor: actor.qn, fields: {} } });
592
+ const operations = OPERATIONS.filter(op => covers(policy, op));
593
+ const actors = context.graph.nodes.filter(n => n.kind === 'Actor');
594
+ const allowed = actors.map(actor => ({ actor, operations: operations.filter(op => wholes.filter(p => covers(p, op)).every(p => checkable(p) && verdict(p, actor) === true)) }))
595
+ .find(a => verdict(policy, a.actor) === true && a.operations.length);
596
+ const deniedActor = actors.find(actor => verdict(policy, actor) === false);
597
+ const denied = deniedActor && { actor: deniedActor, operations };
598
+ if (!allowed && !denied)
599
+ return testSteps(policy, context);
600
+ const name = testName(policy);
601
+ const entityName = last(entity.qn);
602
+ const body = (label, found, want) => [
603
+ `\tt.Run(${JSON.stringify(label)}, func(t *testing.T) {`,
604
+ ...(found ? [
605
+ `\t\tactor := ${accessIn(scope, `New${accessOf(context).name(found.actor.qn)}`)}()`,
606
+ `\t\t${record} := ${valid.name}()`,
607
+ ...found.operations.flatMap(op => {
608
+ const check = `Can${pascal(op)}${entityName}`;
609
+ return [
610
+ `\t\tif ${want ? '!' : ''}${check}(actor, ${record}) {`,
611
+ `\t\t\tt.Error(${JSON.stringify(`${check}: want ${want} for ${found.actor.qn}`)})`,
612
+ '\t\t}'
613
+ ];
614
+ })
615
+ ] : [`\t\tt.Skip(${JSON.stringify(`registry task: ${policy.qn}`)})`]),
616
+ '\t})'
617
+ ];
618
+ const code = [`func ${name}(t *testing.T) {`, ...body(POLICY_CASES[0], allowed, true), ...body(POLICY_CASES[1], denied, false), '}'].join('\n');
619
+ const missing = [allowed ? undefined : POLICY_CASES[0], denied ? undefined : POLICY_CASES[1]].filter(c => c !== undefined);
620
+ return [
621
+ valid.step,
622
+ goFile(policy.module, `${pkgOf(policy.module)}_test.go`, context, imports, code),
623
+ ...missing.map(c => task(`write the ${c} case of the test ${name}`))
624
+ ];
625
+ }
626
+ /**
627
+ * Whether the condition reads the actor only through `actor.is(X)` with an X whose verdict needs no actor field
628
+ * (an actor, or a role without a condition), and not the tenant, so `access.New<Actor>()` has the simulated verdict.
629
+ */
630
+ function onlyActorKinds(expr, context) {
631
+ if (!expr)
632
+ return true;
633
+ if (expr.$type === 'MemberExpr' && expr.member === 'is' && expr.call && expr.receiver?.$type === 'NameExpr' && expr.receiver.name === 'actor' && !expr.receiver.target) {
634
+ const target = expr.args?.[0]?.target;
635
+ const node = target ? context.node(target) : undefined;
636
+ return node?.kind === 'Actor' || node?.kind === 'Role' && !node.data.condition;
637
+ }
638
+ if (expr.$type === 'NameExpr' && (expr.name === 'actor' || expr.name === 'tenant') && !expr.target)
639
+ return false;
640
+ const parts = [expr.left, expr.right, expr.operand, expr.receiver, expr.index, ...(expr.args ?? []), ...(expr.items ?? [])];
641
+ return parts.every(p => onlyActorKinds(p, context));
642
+ }
643
+ function testName(node) {
644
+ return `Test${pascal(last(parentOf(node.qn)))}${pascal(String(node.data.label ?? last(node.qn)).replace(/[^A-Za-z0-9]+/g, '_'))}`.replace(/_/g, '');
645
+ }
646
+ const simulators = new WeakMap();
647
+ /** One simulator per graph, which proves that a test record satisfies or breaks an invariant. */
648
+ function simulator(context) {
649
+ let found = simulators.get(context.graph);
650
+ if (!found)
651
+ simulators.set(context.graph, found = new Simulator(context.graph));
652
+ return found;
653
+ }
654
+ /**
655
+ * The test of an invariant that `Validate` checks: the entity's valid record passes `Validate`, and the same
656
+ * record with one field the simulator proves to break the invariant fails with its label. Without a valid
657
+ * record the test stays skipped; without such a field value only the violation case does, as a registry task.
658
+ */
659
+ function invariantTestSteps(invariant, context) {
660
+ const entity = context.node(parentOf(invariant.qn));
661
+ if (!validation(invariant, context))
662
+ return testSteps(invariant, context);
663
+ const imports = new Set(['testing']);
664
+ const scope = goScope(entity, context, imports);
665
+ const valid = validRecord(entity, context);
666
+ if (!valid)
667
+ return testSteps(invariant, context);
668
+ const label = JSON.stringify(String(invariant.data.label));
669
+ const violation = violating(invariant, entity, valid.record, context, scope);
670
+ if (violation)
671
+ imports.add('strings');
672
+ const name = testName(invariant);
673
+ const code = [
674
+ `func ${name}(t *testing.T) {`,
675
+ '\tt.Run("holds for a valid record", func(t *testing.T) {',
676
+ `\t\tif err := ${valid.name}().Validate(); err != nil {`,
677
+ `\t\t\tt.Fatalf("a valid ${last(entity.qn)}: %v", err)`,
678
+ '\t\t}',
679
+ '\t})',
680
+ '\tt.Run("rejects a violation", func(t *testing.T) {',
681
+ ...(violation ? [
682
+ `\t\tx := ${valid.name}()`,
683
+ `\t\t${violation}`,
684
+ `\t\tif err := x.Validate(); err == nil || !strings.Contains(err.Error(), ${label}) {`,
685
+ `\t\t\tt.Fatalf(${JSON.stringify(`${violation}: want the error %q, got %v`)}, ${label}, err)`,
686
+ '\t\t}'
687
+ ] : [`\t\tt.Skip(${JSON.stringify(`registry task: ${invariant.qn}`)})`]),
688
+ '\t})',
689
+ '}'
690
+ ].join('\n');
691
+ return [
692
+ valid.step,
693
+ goFile(invariant.module, `${pkgOf(invariant.module)}_test.go`, context, imports, code),
694
+ ...(violation ? [] : [task(`write the violation case of the test ${name}`)])
695
+ ];
696
+ }
697
+ /**
698
+ * The test of a transition an action runs: the entity's valid record in a `from` state goes to the `to`
699
+ * state through the action, and, when the action allows a state no transition leaves, the action refuses it
700
+ * with `ErrInvalidTransition`. The simulator must prove that the preconditions and the guard hold and that no
701
+ * earlier case of the switch takes the record; without that (an actor to pass, an input or state it cannot
702
+ * say, code in another package) the test stays skipped as a registry task.
703
+ */
704
+ function transitionTestSteps(transition, context) {
705
+ const plan = transitionTest(transition, context);
706
+ if (!plan)
707
+ return testSteps(transition, context);
708
+ const { action, valid, state, from, to, invalid, args, actor, imports } = plan;
709
+ const call = `${last(action.qn)}(${[...(actor ? [actor] : []), 'x', ...args].join(', ')})`;
710
+ const name = testName(transition);
711
+ const code = [
712
+ `func ${name}(t *testing.T) {`,
713
+ `\tt.Run("goes from ${from.label} to ${to.label}", func(t *testing.T) {`,
714
+ `\t\tx := ${valid.name}()`,
715
+ `\t\tx.${state} = ${from.go}`,
716
+ `\t\tif _, err := ${call}; err != nil {`,
717
+ `\t\t\tt.Fatalf("${last(action.qn)} from ${from.label}: %v", err)`,
718
+ '\t\t}',
719
+ `\t\tif x.${state} != ${to.go} {`,
720
+ `\t\t\tt.Fatalf("${last(action.qn)} from ${from.label}: want ${to.label}, got %v", x.${state})`,
721
+ '\t\t}',
722
+ '\t})',
723
+ ...(invalid ? [
724
+ `\tt.Run("refuses ${invalid.label}", func(t *testing.T) {`,
725
+ `\t\tx := ${valid.name}()`,
726
+ `\t\tx.${state} = ${invalid.go}`,
727
+ `\t\tif _, err := ${call}; !errors.Is(err, ErrInvalidTransition) {`,
728
+ `\t\t\tt.Fatalf("${last(action.qn)} from ${invalid.label}: want ErrInvalidTransition, got %v", err)`,
729
+ '\t\t}',
730
+ '\t})'
731
+ ] : []),
732
+ '}'
733
+ ].join('\n');
734
+ if (invalid)
735
+ imports.add('errors');
736
+ return [valid.step, goFile(transition.module, `${pkgOf(transition.module)}_test.go`, context, imports, code)];
737
+ }
738
+ function transitionTest(transition, context) {
739
+ const action = transition.data.action ? context.node(transition.data.action) : undefined;
740
+ const machine = context.node(parentOf(transition.qn));
741
+ const entity = action?.data.entity ? context.node(action.data.entity) : undefined;
742
+ if (!action || !entity || !machine.data.field.startsWith(`${entity.qn}.`))
743
+ return undefined;
744
+ // Code in another package is more than a generated test sets up.
745
+ if (action.module !== transition.module || entity.module !== transition.module)
746
+ return undefined;
747
+ const imports = new Set(['testing']);
748
+ const scope = goScope(transition, context, imports);
749
+ const valid = validRecord(entity, context);
750
+ if (!valid)
751
+ return undefined;
752
+ const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
753
+ const self = camel(last(entity.qn));
754
+ const dry = { ...goScope(action, context, new Set()), self };
755
+ const args = [];
756
+ const inputs = {};
757
+ const takesActor = !!guardOf(action, context) || enforced(context);
758
+ // The store functions the action takes, found the way actionSteps finds them; the test stores nothing.
759
+ const creating = storing(action);
760
+ transitionSwitch(transitions, self, last(action.qn), dry, context, [], creating);
761
+ effectBlock(action, self, dry, context, [], creating);
762
+ if (takesActor) {
763
+ // Every policy the simulator weighs must be one Go checks, or Go denies where the simulator allows.
764
+ const written = stores(creating).map(([, e]) => e.qn);
765
+ const policies = [action.qn, entity.qn, ...written].flatMap(qn => context.children(qn)).filter(c => c.kind === 'Policy');
766
+ if (!policies.every(p => goExpr(p.data.condition, { ...dry, actor: 'actor' })))
767
+ return undefined;
768
+ }
769
+ for (const param of context.children(action.qn).filter(c => c.kind === 'Param')) {
770
+ const type = param.data.type;
771
+ if (type.optional || type.many) {
772
+ args.push('nil');
773
+ inputs[last(param.qn)] = type.many ? [] : null;
774
+ continue;
775
+ }
776
+ const sample = goSample(last(param.qn), type, scope, context);
777
+ if (!sample || sample.value === UNKNOWN)
778
+ return undefined;
779
+ args.push(sample.go);
780
+ inputs[last(param.qn)] = sample.value;
781
+ }
782
+ for (const [, stored] of stores(creating))
783
+ args.push(`func(${typeOf({ $type: 'TypeRef', decl: stored.qn }, scope)}) error { return nil }`);
784
+ const field = context.node(machine.data.field);
785
+ const enumNode = context.node(field.data.type.decl);
786
+ const literal = (value) => ({ go: enumConstant(context.node(`${enumNode.qn}.${value}`), scope), label: value });
787
+ const sim = simulator(context);
788
+ const holds = (record) => (action.data.preconditions ?? []).every(p => sim.evaluate(p.condition, { self: record, inputs }) === true);
789
+ const guard = (t, record) => t.data.guard ? sim.evaluate(t.data.guard, { self: record, inputs }) : true;
790
+ const fieldName = last(field.qn);
791
+ const from = transition.data.from.find(state => {
792
+ const record = { ...valid.record, [fieldName]: state };
793
+ if (!holds(record))
794
+ return false;
795
+ for (const t of transitions) {
796
+ if (!t.data.from.includes(state))
797
+ continue;
798
+ const verdict = guard(t, record);
799
+ if (t === transition)
800
+ return verdict === true && (!t.data.guard || !!goExpr(t.data.guard, dry));
801
+ // An earlier case takes the record unless Go checks its guard and the guard is false.
802
+ if (verdict !== false || !goExpr(t.data.guard, dry))
803
+ return false;
804
+ }
805
+ return false;
806
+ });
807
+ if (!from)
808
+ return undefined;
809
+ let actor;
810
+ if (takesActor) {
811
+ // The first declared actor the simulator proves the policies let run the action, created as New<Actor> makes it.
812
+ const record = { ...valid.record, [fieldName]: from };
813
+ const found = context.graph.nodes.filter(n => n.kind === 'Actor').find(a => sim.run(action.qn, record, { actor: a.qn }, inputs).allowed === 'yes');
814
+ if (!found)
815
+ return undefined;
816
+ actor = `${accessIn(scope, `New${accessOf(context).name(found.qn)}`)}()`;
817
+ }
818
+ const left = new Set(transitions.flatMap(t => t.data.from));
819
+ const invalid = context.children(enumNode.qn).map(c => last(c.qn)).find(state => !left.has(state) && holds({ ...valid.record, [fieldName]: state }));
820
+ return {
821
+ action, valid, imports, args, actor,
822
+ state: pascal(fieldName),
823
+ from: literal(from),
824
+ to: literal(transition.data.to),
825
+ invalid: invalid ? literal(invalid) : undefined
826
+ };
827
+ }
828
+ /**
829
+ * The test helper `valid<Entity>` in the module's test file: `New<Entity>` with a sample value for every
830
+ * required stored field without a default that has one (strings, numbers, booleans, times, the first enum
831
+ * literal), and the record the simulator sees. Undefined when an invariant `Validate` checks is not proven to hold.
832
+ */
833
+ function validRecord(entity, context) {
834
+ const name = `valid${last(entity.qn)}`;
835
+ const imports = new Set();
836
+ const scope = goScope(entity, context, imports);
837
+ const record = { $type: entity.qn };
838
+ const lines = [];
839
+ for (const field of fieldsOf(entity, context).filter(f => !f.data.derived)) {
840
+ const type = field.data.type;
841
+ const fieldName = last(field.qn);
842
+ if (type.many)
843
+ record[fieldName] = [];
844
+ // The default only decides whether the simulator sees its value; `New<Entity>` writes it, so its imports stay out.
845
+ else if (field.data.default)
846
+ record[fieldName] = defaultValue(field, { ...scope, imports: new Set(), self: 'x' }) ? simulator(context).evaluate(field.data.default, { self: record }) : UNKNOWN;
847
+ else if (type.optional)
848
+ record[fieldName] = null;
849
+ else {
850
+ const sample = goSample(fieldName, type, scope, context);
851
+ record[fieldName] = sample?.value ?? UNKNOWN;
852
+ if (sample)
853
+ lines.push(`\tx.${pascal(fieldName)} = ${sample.go}`);
854
+ }
855
+ }
856
+ const checked = context.children(entity.qn).filter(n => n.kind === 'Invariant' && validation(n, context));
857
+ if (!checked.every(i => simulator(context).evaluate(i.data.condition, { self: record }) === true))
858
+ return undefined;
859
+ const code = [
860
+ `// ${name} returns ${/^[AEIOU]/.test(last(entity.qn)) ? 'an' : 'a'} ${last(entity.qn)} with the defaults of the model and a sample value for every other required field.`,
861
+ `func ${name}() *${last(entity.qn)} {`, `\tx := New${last(entity.qn)}()`, ...lines, '\treturn x', '}'
862
+ ].join('\n');
863
+ const file = goFile(entity.module, `${pkgOf(entity.module)}_test.go`, context, imports, code);
864
+ const step = { ...file, write: existing => existing?.includes(`\nfunc ${name}() `) ? existing : file.write(existing) };
865
+ return { name, record, step };
866
+ }
867
+ /** A sample value of a required field in Go and as the simulator sees it; undefined for files, value types and records. */
868
+ function goSample(name, type, scope, context) {
869
+ if (type.decl) {
870
+ const decl = context.node(type.decl);
871
+ const first = decl?.kind === 'Enum' ? context.children(decl.qn)[0] : undefined;
872
+ return first ? { go: enumConstant(first, scope), value: last(first.qn) } : undefined;
873
+ }
874
+ switch (type.primitive) {
875
+ case 'String':
876
+ case 'Text': return { go: JSON.stringify(`${name}-1`), value: `${name}-1` };
877
+ case 'Uuid': return { go: '"00000000-0000-4000-8000-000000000001"', value: '00000000-0000-4000-8000-000000000001' };
878
+ case 'Int': return { go: '1', value: 1 };
879
+ case 'Decimal':
880
+ case 'Money':
881
+ scope.imports.add(DECIMAL);
882
+ return { go: 'decimal.NewFromInt(1)', value: 1 };
883
+ case 'Bool': return { go: 'false', value: false };
884
+ case 'Date':
885
+ case 'DateTime':
886
+ scope.imports.add('time');
887
+ return { go: 'time.Now()', value: UNKNOWN };
888
+ case 'Duration':
889
+ scope.imports.add('time');
890
+ return { go: 'time.Hour', value: 3_600_000 };
891
+ }
892
+ return undefined;
893
+ }
894
+ /**
895
+ * An assignment such as `x.Total = decimal.NewFromInt(-1)` that makes the invariant false on the valid record,
896
+ * trying the fields the condition reads in order.
897
+ */
898
+ function violating(invariant, entity, record, context, scope) {
899
+ const condition = invariant.data.condition;
900
+ const read = targets(condition);
901
+ for (const field of fieldsOf(entity, context).filter(f => read.has(f.qn) && !f.data.derived && !f.data.type.many)) {
902
+ for (const candidate of candidates(field.data.type, scope, context)) {
903
+ if (simulator(context).evaluate(condition, { self: { ...record, [last(field.qn)]: candidate.value } }) !== false)
904
+ continue;
905
+ candidate.imports.forEach(i => scope.imports.add(i));
906
+ return `x.${pascal(last(field.qn))} = ${candidate.go}`;
907
+ }
908
+ }
909
+ return undefined;
910
+ }
911
+ /** The values tried on a field: a few numbers, both booleans, the empty string, every enum literal, and nil when optional. */
912
+ function candidates(type, scope, context) {
913
+ const found = [];
914
+ if (type.decl) {
915
+ const decl = context.node(type.decl);
916
+ if (decl?.kind === 'Enum')
917
+ for (const literal of context.children(decl.qn))
918
+ found.push({ go: enumConstant(literal, scope), value: last(literal.qn), imports: [] });
919
+ }
920
+ else {
921
+ const numbers = [-1, 0, 1_000_000];
922
+ switch (type.primitive) {
923
+ case 'Int':
924
+ found.push(...numbers.map(n => ({ go: String(n), value: n, imports: [], cast: 'int64' })));
925
+ break;
926
+ case 'Decimal':
927
+ case 'Money':
928
+ found.push(...numbers.map(n => ({ go: `decimal.NewFromInt(${n})`, value: n, imports: [DECIMAL] })));
929
+ break;
930
+ case 'Bool':
931
+ found.push(...[true, false].map(b => ({ go: String(b), value: b, imports: [] })));
932
+ break;
933
+ case 'String':
934
+ case 'Text':
935
+ found.push({ go: '""', value: '', imports: [] });
936
+ break;
937
+ }
938
+ }
939
+ if (!type.optional)
940
+ return found;
941
+ return [{ go: 'nil', value: null, imports: [] }, ...found.map(c => ({ ...c, go: `ptr(${c.cast ? `${c.cast}(${c.go})` : c.go})` }))];
942
+ }
943
+ /** The qualified names the expression compares; a name only tested by `has()` is left out, its null is meant. */
944
+ function targets(expr, found = new Set()) {
945
+ if (Array.isArray(expr)) {
946
+ for (const item of expr)
947
+ targets(item, found);
948
+ }
949
+ else if (expr && typeof expr === 'object') {
950
+ const node = expr;
951
+ if (node.$type === 'NameExpr' && node.call && node.name === 'has')
952
+ return found;
953
+ if (node.$type === 'NameExpr' && typeof node.target === 'string')
954
+ found.add(node.target);
955
+ for (const value of Object.values(expr))
956
+ targets(value, found);
957
+ }
958
+ return found;
959
+ }
232
960
  function defaultValue(field, scope) {
233
961
  const expr = field.data.default;
234
962
  if (!expr)
@@ -263,12 +991,15 @@ function typeOf(type, scope) {
263
991
  return type.optional && !base.startsWith('*') ? `*${base}` : base;
264
992
  }
265
993
  function goScope(node, context, imports) {
266
- return { node: context.node, pkg: pkgOf(node.module || node.qn), imports, importOf: module => importPath(module, context) };
994
+ return { node: context.node, pkg: pkgOf(node.module || node.qn), imports, importOf: module => importPath(module, context), access: accessOf(context) };
267
995
  }
268
- /** Adds a block to a Go file of a module's package, merging its imports; gofmt formats the result at the end. */
269
- function goFile(module, file, context, imports, block) {
270
- const pkg = pkgOf(module);
271
- const own = importPath(module, context);
996
+ /**
997
+ * Adds a block to a Go file of a module's package, merging its imports; gofmt formats the result at the end. An
998
+ * external test file belongs to the package `<pkg>_test`, which imports the module's package like any other.
999
+ */
1000
+ function goFile(module, file, context, imports, block, external = false) {
1001
+ const pkg = external ? `${pkgOf(module)}_test` : pkgOf(module);
1002
+ const own = external ? undefined : importPath(module, context);
272
1003
  return {
273
1004
  kind: 'template', file: `${dirOf(module)}/${file}`, write: existing => {
274
1005
  const text = existing ?? `package ${pkg}\n`;
@@ -304,3 +1035,244 @@ function last(qn) {
304
1035
  function task(what) {
305
1036
  return { kind: 'task', what };
306
1037
  }
1038
+ /** A registry task the model leaves to the code by design (`docs/concept.md` section 8): it does not lower the coverage. */
1039
+ function leftToCode(what) {
1040
+ return { kind: 'task', what, leftToCode: true };
1041
+ }
1042
+ const coverage = new WeakMap();
1043
+ /** The actions, use cases and transitions the scenarios run; their guessed tests give way to the scenario tests. */
1044
+ function covered(context) {
1045
+ let found = coverage.get(context.graph);
1046
+ if (!found)
1047
+ coverage.set(context.graph, found = coveredByScenarios(context.graph));
1048
+ return found;
1049
+ }
1050
+ /** Why a scenario has no generated test; it becomes the task of the skipped test. */
1051
+ class Unsupported extends Error {
1052
+ }
1053
+ /** Names a scenario test declares or reads itself, which a binding must not shadow. */
1054
+ const GO_NAMES = new Set([
1055
+ 'break', 'case', 'chan', 'const', 'continue', 'default', 'defer', 'else', 'fallthrough', 'for', 'func', 'go', 'goto', 'if', 'import',
1056
+ 'interface', 'map', 'package', 'range', 'return', 'select', 'struct', 'switch', 'type', 'var',
1057
+ 'any', 'append', 'bool', 'error', 'false', 'int64', 'len', 'make', 'new', 'nil', 'string', 'true',
1058
+ 't', 'err', 'events', 'event', 'got', 'ok', 'actor', 'ptr', 'decimal', 'errors', 'slices', 'strings', 'regexp', 'testing', 'time'
1059
+ ]);
1060
+ /**
1061
+ * A scenario becomes `TestScenario<Name>` in its module's test file: the given rows built with `New<Entity>`, an
1062
+ * ID each, the given values and a sample for every other required field; the actor built with `access.New<Actor>`
1063
+ * and its given fields (`access.System()` when the scenario has none, which the actions do not check); one call of
1064
+ * the action; and the assertions of `then`. Without a test it stays a skipped test with a registry task.
1065
+ */
1066
+ function scenarioSteps(scenario, context) {
1067
+ const name = `TestScenario${pascal(last(scenario.qn))}`;
1068
+ const file = 'scenarios_test.go';
1069
+ const imports = new Set(['testing']);
1070
+ try {
1071
+ const lines = scenarioTest(scenario, context, imports);
1072
+ const does = scenario.data.describe ? `: ${String(scenario.data.describe).trim().replace(/\s+/g, ' ')}` : '.';
1073
+ const comment = [`// ${name} runs the scenario ${scenario.qn}${does}`];
1074
+ const helper = goFile(scenario.module, file, context, new Set(), '// ptr returns a pointer to a copy of v, for optional fields.\nfunc ptr[T any](v T) *T { return &v }', true);
1075
+ return [
1076
+ { ...helper, write: existing => existing?.includes('\nfunc ptr[') ? existing : helper.write(existing) },
1077
+ goFile(scenario.module, file, context, imports, [...comment, `func ${name}(t *testing.T) {`, ...lines.map(l => `\t${l}`), '}'].join('\n'), true)
1078
+ ];
1079
+ }
1080
+ catch (error) {
1081
+ if (!(error instanceof Unsupported))
1082
+ throw error;
1083
+ const code = `func ${name}(t *testing.T) {\n\tt.Skip(${JSON.stringify(`registry task: ${scenario.qn}`)})\n}`;
1084
+ return [goFile(scenario.module, file, context, new Set(['testing']), code, true), task(`write the test ${name}: ${error.message}`)];
1085
+ }
1086
+ }
1087
+ function scenarioTest(scenario, context, imports) {
1088
+ const data = scenario.data;
1089
+ let result;
1090
+ try {
1091
+ result = simulator(context).scenario(scenario.qn);
1092
+ }
1093
+ catch (error) {
1094
+ throw new Unsupported(`the simulator cannot run the scenario: ${error.message}`);
1095
+ }
1096
+ if (!result.passed)
1097
+ throw new Unsupported(`the simulator does not pass the scenario: ${result.failures.join(' ')}`);
1098
+ const call = scenarioCall(scenario);
1099
+ const target = context.node(call.target);
1100
+ if (!target)
1101
+ throw new Unsupported('the scenario calls nothing the extension knows');
1102
+ if (target.kind !== 'Action')
1103
+ throw new Unsupported(`${last(target.qn)} is a ${target.kind === 'UseCase' ? 'use case' : target.kind.toLowerCase()}, which the Go extension leaves to you`);
1104
+ const code = actionCode(target, context);
1105
+ if (code.tasks.length)
1106
+ throw new Unsupported(`${last(target.qn)} is not fully generated (${code.tasks.map(t => t.kind === 'task' ? t.what : '').join('; ')})`);
1107
+ // The test is in the external package `<pkg>_test`, so every name of the module's package is qualified.
1108
+ const scope = { ...goScope(scenario, context, imports), pkg: `${pkgOf(scenario.module)}_test`, vars: new Map(), rename: new Map() };
1109
+ const fixtures = (data.fixtures ?? []);
1110
+ const reserved = new Set([...GO_NAMES, accessOf(context).pkg, ...context.graph.nodes.filter(n => n.kind === 'Module').map(n => pkgOf(n.qn))]);
1111
+ const lines = [];
1112
+ // given: the rows, built as the simulator builds them, each with its own ID so records compare by identity.
1113
+ fixtures.forEach((fixture, i) => {
1114
+ const entity = context.node(fixture.entity);
1115
+ let variable = fixture.name ? (reserved.has(fixture.name) ? `${fixture.name}Row` : fixture.name) : `row${i + 1}`;
1116
+ while (!fixture.name && fixtures.some(f => f.name === variable))
1117
+ variable = `${variable}_`;
1118
+ const constructor = qualify(entity, scope).replace(/(\w+)$/, 'New$1');
1119
+ lines.push(`${variable} := ${constructor}()`, `${variable}.ID = ${i + 1}`);
1120
+ const given = new Map((fixture.assignments ?? []).map(a => [a.name, a.value]));
1121
+ for (const field of fieldsOf(entity, context).filter(f => !f.data.derived)) {
1122
+ const type = field.data.type;
1123
+ const fieldName = last(field.qn);
1124
+ const expr = given.get(fieldName);
1125
+ if (expr) {
1126
+ const value = valueOf(type, expr, scope);
1127
+ if (!value)
1128
+ throw new Unsupported(`the value of ${fieldName} in ${variable} has no Go translation`);
1129
+ lines.push(`${variable}.${pascal(fieldName)} = ${value}`);
1130
+ }
1131
+ else if (field.data.default) {
1132
+ if (!defaultValue(field, { ...scope, imports: new Set(), self: 'x' }))
1133
+ throw new Unsupported(`New${last(entity.qn)} does not set the default of ${fieldName}`);
1134
+ }
1135
+ else if (!type.optional && !type.many) {
1136
+ const sample = goSample(fieldName, type, scope, context);
1137
+ if (sample)
1138
+ lines.push(`${variable}.${pascal(fieldName)} = ${sample.go}`);
1139
+ }
1140
+ }
1141
+ if (fixture.name) {
1142
+ scope.vars.set(fixture.name, 'other');
1143
+ if (variable !== fixture.name)
1144
+ scope.rename.set(fixture.name, variable);
1145
+ }
1146
+ });
1147
+ // as: the declared actor, or the first one carrying the role, with the given fields.
1148
+ const persona = data.actor;
1149
+ if (persona) {
1150
+ const named = context.node(persona.persona);
1151
+ const actor = named.kind === 'Role' ? context.graph.nodes.find(n => n.kind === 'Actor' && (n.data.roles ?? []).includes(named.qn)) : named;
1152
+ if (!actor)
1153
+ throw new Unsupported(`no declared actor carries the role ${last(named.qn)}`);
1154
+ lines.push(`actor := ${accessIn(scope, `New${accessOf(context).name(actor.qn)}`)}()`);
1155
+ for (const assignment of persona.assignments ?? []) {
1156
+ const field = actorFields(context).find(f => last(f.qn) === assignment.name);
1157
+ if (!field || !actorFieldType(field, context, new Set()))
1158
+ throw new Unsupported(`the actor field ${assignment.name} has no form in the access package`);
1159
+ const type = field.data.type;
1160
+ const term = goTerm(assignment.value, scope);
1161
+ if (!term || type.many)
1162
+ throw new Unsupported(`the value of the actor field ${assignment.name} has no Go translation`);
1163
+ if (term.null)
1164
+ continue;
1165
+ const value = type.decl ? `ptr(${term.value}.ID)` : valueOf({ ...type, optional: true }, assignment.value, scope);
1166
+ lines.push(`actor.${pascal(assignment.name)} = ${value}`);
1167
+ }
1168
+ if (!code.takesActor)
1169
+ lines.push('_ = actor');
1170
+ scope.actor = 'actor';
1171
+ if (code.takesActor && enforced(context))
1172
+ checkedPolicies(target, code.creates, context);
1173
+ }
1174
+ // when: the action, with the record first, then the inputs and a create function per created entity that stores nothing.
1175
+ const entity = target.data.entity ? context.node(target.data.entity) : undefined;
1176
+ const given = [...call.args];
1177
+ const args = [];
1178
+ if (code.takesActor)
1179
+ args.push(persona ? 'actor' : `${accessIn(scope, 'System')}()`);
1180
+ if (entity) {
1181
+ const record = given.shift();
1182
+ const value = record && valueOf({ $type: 'TypeRef', decl: entity.qn }, record, scope);
1183
+ if (!value)
1184
+ throw new Unsupported(`the record passed to ${last(target.qn)} has no Go translation`);
1185
+ args.push(value);
1186
+ }
1187
+ for (const param of context.children(target.qn).filter(c => c.kind === 'Param')) {
1188
+ const type = param.data.type;
1189
+ const expr = given.shift();
1190
+ const value = expr ? valueOf(type, expr, scope) : type.optional || type.many ? 'nil' : undefined;
1191
+ if (!value)
1192
+ throw new Unsupported(`the input ${last(param.qn)} of ${last(target.qn)} has no Go translation`);
1193
+ args.push(value);
1194
+ }
1195
+ for (const created of code.creates)
1196
+ args.push(`func(${typeOf({ $type: 'TypeRef', decl: created.qn }, scope)}) error { return nil }`);
1197
+ const label = last(target.qn);
1198
+ const checks = (data.checks ?? []);
1199
+ const emits = !data.fails && !data.refused && checks.some(c => c.$type === 'Emitted');
1200
+ lines.push(`${emits ? 'events' : '_'}, err := ${qualify(target, scope)}(${args.join(', ')})`);
1201
+ // then: the error, the refusal, or the checks on the rows (changed in place) and the emitted events.
1202
+ if (data.refused) {
1203
+ imports.add('errors');
1204
+ const forbidden = accessIn(scope, 'ErrForbidden');
1205
+ lines.push(`if !errors.Is(err, ${forbidden}) {`, `\tt.Fatalf("${label}: want ${forbidden}, got %v", err)`, '}');
1206
+ }
1207
+ else if (data.fails) {
1208
+ const error = data.error ? context.node(data.error) : undefined;
1209
+ if (error || code.takesActor)
1210
+ imports.add('errors');
1211
+ if (error) {
1212
+ const name = `${qualifyModule(error.module, scope)}.${errorName(error)}`;
1213
+ lines.push(`if !errors.Is(err, ${name}) {`, `\tt.Fatalf("${label}: want ${name}, got %v", err)`, '}');
1214
+ }
1215
+ else if (code.takesActor) {
1216
+ lines.push(`if err == nil || errors.Is(err, ${accessIn(scope, 'ErrForbidden')}) {`, `\tt.Fatalf("${label}: want an error, got %v", err)`, '}');
1217
+ }
1218
+ else {
1219
+ lines.push('if err == nil {', `\tt.Fatalf("${label}: want an error, got none")`, '}');
1220
+ }
1221
+ }
1222
+ else {
1223
+ lines.push('if err != nil {', `\tt.Fatalf("${label}: %v", err)`, '}');
1224
+ const shown = (scenario.props.checks ?? []);
1225
+ checks.forEach((check, i) => lines.push(...checkLines(check, shown[i], scope, context)));
1226
+ }
1227
+ return lines;
1228
+ }
1229
+ /** An expectation as an `if` on the rows, an emitted event as a search through the events the action returns. */
1230
+ function checkLines(check, shown, scope, context) {
1231
+ if (check.$type === 'Expectation') {
1232
+ const condition = goExpr(check.condition, scope);
1233
+ if (!condition)
1234
+ throw new Unsupported(`the check ${shown} has no Go translation`);
1235
+ return [`if !(${condition}) {`, `\tt.Error(${JSON.stringify(`${shown} is false`)})`, '}'];
1236
+ }
1237
+ const event = context.node(check.event);
1238
+ const compared = (check.assignments ?? []).map(a => {
1239
+ const field = fieldsOf(event, context).find(f => last(f.qn) === a.name);
1240
+ const type = field.data.type;
1241
+ if (type.many || (type.decl && context.node(type.decl)?.kind === 'ValueType'))
1242
+ throw new Unsupported(`the field ${a.name} of ${last(event.qn)} does not compare in Go`);
1243
+ const left = { $type: 'MemberExpr', receiver: { $type: 'NameExpr', name: 'got', type: last(event.qn) }, member: a.name, target: field.qn, type: `${type.primitive ?? last(type.decl)}${type.optional ? '?' : ''}` };
1244
+ const same = goExpr({ $type: 'BinaryExpr', op: '==', left, right: a.value, type: 'Bool' }, { ...scope, vars: new Map([...scope.vars ?? [], ['got', 'other']]) });
1245
+ if (!same)
1246
+ throw new Unsupported(`the field ${a.name} of ${last(event.qn)} in ${shown} has no Go translation`);
1247
+ return same;
1248
+ });
1249
+ scope.imports.add('slices');
1250
+ return [
1251
+ 'if !slices.ContainsFunc(events, func(event any) bool {',
1252
+ `\t${compared.length ? 'got' : '_'}, ok := event.(${qualify(event, scope)})`,
1253
+ `\treturn ${['ok', ...compared.map(c => `(${c})`)].join(' && ')}`,
1254
+ '}) {',
1255
+ `\tt.Error(${JSON.stringify(`${shown} did not happen`)})`,
1256
+ '}'
1257
+ ];
1258
+ }
1259
+ /** A value in Go for a field or an input of the type: lists of records or values as slice literals, the rest as `assigned` says it. */
1260
+ function valueOf(type, expr, scope) {
1261
+ if (type.many && expr.$type === 'ListExpr' && expr.items?.length) {
1262
+ const items = expr.items.map(item => valueOf({ ...type, many: false, optional: false }, item, scope));
1263
+ return items.every(i => i) ? `${typeOf(type, scope)}{${items.join(', ')}}` : undefined;
1264
+ }
1265
+ return assigned({ data: { type } }, expr, scope);
1266
+ }
1267
+ /** Every policy the simulator weighs for the actor must be one Go checks the same way, and every role condition one Go says. */
1268
+ function checkedPolicies(action, creates, context) {
1269
+ const entity = action.data.entity;
1270
+ const dry = { ...goScope(action, context, new Set()), self: entity && camel(last(entity)), actor: 'actor' };
1271
+ const policies = [action.qn, ...(entity ? [entity] : []), ...creates.map(c => c.qn)].flatMap(qn => context.children(qn)).filter(c => c.kind === 'Policy');
1272
+ const untranslated = policies.find(p => !goExpr(p.data.condition, dry));
1273
+ if (untranslated)
1274
+ throw new Unsupported(`the policy ${untranslated.qn} has no Go translation`);
1275
+ const role = context.graph.nodes.find(n => n.kind === 'Role' && accessSteps(n, context).some(s => s.kind === 'task'));
1276
+ if (role)
1277
+ throw new Unsupported(`the condition of the role ${last(role.qn)} has no Go translation`);
1278
+ }