@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/README.md +10 -4
- package/out/access.d.ts +23 -0
- package/out/access.js +159 -0
- package/out/golang.d.ts +31 -2
- package/out/golang.js +117 -6
- package/out/index.js +1010 -38
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -21,12 +21,18 @@ Requires Go 1.22 or later. Money and decimals use [shopspring/decimal](https://g
|
|
|
21
21
|
| `value`, `event` | a struct with JSON tags |
|
|
22
22
|
| `entity` | a struct with an `ID`, `New<Entity>()` with the defaults, a method per derived field, and `Validate()` that checks the invariants |
|
|
23
23
|
| optional fields, entity references, lists | pointers, `*Entity`, slices |
|
|
24
|
-
| `action` | a function on the entity that checks the preconditions (returning the declared errors), takes the state transition (`ErrInvalidTransition` otherwise), applies the effects and returns the emitted events |
|
|
24
|
+
| `action` | a function on the entity that checks the preconditions (returning the declared errors), takes the state transition (`ErrInvalidTransition` otherwise), applies the effects and returns the emitted events; a `create` effect builds the record, checks it and hands it to a `create<Entity>` parameter that stores it; `for` loops over a collection relationship, and `update` and `delete` effects check the record and hand it to `update<Entity>` and `delete<Entity>` parameters |
|
|
25
25
|
| `machine` | for transitions on an event, a function `<Machine>On<Event>(event)` |
|
|
26
26
|
| `errors` | `Err<Name>` variables |
|
|
27
|
-
|
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
| `role`, `actor`, `tenant` | the package `internal/access`: `Actor` (type, roles, tenant, the actor fields, records by ID), `Is<Role>(actor)` checks, `New<Actor>()`, `System()` (a call the system makes, which the actions do not check), and `InTenant` with `TenantID()` on every entity that belongs to the tenant |
|
|
28
|
+
| `policy` | pure checks in `policies.go`: `Can<Op><Entity>`, `Can<Op><Entity><Field>`, `Can<Action>` (called by the action, which then takes the actor and returns `access.ErrForbidden`), `Can<Query>`, `Can<UseCase>`. Once the model has any policy, every entity, action and query gets its check, and what no policy covers is denied |
|
|
29
|
+
| invariants | a test in `<module>_test.go`: `valid<Entity>()` passes `Validate`, and one field set to a value the simulator proves to break the invariant fails with its label (without such a value that case stays a registry task) |
|
|
30
|
+
| transitions | a test in `<module>_test.go` per transition an action runs: `valid<Entity>()` in a `from` state reaches the `to` state, a state the action does not leave fails with `ErrInvalidTransition`; with policies it passes an actor the simulator proves allowed. Skipped as a registry task when the simulator cannot prove the preconditions, the guard or the actor |
|
|
31
|
+
| entity policies | a test in `<module>_test.go` per policy on a whole entity that reads the actor only through `actor.is(...)`: `Can<Op><Entity>` on `valid<Entity>()` holds for an actor the simulator proves allowed and fails for one it proves denied. Other policies, and a case without such an actor, stay skipped as registry tasks |
|
|
32
|
+
| preconditions | skipped tests in `<module>_test.go`; writing their bodies is a registry task |
|
|
33
|
+
| `scenario` | a test `TestScenario<Name>` in `scenarios_test.go` (package `<module>_test`): the given rows with an ID each, the actor (`access.System()` without `as`), one call of the action, and the assertions of `then`. It replaces the transition and precondition tests of the action it calls. A scenario that calls a use case, or an action or policy Go does not fully translate, stays a skipped test with a registry task |
|
|
34
|
+
|
|
35
|
+
Queries, projections, interfaces, pages, use cases, external systems and jobs become registry tasks (a query whose filter translates still gets `In<Query>(record, inputs...)`, which says whether a record belongs to its results), as do policies Go cannot translate (their check returns false until written): they need storage, HTTP and scheduling choices the model does not make. The project ends with `gofmt -w .`, and `go test ./...` is the registry's test command. The extension stays at the domain and behavior layers on purpose: generating the layers above means picking a storage, HTTP and scheduling stack, and that choice is deferred while Django and Ash catch up.
|
|
30
36
|
|
|
31
37
|
## License
|
|
32
38
|
|
package/out/access.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { MapContext, Step } from '@appling/codegen';
|
|
2
|
+
import type { GraphNode } from '@appling/model';
|
|
3
|
+
import { type GoAccess } from './golang.js';
|
|
4
|
+
/**
|
|
5
|
+
* The access package: `Actor` (who acts, with its roles, tenant and the fields the actors declare), the role
|
|
6
|
+
* and actor constants, one `Is<Role>` check per role, and the tenant helpers. It has no imports from the model's
|
|
7
|
+
* packages, so every module package can import it; fields that hold records hold their ID.
|
|
8
|
+
*/
|
|
9
|
+
export declare function accessOf(context: MapContext): GoAccess;
|
|
10
|
+
/** The tenant when the workspace declares exactly one; only then does `tenant` mean something. */
|
|
11
|
+
export declare function tenantOf(context: MapContext): GraphNode | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* The entities that belong to the tenant, each with the fields that lead from it to the tenant's entity:
|
|
14
|
+
* the entity itself (no fields), and every entity with a single, not list, reference to one that belongs.
|
|
15
|
+
*/
|
|
16
|
+
export declare function tenantPaths(context: MapContext): Map<string, GraphNode[]>;
|
|
17
|
+
/** The fields of the `Actor` struct by name: those the actors declare, then those of the entities they are stored as. */
|
|
18
|
+
export declare function actorFields(context: MapContext): GraphNode[];
|
|
19
|
+
/** The Go type of an actor field: pointers, so a field is nil for actors without it; records by ID. Undefined for enums and value types. */
|
|
20
|
+
export declare function actorFieldType(field: GraphNode, context: MapContext, imports: Set<string>): string | undefined;
|
|
21
|
+
/** The steps of a role, actor or tenant: the whole access file (each writes the same), plus tasks for what it cannot say. */
|
|
22
|
+
export declare function accessSteps(node: GraphNode, context: MapContext): Step[];
|
|
23
|
+
export declare function accessFile(context: MapContext, access: GoAccess): Step;
|
package/out/access.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { goExpr, pascal, PRIMITIVES } from './golang.js';
|
|
2
|
+
/**
|
|
3
|
+
* The access package: `Actor` (who acts, with its roles, tenant and the fields the actors declare), the role
|
|
4
|
+
* and actor constants, one `Is<Role>` check per role, and the tenant helpers. It has no imports from the model's
|
|
5
|
+
* packages, so every module package can import it; fields that hold records hold their ID.
|
|
6
|
+
*/
|
|
7
|
+
export function accessOf(context) {
|
|
8
|
+
const pkg = context.graph.nodes.some(n => n.kind === 'Module' && n.qn === 'access') ? 'accessctl' : 'access';
|
|
9
|
+
return { pkg, path: `${context.name}/internal/${pkg}`, name: qn => uniqueName(qn, context) };
|
|
10
|
+
}
|
|
11
|
+
/** The tenant when the workspace declares exactly one; only then does `tenant` mean something. */
|
|
12
|
+
export function tenantOf(context) {
|
|
13
|
+
const tenants = context.graph.nodes.filter(n => n.kind === 'Tenant');
|
|
14
|
+
return tenants.length === 1 ? tenants[0] : undefined;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The entities that belong to the tenant, each with the fields that lead from it to the tenant's entity:
|
|
18
|
+
* the entity itself (no fields), and every entity with a single, not list, reference to one that belongs.
|
|
19
|
+
*/
|
|
20
|
+
export function tenantPaths(context) {
|
|
21
|
+
const tenant = tenantOf(context);
|
|
22
|
+
const paths = new Map();
|
|
23
|
+
if (!tenant)
|
|
24
|
+
return paths;
|
|
25
|
+
paths.set(tenant.data.entity, []);
|
|
26
|
+
const entities = context.graph.nodes.filter(n => n.kind === 'Entity');
|
|
27
|
+
for (let changed = true; changed;) {
|
|
28
|
+
changed = false;
|
|
29
|
+
const round = new Map();
|
|
30
|
+
for (const entity of entities) {
|
|
31
|
+
if (paths.has(entity.qn))
|
|
32
|
+
continue;
|
|
33
|
+
const field = context.children(entity.qn).find(f => {
|
|
34
|
+
const type = f.data.type;
|
|
35
|
+
return f.kind === 'Field' && !f.data.derived && type?.decl && !type.many && paths.has(type.decl);
|
|
36
|
+
});
|
|
37
|
+
if (field)
|
|
38
|
+
round.set(entity.qn, [field, ...paths.get(field.data.type.decl)]);
|
|
39
|
+
}
|
|
40
|
+
for (const [qn, path] of round) {
|
|
41
|
+
paths.set(qn, path);
|
|
42
|
+
changed = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return paths;
|
|
46
|
+
}
|
|
47
|
+
/** The fields of the `Actor` struct by name: those the actors declare, then those of the entities they are stored as. */
|
|
48
|
+
export function actorFields(context) {
|
|
49
|
+
const actors = context.graph.nodes.filter(n => n.kind === 'Actor');
|
|
50
|
+
const fields = new Map();
|
|
51
|
+
for (const field of [
|
|
52
|
+
...actors.flatMap(a => context.children(a.qn).filter(c => c.kind === 'Field')),
|
|
53
|
+
...actors.flatMap(a => a.data.entity ? context.children(a.data.entity).filter(c => c.kind === 'Field') : [])
|
|
54
|
+
]) {
|
|
55
|
+
const name = last(field.qn);
|
|
56
|
+
if (!fields.has(name) && !['type', 'roles', 'id', 'tenant'].includes(name))
|
|
57
|
+
fields.set(name, field);
|
|
58
|
+
}
|
|
59
|
+
return [...fields.values()];
|
|
60
|
+
}
|
|
61
|
+
/** The Go type of an actor field: pointers, so a field is nil for actors without it; records by ID. Undefined for enums and value types. */
|
|
62
|
+
export function actorFieldType(field, context, imports) {
|
|
63
|
+
const type = field.data.type;
|
|
64
|
+
let base;
|
|
65
|
+
if (type.primitive) {
|
|
66
|
+
const [name, pkg] = PRIMITIVES[type.primitive];
|
|
67
|
+
if (pkg)
|
|
68
|
+
imports.add(pkg);
|
|
69
|
+
base = name;
|
|
70
|
+
}
|
|
71
|
+
else if (context.node(type.decl)?.kind === 'Entity')
|
|
72
|
+
base = 'int64';
|
|
73
|
+
else
|
|
74
|
+
return undefined;
|
|
75
|
+
return type.many ? `[]${base}` : `*${base}`;
|
|
76
|
+
}
|
|
77
|
+
/** The steps of a role, actor or tenant: the whole access file (each writes the same), plus tasks for what it cannot say. */
|
|
78
|
+
export function accessSteps(node, context) {
|
|
79
|
+
const access = accessOf(context);
|
|
80
|
+
const steps = [accessFile(context, access)];
|
|
81
|
+
if (node.kind === 'Role' && node.data.condition && !roleCondition(node, context, access, new Set())) {
|
|
82
|
+
steps.push({ kind: 'task', what: `check the condition of ${last(node.qn)} in ${access.pkg}.Is${access.name(node.qn)}: ${node.props.condition}` });
|
|
83
|
+
}
|
|
84
|
+
if (node.kind === 'Tenant' && !tenantOf(context)) {
|
|
85
|
+
steps.push({ kind: 'task', what: `decide how the tenant ${last(node.qn)} scopes the records; with several tenants, the generated Actor has no Tenant` });
|
|
86
|
+
}
|
|
87
|
+
return steps;
|
|
88
|
+
}
|
|
89
|
+
export function accessFile(context, access) {
|
|
90
|
+
return { kind: 'template', file: `internal/${access.pkg}/${access.pkg}.go`, write: () => accessCode(context, access) };
|
|
91
|
+
}
|
|
92
|
+
function accessCode(context, access) {
|
|
93
|
+
const imports = new Set(['errors', 'slices']);
|
|
94
|
+
const roles = context.graph.nodes.filter(n => n.kind === 'Role');
|
|
95
|
+
const actors = context.graph.nodes.filter(n => n.kind === 'Actor');
|
|
96
|
+
const tenant = tenantOf(context);
|
|
97
|
+
const tenantEntity = tenant && tenant.data.entity;
|
|
98
|
+
const blocks = [
|
|
99
|
+
'// ErrForbidden is returned by an action when its policies do not grant it to the actor.\nvar ErrForbidden = errors.New("forbidden")',
|
|
100
|
+
`// Role is a role of the model, by qualified name.\ntype Role string${roles.length ? `\n\nconst (\n${roles.map(r => `\t// Role${access.name(r.qn)} is the role ${r.qn}.\n\tRole${access.name(r.qn)} Role = ${JSON.stringify(r.qn)}`).join('\n')}\n)` : ''}`,
|
|
101
|
+
`// ActorType is a declared actor of the model, by qualified name.\ntype ActorType string${actors.length ? `\n\nconst (\n${actors.map(a => `\t// Actor${access.name(a.qn)} is the ${a.data.kind} actor ${a.qn}.\n\tActor${access.name(a.qn)} ActorType = ${JSON.stringify(a.qn)}`).join('\n')}\n)` : ''}`
|
|
102
|
+
];
|
|
103
|
+
const fields = actorFields(context).flatMap(field => {
|
|
104
|
+
const type = actorFieldType(field, context, imports);
|
|
105
|
+
if (!type)
|
|
106
|
+
return [];
|
|
107
|
+
const owner = parentOf(field.qn);
|
|
108
|
+
const record = field.data.type.decl ? `, the ID of a ${field.data.type.decl}` : '';
|
|
109
|
+
return [`\t// ${pascal(last(field.qn))} is the field ${last(field.qn)} of ${owner}${record}.`, `\t${pascal(last(field.qn))} ${type} \`json:"${last(field.qn)}"\``];
|
|
110
|
+
});
|
|
111
|
+
blocks.push([
|
|
112
|
+
'// Actor is who acts: a declared actor with the roles it carries, the tenant it acts in, and the fields',
|
|
113
|
+
'// the actors declare. A field is nil for actors that do not declare it; fields that hold records hold their ID.',
|
|
114
|
+
'type Actor struct {',
|
|
115
|
+
'\tType ActorType `json:"type"`',
|
|
116
|
+
'\tRoles []Role `json:"roles"`',
|
|
117
|
+
'\t// ID is the record the actor is stored as, for actors declared with `is`.',
|
|
118
|
+
'\tID *int64 `json:"id"`',
|
|
119
|
+
...(tenant ? [`\t// Tenant is the ID of the ${tenantEntity} the actor acts in (the tenant ${tenant.qn}); nil when it acts across tenants.`, '\tTenant *int64 `json:"tenant"`'] : []),
|
|
120
|
+
...fields,
|
|
121
|
+
'\t// system marks a call the system makes; only System sets it.',
|
|
122
|
+
'\tsystem bool',
|
|
123
|
+
'}'
|
|
124
|
+
].join('\n'));
|
|
125
|
+
blocks.push('// System returns the actor of a call the system makes, such as a job, an event handler or a scenario without\n// an actor: the actions check no policy and no tenant for it. The zero Actor is not the system.\nfunc System() Actor {\n\treturn Actor{system: true}\n}', '// IsSystem reports whether the call is one the system makes, which the actions do not check.\nfunc (a Actor) IsSystem() bool {\n\treturn a.system\n}');
|
|
126
|
+
for (const actor of actors) {
|
|
127
|
+
const name = access.name(actor.qn);
|
|
128
|
+
const roleList = (actor.data.roles ?? []).map(r => `Role${access.name(r)}`).join(', ');
|
|
129
|
+
blocks.push(`// New${name} returns the actor ${actor.qn} with the roles it declares.\nfunc New${name}() Actor {\n\treturn Actor{Type: Actor${name}, Roles: []Role{${roleList}}}\n}`);
|
|
130
|
+
}
|
|
131
|
+
blocks.push('// Has reports whether the actor carries the role, without checking the role\'s condition.\nfunc (a Actor) Has(role Role) bool {\n\treturn slices.Contains(a.Roles, role)\n}');
|
|
132
|
+
for (const role of roles) {
|
|
133
|
+
const name = access.name(role.qn);
|
|
134
|
+
const condition = role.data.condition ? roleCondition(role, context, access, imports) : undefined;
|
|
135
|
+
const body = !role.data.condition ? `actor.Has(Role${name})` : condition ? `actor.Has(Role${name}) && (${condition})` : 'false';
|
|
136
|
+
blocks.push(`// Is${name} reports whether the actor is ${role.qn}: it carries the role${role.data.condition ? ' and the role\'s condition holds' : ''}.\nfunc Is${name}(actor Actor) bool {\n\treturn ${body}\n}`);
|
|
137
|
+
}
|
|
138
|
+
blocks.push('// Value returns what an optional actor field points to, or the zero value when the actor does not have it.\nfunc Value[T any](p *T) T {\n\tif p == nil {\n\t\tvar zero T\n\t\treturn zero\n\t}\n\treturn *p\n}', '// Same reports whether a record ID of the actor refers to the record with the given ID.\nfunc Same(ref *int64, id int64) bool {\n\treturn ref != nil && *ref == id\n}', '// SameRef reports whether two record IDs of the actor refer to the same record.\nfunc SameRef(a, b *int64) bool {\n\treturn a != nil && b != nil && *a == *b\n}');
|
|
139
|
+
if (tenant)
|
|
140
|
+
blocks.push(`// Tenanted is a record that belongs to a ${tenantEntity}, the entity of the tenant ${tenant.qn}.\ntype Tenanted interface {\n\t// TenantID returns the ID of the ${tenantEntity}, and false when the record does not reach one.\n\tTenantID() (int64, bool)\n}`, '// InTenant reports whether the record belongs to the tenant the actor acts in. An actor without a tenant acts across tenants.\nfunc InTenant(actor Actor, record Tenanted) bool {\n\tif actor.Tenant == nil {\n\t\treturn true\n\t}\n\tid, ok := record.TenantID()\n\treturn ok && id == *actor.Tenant\n}');
|
|
141
|
+
const all = [...imports].sort((a, b) => Number(a.includes('.')) - Number(b.includes('.')) || a.localeCompare(b));
|
|
142
|
+
return `// Package ${access.pkg} holds the actors, roles and tenant of the model and the checks its policies call.\npackage ${access.pkg}\n\nimport (\n${all.map(i => `\t"${i}"`).join('\n')}\n)\n\n${blocks.join('\n\n')}\n`;
|
|
143
|
+
}
|
|
144
|
+
function roleCondition(role, context, access, imports) {
|
|
145
|
+
const scope = { node: context.node, pkg: access.pkg, imports, importOf: () => access.path, actor: 'actor', access };
|
|
146
|
+
return goExpr(role.data.condition, scope);
|
|
147
|
+
}
|
|
148
|
+
/** The last name of a role or actor, or its module path and name when another role or actor has the same last name. */
|
|
149
|
+
function uniqueName(qn, context) {
|
|
150
|
+
const node = context.node(qn);
|
|
151
|
+
const clash = context.graph.nodes.some(n => n.kind === node.kind && n.qn !== qn && last(n.qn) === last(qn));
|
|
152
|
+
return clash ? qn.split('.').map(pascal).join('') : pascal(last(qn));
|
|
153
|
+
}
|
|
154
|
+
function parentOf(qn) {
|
|
155
|
+
return qn.slice(0, qn.lastIndexOf('.'));
|
|
156
|
+
}
|
|
157
|
+
function last(qn) {
|
|
158
|
+
return qn.slice(qn.lastIndexOf('.') + 1);
|
|
159
|
+
}
|
package/out/golang.d.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import type { ExprData, GraphNode } from '@appling/model';
|
|
2
2
|
/** What a translated expression is in Go, which decides the operators: decimals and times have methods. */
|
|
3
|
-
type Kind = 'decimal' | 'time' | 'duration' | 'int' | 'string' | 'bool' | 'list' | 'null' | 'other';
|
|
3
|
+
type Kind = 'decimal' | 'time' | 'duration' | 'int' | 'string' | 'bool' | 'list' | 'null' | 'other' | 'id';
|
|
4
|
+
/** The generated access package: the actor, role and tenant checks that policies and role conditions call. */
|
|
5
|
+
export interface GoAccess {
|
|
6
|
+
/** The package name, such as `access`. */
|
|
7
|
+
pkg: string;
|
|
8
|
+
/** The import path, such as `shop/internal/access`. */
|
|
9
|
+
path: string;
|
|
10
|
+
/** The Go name of a role or actor, such as `Clerk`, prefixed with its module when the last name is not unique. */
|
|
11
|
+
name(qn: string): string;
|
|
12
|
+
}
|
|
4
13
|
export interface GoScope {
|
|
5
14
|
node(qn: string): GraphNode | undefined;
|
|
6
15
|
/** The variable holding the record, such as `o` in a method or `order` in an action. */
|
|
@@ -8,12 +17,32 @@ export interface GoScope {
|
|
|
8
17
|
/** The Go package the code is written in, to qualify names from other modules. */
|
|
9
18
|
pkg: string;
|
|
10
19
|
vars?: Map<string, Kind>;
|
|
20
|
+
/** The Go variable of a name in `vars` when it differs from the name, such as `typeRow` for `type`. */
|
|
21
|
+
rename?: Map<string, string>;
|
|
11
22
|
imports: Set<string>;
|
|
12
23
|
/** The Go import path of a module, such as `shop/internal/crm`. */
|
|
13
24
|
importOf(module: string): string;
|
|
25
|
+
/** The variable holding the current `access.Actor`, in policies and role conditions; without it `actor` and `tenant` do not translate. */
|
|
26
|
+
actor?: string;
|
|
27
|
+
access?: GoAccess;
|
|
14
28
|
}
|
|
15
|
-
/** Translates an expression to Go, or returns undefined when Go code cannot say it, such as a policy
|
|
29
|
+
/** Translates an expression to Go, or returns undefined when Go code cannot say it, such as `actor` outside a policy. */
|
|
16
30
|
export declare function goExpr(expr: ExprData, scope: GoScope): string | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Translates an expression for an assignment: `value` reads it (`*p` for a pointer), `raw` is the code as it is
|
|
33
|
+
* (the pointer itself for an optional field or input), `null` marks the literal `null` and `empty` the empty list `[]`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function goTerm(expr: ExprData, scope: GoScope): {
|
|
36
|
+
value: string;
|
|
37
|
+
raw: string;
|
|
38
|
+
pointer: boolean;
|
|
39
|
+
null: boolean;
|
|
40
|
+
empty?: boolean;
|
|
41
|
+
} | undefined;
|
|
42
|
+
/** The Go type of a primitive and the package it needs. */
|
|
43
|
+
export declare const PRIMITIVES: {
|
|
44
|
+
[name: string]: [string, string?];
|
|
45
|
+
};
|
|
17
46
|
/** The Go type of an Appling type name as the typer shows it, such as `Money`, `Line[]` or `DateTime?`. */
|
|
18
47
|
export declare function kindOf(type: string): Kind;
|
|
19
48
|
/** The Go constant of an enum value, qualified with its package outside its module. */
|
package/out/golang.js
CHANGED
|
@@ -1,11 +1,27 @@
|
|
|
1
1
|
const COMPARE = { '<': 'LessThan', '<=': 'LessThanOrEqual', '>': 'GreaterThan', '>=': 'GreaterThanOrEqual' };
|
|
2
2
|
const ARITHMETIC = { '+': 'Add', '-': 'Sub', '*': 'Mul', '/': 'Div' };
|
|
3
3
|
const UNITS = { ms: 'time.Millisecond', s: 'time.Second', m: 'time.Minute', h: 'time.Hour', d: '24 * time.Hour' };
|
|
4
|
-
/** Translates an expression to Go, or returns undefined when Go code cannot say it, such as a policy
|
|
4
|
+
/** Translates an expression to Go, or returns undefined when Go code cannot say it, such as `actor` outside a policy. */
|
|
5
5
|
export function goExpr(expr, scope) {
|
|
6
6
|
const result = translate(expr, scope);
|
|
7
7
|
return result && value(result);
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Translates an expression for an assignment: `value` reads it (`*p` for a pointer), `raw` is the code as it is
|
|
11
|
+
* (the pointer itself for an optional field or input), `null` marks the literal `null` and `empty` the empty list `[]`.
|
|
12
|
+
*/
|
|
13
|
+
export function goTerm(expr, scope) {
|
|
14
|
+
if (expr.$type === 'ListExpr' && !expr.items?.length)
|
|
15
|
+
return { value: '', raw: '', pointer: false, null: false, empty: true };
|
|
16
|
+
const result = translate(expr, scope);
|
|
17
|
+
return result && { value: value(result), raw: result.code, pointer: !!result.pointer, null: result.kind === 'null' };
|
|
18
|
+
}
|
|
19
|
+
/** The Go type of a primitive and the package it needs. */
|
|
20
|
+
export const PRIMITIVES = {
|
|
21
|
+
String: ['string'], Text: ['string'], Int: ['int64'], Bool: ['bool'], File: ['string'], Uuid: ['string'],
|
|
22
|
+
Decimal: ['decimal.Decimal', 'github.com/shopspring/decimal'], Money: ['decimal.Decimal', 'github.com/shopspring/decimal'],
|
|
23
|
+
Date: ['time.Time', 'time'], DateTime: ['time.Time', 'time'], Duration: ['time.Duration', 'time']
|
|
24
|
+
};
|
|
9
25
|
/** The Go type of an Appling type name as the typer shows it, such as `Money`, `Line[]` or `DateTime?`. */
|
|
10
26
|
export function kindOf(type) {
|
|
11
27
|
const base = type.replace(/\?$/, '');
|
|
@@ -29,7 +45,10 @@ function translate(expr, scope) {
|
|
|
29
45
|
}
|
|
30
46
|
case 'BinaryExpr': return binary(expr, scope);
|
|
31
47
|
case 'NameExpr': return expr.call ? call(expr, scope) : name(expr, scope);
|
|
32
|
-
case 'MemberExpr':
|
|
48
|
+
case 'MemberExpr':
|
|
49
|
+
if (isActor(expr.receiver, scope))
|
|
50
|
+
return actorMember(expr, scope);
|
|
51
|
+
return expr.call ? method(expr, scope) : member(expr, scope);
|
|
33
52
|
case 'IndexExpr': {
|
|
34
53
|
const [list, index] = [translate(expr.receiver, scope), translate(expr.index, scope)];
|
|
35
54
|
return list && index ? { code: `${value(list)}[${value(index)}]`, kind: kindOf(expr.type) } : undefined;
|
|
@@ -56,6 +75,15 @@ function binary(expr, scope) {
|
|
|
56
75
|
const subject = left.kind === 'null' ? right : left;
|
|
57
76
|
return { code: `${subject.code} ${op} nil`, kind: 'bool' };
|
|
58
77
|
}
|
|
78
|
+
if (left.kind === 'id' || right.kind === 'id') {
|
|
79
|
+
const same = sameRecord(left, right, scope);
|
|
80
|
+
if (!same || (op !== '==' && op !== '!='))
|
|
81
|
+
return undefined;
|
|
82
|
+
return { code: op === '!=' ? `!${wrap(same)}` : same, kind: 'bool' };
|
|
83
|
+
}
|
|
84
|
+
// Two records are the same when their IDs are: `order.Customer.ID == of.ID`.
|
|
85
|
+
if ((op === '==' || op === '!=') && isRecord(expr.left, scope) && isRecord(expr.right, scope))
|
|
86
|
+
return { code: `${left.code}.ID ${op} ${right.code}.ID`, kind: 'bool' };
|
|
59
87
|
const kinds = [left.kind, right.kind];
|
|
60
88
|
if (kinds.includes('decimal')) {
|
|
61
89
|
const [a, b] = [decimal(left, scope), decimal(right, scope)];
|
|
@@ -82,7 +110,11 @@ function binary(expr, scope) {
|
|
|
82
110
|
function name(expr, scope) {
|
|
83
111
|
const id = expr.name;
|
|
84
112
|
if (scope.vars?.has(id))
|
|
85
|
-
return { code: id, kind: scope.vars.get(id) };
|
|
113
|
+
return { code: scope.rename?.get(id) ?? id, kind: scope.vars.get(id) };
|
|
114
|
+
if (isActor(expr, scope))
|
|
115
|
+
return scope.actor ? { code: `${scope.actor}.ID`, kind: 'id', pointer: true } : undefined;
|
|
116
|
+
if (expr.target && scope.node(expr.target)?.kind === 'Tenant')
|
|
117
|
+
return scope.actor ? { code: `${scope.actor}.Tenant`, kind: 'id', pointer: true } : undefined;
|
|
86
118
|
if (!expr.target) {
|
|
87
119
|
if (id === 'this')
|
|
88
120
|
return scope.self ? { code: scope.self, kind: 'other' } : undefined;
|
|
@@ -105,7 +137,7 @@ function name(expr, scope) {
|
|
|
105
137
|
function member(expr, scope) {
|
|
106
138
|
const receiver = translate(expr.receiver, scope);
|
|
107
139
|
const target = expr.target ? scope.node(expr.target) : undefined;
|
|
108
|
-
if (!receiver || target?.kind !== 'Field' || !isRecordField(target, scope))
|
|
140
|
+
if (!receiver || receiver.kind === 'id' || target?.kind !== 'Field' || !isRecordField(target, scope))
|
|
109
141
|
return undefined;
|
|
110
142
|
return { code: `${value(receiver)}.${pascal(expr.member)}${target.data.derived ? '()' : ''}`, kind: kindOf(expr.type), pointer: optional(target) };
|
|
111
143
|
}
|
|
@@ -181,10 +213,89 @@ function decimal(go, scope) {
|
|
|
181
213
|
return /^\d+$/.test(go.code) ? `decimal.NewFromInt(${go.code})` : /^[\d.]+$/.test(go.code) ? `decimal.RequireFromString(${JSON.stringify(go.code)})` : `decimal.NewFromInt(${value(go)})`;
|
|
182
214
|
}
|
|
183
215
|
function value(go) {
|
|
184
|
-
return go.pointer ? `(*${go.code})` : go.code;
|
|
216
|
+
return go.read ?? (go.pointer ? `(*${go.code})` : go.code);
|
|
217
|
+
}
|
|
218
|
+
/** The name `actor` itself, not a lambda variable or a field that happens to be called so. */
|
|
219
|
+
function isActor(expr, scope) {
|
|
220
|
+
return expr.$type === 'NameExpr' && expr.name === 'actor' && !expr.target && !expr.call && !scope.vars?.has('actor');
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* `actor.is(X)` calls the role check `IsX` or compares the actor type; `actor.field` reads the field of the
|
|
224
|
+
* `access.Actor`, a pointer that is nil for actors without it. Fields that hold records hold their ID.
|
|
225
|
+
*/
|
|
226
|
+
function actorMember(expr, scope) {
|
|
227
|
+
const { actor, access } = scope;
|
|
228
|
+
if (!actor || !access)
|
|
229
|
+
return undefined;
|
|
230
|
+
if (expr.call) {
|
|
231
|
+
const target = expr.member === 'is' && expr.args?.[0]?.target ? scope.node(expr.args[0].target) : undefined;
|
|
232
|
+
if (target?.kind === 'Role')
|
|
233
|
+
return { code: `${accessName(`Is${access.name(target.qn)}`, scope)}(${actor})`, kind: 'bool' };
|
|
234
|
+
if (target?.kind === 'Actor')
|
|
235
|
+
return { code: `${actor}.Type == ${accessName(`Actor${access.name(target.qn)}`, scope)}`, kind: 'bool' };
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
const target = expr.target ? scope.node(expr.target) : undefined;
|
|
239
|
+
const type = target?.kind === 'Field' ? target.data.type : undefined;
|
|
240
|
+
if (!type)
|
|
241
|
+
return undefined;
|
|
242
|
+
const code = `${actor}.${pascal(expr.member)}`;
|
|
243
|
+
if (type.many)
|
|
244
|
+
return { code, kind: 'list' };
|
|
245
|
+
if (type.decl)
|
|
246
|
+
return scope.node(type.decl)?.kind === 'Entity' ? { code, kind: 'id', pointer: true } : undefined;
|
|
247
|
+
return { code, kind: kindOf(type.primitive), pointer: true, read: `${accessName('Value', scope)}(${code})` };
|
|
248
|
+
}
|
|
249
|
+
/** Whether a record ID of the actor (or the tenant) refers to a record: `access.Same(actor.Account, order.Customer.ID)`. */
|
|
250
|
+
function sameRecord(left, right, scope) {
|
|
251
|
+
if (left.kind === 'id' && right.kind === 'id')
|
|
252
|
+
return `${accessName('SameRef', scope)}(${left.code}, ${right.code})`;
|
|
253
|
+
const [id, record] = left.kind === 'id' ? [left, right] : [right, left];
|
|
254
|
+
if (record.kind !== 'other')
|
|
255
|
+
return undefined;
|
|
256
|
+
const same = `${accessName('Same', scope)}(${id.code}, ${record.code}.ID)`;
|
|
257
|
+
return record.pointer ? `(${record.code} != nil && ${same})` : same;
|
|
258
|
+
}
|
|
259
|
+
/** A name from the access package, qualified outside it. */
|
|
260
|
+
function accessName(name, scope) {
|
|
261
|
+
const access = scope.access;
|
|
262
|
+
if (access.pkg === scope.pkg)
|
|
263
|
+
return name;
|
|
264
|
+
scope.imports.add(access.path);
|
|
265
|
+
return `${access.pkg}.${name}`;
|
|
185
266
|
}
|
|
186
267
|
function wrap(code) {
|
|
187
|
-
return
|
|
268
|
+
return atomic(code) ? code : `(${code})`;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Whether the code needs no parentheses as an operand: names, calls and selectors (`a.B(x).C`), one
|
|
272
|
+
* parenthesized group or a string. Brackets are matched, so `f(a) && g(b)` is not atomic.
|
|
273
|
+
*/
|
|
274
|
+
function atomic(code) {
|
|
275
|
+
if (/^"([^"\\]|\\.)*"$/.test(code))
|
|
276
|
+
return true;
|
|
277
|
+
let depth = 0;
|
|
278
|
+
for (let i = 0; i < code.length; i++) {
|
|
279
|
+
const c = code[i];
|
|
280
|
+
if (c === '"') {
|
|
281
|
+
for (i++; i < code.length && code[i] !== '"'; i++)
|
|
282
|
+
if (code[i] === '\\')
|
|
283
|
+
i++;
|
|
284
|
+
}
|
|
285
|
+
else if ('([{'.includes(c))
|
|
286
|
+
depth++;
|
|
287
|
+
else if (')]}'.includes(c))
|
|
288
|
+
depth--;
|
|
289
|
+
else if (depth === 0 && !/[\w.]/.test(c))
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
return depth === 0;
|
|
293
|
+
}
|
|
294
|
+
/** Whether the expression names one record of an entity: a field or an input of an entity type. */
|
|
295
|
+
function isRecord(expr, scope) {
|
|
296
|
+
const target = expr.target && !expr.call ? scope.node(expr.target) : undefined;
|
|
297
|
+
const type = target?.kind === 'Field' || target?.kind === 'Param' ? target.data.type : undefined;
|
|
298
|
+
return !!type?.decl && !type.many && scope.node(type.decl)?.kind === 'Entity';
|
|
188
299
|
}
|
|
189
300
|
function isRecordField(field, scope) {
|
|
190
301
|
const owner = scope.node(field.qn.slice(0, field.qn.lastIndexOf('.')))?.kind;
|