@hyperscale0/hsx 2.4.1 → 3.0.0

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.
Files changed (249) hide show
  1. package/CHANGELOG.md +2 -408
  2. package/README.md +3 -92
  3. package/dist/src/ast.d.ts +99 -310
  4. package/dist/src/ast.d.ts.map +1 -1
  5. package/dist/src/ast.js +16 -69
  6. package/dist/src/ast.js.map +1 -1
  7. package/dist/src/cli.d.ts +6 -19
  8. package/dist/src/cli.d.ts.map +1 -1
  9. package/dist/src/cli.js +76 -315
  10. package/dist/src/cli.js.map +1 -1
  11. package/dist/src/compile.d.ts +23 -73
  12. package/dist/src/compile.d.ts.map +1 -1
  13. package/dist/src/compile.js +1113 -148
  14. package/dist/src/compile.js.map +1 -1
  15. package/dist/src/cost.d.ts +8 -77
  16. package/dist/src/cost.d.ts.map +1 -1
  17. package/dist/src/cost.js +13 -422
  18. package/dist/src/cost.js.map +1 -1
  19. package/dist/src/format.d.ts +8 -7
  20. package/dist/src/format.d.ts.map +1 -1
  21. package/dist/src/format.js +9 -175
  22. package/dist/src/format.js.map +1 -1
  23. package/dist/src/headers.d.ts +35 -0
  24. package/dist/src/headers.d.ts.map +1 -0
  25. package/dist/src/headers.js +108 -0
  26. package/dist/src/headers.js.map +1 -0
  27. package/dist/src/index.d.ts +6 -12
  28. package/dist/src/index.d.ts.map +1 -1
  29. package/dist/src/index.js +4 -9
  30. package/dist/src/index.js.map +1 -1
  31. package/dist/src/lex.d.ts +8 -28
  32. package/dist/src/lex.d.ts.map +1 -1
  33. package/dist/src/lex.js +88 -146
  34. package/dist/src/lex.js.map +1 -1
  35. package/dist/src/parse.d.ts +4 -17
  36. package/dist/src/parse.d.ts.map +1 -1
  37. package/dist/src/parse.js +402 -1040
  38. package/dist/src/parse.js.map +1 -1
  39. package/dist/src/std-bundle.d.ts.map +1 -1
  40. package/dist/src/std-bundle.js +12 -20
  41. package/dist/src/std-bundle.js.map +1 -1
  42. package/dist/src/std-library.d.ts +1 -1
  43. package/dist/src/std-library.d.ts.map +1 -1
  44. package/dist/src/std-library.js +1 -5
  45. package/dist/src/std-library.js.map +1 -1
  46. package/dist/src/tunables.d.ts +7 -0
  47. package/dist/src/tunables.d.ts.map +1 -0
  48. package/dist/src/tunables.js +26 -0
  49. package/dist/src/tunables.js.map +1 -0
  50. package/dist/src/version.d.ts +2 -4
  51. package/dist/src/version.d.ts.map +1 -1
  52. package/dist/src/version.js +2 -4
  53. package/dist/src/version.js.map +1 -1
  54. package/docs/README.md +179 -41
  55. package/docs/headers.md +44 -0
  56. package/examples/cost-table.json +99 -751
  57. package/examples/library.hsx +59 -0
  58. package/package.json +9 -17
  59. package/src/ast.ts +82 -441
  60. package/src/cli.ts +77 -362
  61. package/src/compile.ts +1535 -247
  62. package/src/cost.ts +28 -671
  63. package/src/format.ts +12 -256
  64. package/src/headers.ts +126 -0
  65. package/src/index.ts +7 -39
  66. package/src/lex.ts +99 -195
  67. package/src/parse.ts +403 -1209
  68. package/src/std-bundle.ts +12 -20
  69. package/src/std-library.ts +2 -7
  70. package/src/tunables.ts +31 -0
  71. package/src/version.ts +2 -5
  72. package/std/approvals.hsx +17 -0
  73. package/std/cards.hsx +63 -0
  74. package/std/collections.hsx +31 -0
  75. package/std/escrow.hsx +43 -0
  76. package/std/financing.hsx +372 -0
  77. package/std/insurance.hsx +59 -0
  78. package/std/lending.hsx +115 -0
  79. package/std/marketplace.hsx +24 -0
  80. package/std/money.hsx +195 -0
  81. package/std/savings.hsx +44 -0
  82. package/std/travel.hsx +98 -0
  83. package/std/wallet.hsx +41 -0
  84. package/dist/src/diagnostics.d.ts +0 -13
  85. package/dist/src/diagnostics.d.ts.map +0 -1
  86. package/dist/src/diagnostics.js +0 -587
  87. package/dist/src/diagnostics.js.map +0 -1
  88. package/dist/src/emit.d.ts +0 -51
  89. package/dist/src/emit.d.ts.map +0 -1
  90. package/dist/src/emit.js +0 -192
  91. package/dist/src/emit.js.map +0 -1
  92. package/dist/src/entry-overrides.d.ts +0 -58
  93. package/dist/src/entry-overrides.d.ts.map +0 -1
  94. package/dist/src/entry-overrides.js +0 -284
  95. package/dist/src/entry-overrides.js.map +0 -1
  96. package/dist/src/ir.d.ts +0 -73
  97. package/dist/src/ir.d.ts.map +0 -1
  98. package/dist/src/ir.js +0 -15
  99. package/dist/src/ir.js.map +0 -1
  100. package/dist/src/limits.d.ts +0 -23
  101. package/dist/src/limits.d.ts.map +0 -1
  102. package/dist/src/limits.js +0 -23
  103. package/dist/src/limits.js.map +0 -1
  104. package/dist/src/lsp/server.d.ts +0 -32
  105. package/dist/src/lsp/server.d.ts.map +0 -1
  106. package/dist/src/lsp/server.js +0 -391
  107. package/dist/src/lsp/server.js.map +0 -1
  108. package/dist/src/modules.d.ts +0 -38
  109. package/dist/src/modules.d.ts.map +0 -1
  110. package/dist/src/modules.js +0 -372
  111. package/dist/src/modules.js.map +0 -1
  112. package/dist/src/typecheck.d.ts +0 -8
  113. package/dist/src/typecheck.d.ts.map +0 -1
  114. package/dist/src/typecheck.js +0 -4160
  115. package/dist/src/typecheck.js.map +0 -1
  116. package/docs/guide/01-first-program.md +0 -24
  117. package/docs/guide/02-money.md +0 -25
  118. package/docs/guide/03-instruments.md +0 -93
  119. package/docs/guide/04-lifecycles.md +0 -40
  120. package/docs/guide/05-fees-and-splits.md +0 -45
  121. package/docs/guide/06-schedules.md +0 -26
  122. package/docs/guide/07-composition.md +0 -52
  123. package/docs/guide/08-writing-a-module.md +0 -85
  124. package/docs/guide/09-cost.md +0 -24
  125. package/docs/guide/10-diagnostics.md +0 -27
  126. package/docs/llms-full.txt +0 -3684
  127. package/docs/llms.txt +0 -44
  128. package/docs/piece-plans.md +0 -120
  129. package/docs/playground.md +0 -55
  130. package/docs/reference/cli.md +0 -36
  131. package/docs/reference/diagnostics.md +0 -901
  132. package/docs/reference/grammar.md +0 -38
  133. package/docs/reference/std/advance.md +0 -112
  134. package/docs/reference/std/cancellable_booking.md +0 -159
  135. package/docs/reference/std/captured_payment.md +0 -115
  136. package/docs/reference/std/conditional_disbursement.md +0 -101
  137. package/docs/reference/std/credit_facility.md +0 -108
  138. package/docs/reference/std/held_payment.md +0 -173
  139. package/docs/reference/std/instant_transfer.md +0 -97
  140. package/docs/reference/std/metered.md +0 -89
  141. package/docs/reference/std/pooled_split.md +0 -95
  142. package/docs/reference/std/premium_forward.md +0 -119
  143. package/docs/reference/std/reconciled_payout.md +0 -103
  144. package/docs/reference/std/rotating_pool.md +0 -130
  145. package/docs/reference/std/scheduled.md +0 -136
  146. package/docs/reference/std/security_deposit.md +0 -138
  147. package/docs/reference/std/settlement_batch.md +0 -123
  148. package/docs/reference/std/swap.md +0 -133
  149. package/docs/reference/std/threshold_pool.md +0 -138
  150. package/docs/reference/std/weighted_distribution.md +0 -135
  151. package/docs/reference/types.md +0 -61
  152. package/docs/reference/udl-output.md +0 -13
  153. package/examples/01-first-program/README.md +0 -45
  154. package/examples/01-first-program/tip-jar.hsx +0 -17
  155. package/examples/02-imports-and-modules/README.md +0 -96
  156. package/examples/02-imports-and-modules/photo-booth.hsx +0 -37
  157. package/examples/03-diagnostics/README.md +0 -68
  158. package/examples/03-diagnostics/corner-shop-fixed.hsx +0 -22
  159. package/examples/03-diagnostics/corner-shop.hsx +0 -19
  160. package/examples/04-complete-product/README.md +0 -84
  161. package/examples/04-complete-product/study-hall.hsx +0 -67
  162. package/examples/05-authored-instrument/README.md +0 -5
  163. package/examples/05-authored-instrument/payment.hsx +0 -37
  164. package/examples/05-watch-club/README.md +0 -6
  165. package/examples/05-watch-club/watch-club.hsx +0 -123
  166. package/examples/README.md +0 -48
  167. package/examples/advance/README.md +0 -3
  168. package/examples/advance/advance.hsx +0 -13
  169. package/examples/advance/advance.udl +0 -367
  170. package/examples/cancellable_booking/README.md +0 -3
  171. package/examples/cancellable_booking/cancellable_booking.hsx +0 -14
  172. package/examples/cancellable_booking/cancellable_booking.udl +0 -413
  173. package/examples/captured_payment/README.md +0 -3
  174. package/examples/captured_payment/captured_payment.hsx +0 -17
  175. package/examples/captured_payment/captured_payment.udl +0 -686
  176. package/examples/conditional_disbursement/README.md +0 -3
  177. package/examples/conditional_disbursement/conditional_disbursement.hsx +0 -15
  178. package/examples/conditional_disbursement/conditional_disbursement.udl +0 -418
  179. package/examples/credit_facility/README.md +0 -3
  180. package/examples/credit_facility/credit_facility.hsx +0 -24
  181. package/examples/credit_facility/credit_facility.udl +0 -1396
  182. package/examples/held_payment/README.md +0 -3
  183. package/examples/held_payment/held_payment.hsx +0 -13
  184. package/examples/held_payment/held_payment.udl +0 -569
  185. package/examples/instant_transfer/README.md +0 -3
  186. package/examples/instant_transfer/instant_transfer.hsx +0 -16
  187. package/examples/instant_transfer/instant_transfer.udl +0 -376
  188. package/examples/metered/README.md +0 -3
  189. package/examples/metered/metered.hsx +0 -13
  190. package/examples/metered/metered.udl +0 -253
  191. package/examples/pooled_split/README.md +0 -3
  192. package/examples/pooled_split/pooled_split.hsx +0 -15
  193. package/examples/pooled_split/pooled_split.udl +0 -432
  194. package/examples/premium_forward/README.md +0 -3
  195. package/examples/premium_forward/premium_forward.hsx +0 -19
  196. package/examples/premium_forward/premium_forward.udl +0 -604
  197. package/examples/reconciled_payout/README.md +0 -3
  198. package/examples/reconciled_payout/reconciled_payout.hsx +0 -13
  199. package/examples/reconciled_payout/reconciled_payout.udl +0 -312
  200. package/examples/rotating_pool/README.md +0 -3
  201. package/examples/rotating_pool/rotating_pool.hsx +0 -18
  202. package/examples/rotating_pool/rotating_pool.udl +0 -4370
  203. package/examples/scheduled/README.md +0 -3
  204. package/examples/scheduled/scheduled.hsx +0 -12
  205. package/examples/scheduled/scheduled.udl +0 -355
  206. package/examples/security_deposit/README.md +0 -3
  207. package/examples/security_deposit/security_deposit.hsx +0 -21
  208. package/examples/security_deposit/security_deposit.udl +0 -320
  209. package/examples/settlement_batch/README.md +0 -3
  210. package/examples/settlement_batch/settlement_batch.hsx +0 -19
  211. package/examples/settlement_batch/settlement_batch.udl +0 -757
  212. package/examples/swap/README.md +0 -3
  213. package/examples/swap/swap.hsx +0 -19
  214. package/examples/swap/swap.udl +0 -892
  215. package/examples/threshold_pool/README.md +0 -3
  216. package/examples/threshold_pool/threshold_pool.hsx +0 -16
  217. package/examples/threshold_pool/threshold_pool.udl +0 -680
  218. package/examples/weighted_distribution/README.md +0 -3
  219. package/examples/weighted_distribution/weighted_distribution.hsx +0 -20
  220. package/examples/weighted_distribution/weighted_distribution.udl +0 -348
  221. package/skills/hsx/SKILL.md +0 -449
  222. package/src/diagnostics.ts +0 -620
  223. package/src/emit.ts +0 -282
  224. package/src/entry-overrides.ts +0 -428
  225. package/src/ir.ts +0 -113
  226. package/src/limits.ts +0 -22
  227. package/src/lsp/server.ts +0 -460
  228. package/src/modules.ts +0 -452
  229. package/src/typecheck.ts +0 -5515
  230. package/std/SEMANTICS.md +0 -44
  231. package/std/money_flows/advance.hsx +0 -235
  232. package/std/money_flows/cancellable_booking.hsx +0 -402
  233. package/std/money_flows/captured_payment.hsx +0 -220
  234. package/std/money_flows/conditional_disbursement.hsx +0 -226
  235. package/std/money_flows/credit_facility.hsx +0 -214
  236. package/std/money_flows/held_payment.hsx +0 -812
  237. package/std/money_flows/index.hsx +0 -4
  238. package/std/money_flows/instant_transfer.hsx +0 -231
  239. package/std/money_flows/metered.hsx +0 -104
  240. package/std/money_flows/pooled_split.hsx +0 -109
  241. package/std/money_flows/premium_forward.hsx +0 -307
  242. package/std/money_flows/reconciled_payout.hsx +0 -119
  243. package/std/money_flows/rotating_pool.hsx +0 -305
  244. package/std/money_flows/scheduled.hsx +0 -599
  245. package/std/money_flows/security_deposit.hsx +0 -248
  246. package/std/money_flows/settlement_batch.hsx +0 -173
  247. package/std/money_flows/swap.hsx +0 -1192
  248. package/std/money_flows/threshold_pool.hsx +0 -307
  249. package/std/money_flows/weighted_distribution.hsx +0 -237
package/src/parse.ts CHANGED
@@ -1,1277 +1,471 @@
1
- import { udlClauseVocabulary } from "@hyperscale0/udl";
2
-
3
- const compoundClauseHeads = new Set(
4
- udlClauseVocabulary
5
- .filter((clause) => clause.spelling.includes(" "))
6
- .map((clause) => clause.spelling.split(" ")[0]),
7
- );
8
-
9
- /**
10
- * The HSX parser. Recursive descent over the lexer's token stream, total:
11
- * it always returns a best-effort `Program` plus diagnostics, recovering at
12
- * the next top-level keyword after an error so one mistake never hides the
13
- * rest of the file. Diagnostics speak the author's language and point at
14
- * source spans.
15
- */
16
-
1
+ import { lex, type Token } from "./lex.ts";
17
2
  import type {
18
- ApplyExpr,
19
- AssetDecl,
20
3
  BlockExpr,
21
- ConstDecl,
22
- Decl,
23
4
  Diagnostic,
24
5
  Entry,
25
6
  Expr,
26
- ExposeDecl,
27
- IdentExpr,
28
- ImportDecl,
29
- InstrumentApplyDecl,
30
- InstrumentDecl,
31
- ModuleDecl,
32
- Parameter,
33
- PartyDecl,
34
- PortDecl,
35
7
  Program,
36
- ProgramDecl,
37
8
  Span,
38
- StringExpr,
39
- SubjectDecl,
40
- TypeDecl,
41
- TypeParameter,
42
- UseDecl,
43
9
  } from "./ast.ts";
44
- import { lex, type Token } from "./lex.ts";
45
- import { HSX_LIMITS } from "./limits.ts";
46
10
 
47
- export interface ParseResult {
48
- readonly diagnostics: readonly Diagnostic[];
49
- readonly program: Program;
11
+ class ParseFailure extends Error {
12
+ constructor(readonly diagnostic: Diagnostic) {
13
+ super(diagnostic.message);
14
+ }
50
15
  }
51
-
52
- type BlockContext = "general" | "lifecycle";
53
-
54
- export function parseProgram(source: string): ParseResult {
55
- // Measured before lexing. The ceiling counts UTF-8 bytes, so the encode is
56
- // the measurement rather than an extra step: `source.length` counts UTF-16
57
- // code units, which is a third of the size for CJK text.
58
- const sourceBytes = new TextEncoder().encode(source).byteLength;
59
- if (sourceBytes > HSX_LIMITS.maxSourceBytes) {
16
+ export function parseProgram(source: string): {
17
+ program: Program;
18
+ diagnostics: Diagnostic[];
19
+ } {
20
+ const empty: Program = {
21
+ name: "",
22
+ title: "",
23
+ currency: "SAR",
24
+ header: false,
25
+ decls: [],
26
+ span: { start: 0, end: source.length },
27
+ };
28
+ if (new TextEncoder().encode(source).length > 262144)
60
29
  return {
30
+ program: empty,
61
31
  diagnostics: [
62
32
  {
63
- message: `this file is ${sourceBytes} bytes; HSX reads at most ${HSX_LIMITS.maxSourceBytes}`,
64
- span: { end: 0, start: 0 },
33
+ code: "HSX1004",
34
+ message: "source exceeds 256 KiB",
35
+ fix: "split the program into headers",
36
+ span: empty.span,
65
37
  },
66
38
  ],
67
- program: { decls: [], span: { end: 0, start: 0 } },
68
39
  };
69
- }
70
-
71
- const first = source.search(/\S/);
72
- if (first >= 0 && source[first] === "{") {
40
+ const result = lex(source);
41
+ if (result.diagnostics.length)
42
+ return { program: empty, diagnostics: result.diagnostics };
43
+ try {
73
44
  return {
74
- diagnostics: [
75
- {
76
- code: "HSX1014",
77
- fix: "replace the JSON object with HSX declarations",
78
- message: "JSON is not HSX",
79
- span: { end: first + 1, start: first },
80
- },
81
- ],
82
- program: { decls: [], span: { end: source.length, start: 0 } },
45
+ program: new Parser(result.tokens).program(empty),
46
+ diagnostics: [],
83
47
  };
48
+ } catch (error) {
49
+ if (error instanceof ParseFailure)
50
+ return { program: empty, diagnostics: [error.diagnostic] };
51
+ throw error;
84
52
  }
85
-
86
- const lexed = lex(source);
87
- const parser = new Parser(lexed.tokens, [...lexed.diagnostics]);
88
- const program = parser.parseProgram(source.length);
89
- return { diagnostics: parser.diagnostics, program };
90
53
  }
91
-
92
54
  class Parser {
93
- readonly diagnostics: Diagnostic[];
94
- private readonly tokens: readonly Token[];
95
55
  private index = 0;
96
56
  private depth = 0;
97
-
98
- constructor(tokens: readonly Token[], diagnostics: Diagnostic[]) {
99
- this.tokens = tokens;
100
- this.diagnostics = diagnostics;
101
- }
102
-
103
- parseProgram(sourceLength: number): Program {
104
- const decls: Decl[] = [];
105
- while (!this.at("eof")) {
106
- if (this.atPunct(";")) {
107
- this.advance();
108
- continue;
109
- }
110
- const decl = this.parseDecl();
111
- if (decl) {
112
- decls.push(decl);
113
- continue;
114
- }
115
- this.recoverToDecl();
116
- }
117
- return { decls, span: { end: sourceLength, start: 0 } };
57
+ constructor(private readonly tokens: Token[]) {}
58
+ private peek(): Token {
59
+ return this.tokens[this.index]!;
118
60
  }
119
-
120
- // --- Declarations --------------------------------------------------------
121
-
122
- private parseDecl(exported = false): Decl | undefined {
61
+ private take(): Token {
123
62
  const token = this.peek();
124
- if (token.kind !== "keyword" || token.text === "from") {
125
- this.error(
126
- token.span,
127
- token.kind === "eof"
128
- ? "the program ends unexpectedly"
129
- : `expected a declaration (module, program, use, expose, import, party, asset, subject, instrument, settlement, type, const, or port), found "${token.text}"`,
130
- );
131
- return undefined;
132
- }
133
- switch (token.text) {
134
- case "export":
135
- this.advance();
136
- return this.parseDecl(true);
137
- case "module":
138
- return this.parseModuleDecl(exported);
139
- case "program":
140
- return this.parseProgramDecl();
141
- case "use":
142
- return this.parseUseDecl();
143
- case "expose":
144
- return this.parseExposeDecl();
145
- case "import":
146
- return this.parseImportDecl();
147
- case "party":
148
- return this.parsePartyDecl();
149
- case "asset":
150
- return this.parseAssetDecl();
151
- case "subject":
152
- return this.parseSubjectDecl(exported);
153
- case "instrument":
154
- return this.parseInstrumentDecl(exported);
155
- case "settlement":
156
- return this.parseSettlementDecl();
157
- case "port":
158
- return this.parsePortDecl();
159
- case "type":
160
- return this.parseTypeDecl(exported);
161
- case "const":
162
- return this.parseConstDecl(exported);
163
- default:
164
- this.error(token.span, `"${token.text}" cannot start a declaration`);
165
- this.advance();
166
- return undefined;
167
- }
168
- }
169
-
170
- private parseModuleDecl(exported: boolean): ModuleDecl | undefined {
171
- const start = this.advance();
172
- if (exported) {
173
- this.error(start.span, "a module declaration cannot be exported");
174
- }
175
- const name = this.parsePath("the module needs a dotted name");
176
- return name
177
- ? { kind: "module", name, span: this.spanFrom(start.span) }
178
- : undefined;
179
- }
180
-
181
- private parseInstrumentDecl(
182
- exported: boolean,
183
- ): InstrumentDecl | InstrumentApplyDecl | undefined {
184
- const start = this.advance();
185
- const name = this.expectIdent("the instrument needs a snake_case name");
186
- if (!name) return undefined;
187
- const typeParameters = this.parseTypeParameters();
188
- if (!typeParameters) return undefined;
189
- const hasParameterList = this.atPunct("(");
190
- const parameters = hasParameterList ? this.parseParameters() : [];
191
- if (!parameters) return undefined;
192
- if (this.atPunct("=")) {
193
- this.advance();
194
- const application = this.parseApplication();
195
- if (!application) return undefined;
196
- const metadata = this.atPunct("{") ? this.parseBlock() : undefined;
197
- return {
198
- application,
199
- exported,
200
- kind: "instrument_apply",
201
- ...(metadata ? { metadata } : {}),
202
- name,
203
- span: this.spanFrom(start.span),
204
- };
205
- }
206
- if (!this.atPunct("{")) {
207
- this.error(
208
- this.peek().span,
209
- `instrument ${name.name} needs a body or an exported instrument application`,
210
- );
211
- return undefined;
212
- }
213
- const body = this.parseBlock();
214
- if (!body) return undefined;
215
- return {
216
- body,
217
- exported,
218
- hasParameterList,
219
- kind: "instrument",
220
- name,
221
- parameters,
222
- span: this.spanFrom(start.span),
223
- typeParameters,
224
- };
225
- }
226
-
227
- private parseTypeDecl(exported: boolean): TypeDecl | undefined {
228
- const start = this.advance();
229
- const name = this.expectIdent("the type needs a name");
230
- if (!name) return undefined;
231
- if (
232
- !this.expectPunct("=", `type ${name.name} needs = before its definition`)
233
- ) {
234
- return undefined;
235
- }
236
- const value = this.parseExpr();
237
- return value
238
- ? { exported, kind: "type", name, span: this.spanFrom(start.span), value }
239
- : undefined;
240
- }
241
-
242
- private parseConstDecl(exported: boolean): ConstDecl | undefined {
243
- const start = this.advance();
244
- const name = this.expectIdent("the constant needs a name");
245
- if (!name) return undefined;
246
- let type: Expr | undefined;
247
- if (this.atPunct(":")) {
248
- this.advance();
249
- type = this.parseExpr();
250
- if (!type) return undefined;
251
- }
252
- if (!this.expectPunct("=", `const ${name.name} needs = before its value`)) {
253
- return undefined;
254
- }
255
- const value = this.parseExpr();
256
- return value
257
- ? {
258
- exported,
259
- kind: "const",
260
- name,
261
- span: this.spanFrom(start.span),
262
- ...(type ? { type } : {}),
263
- value,
264
- }
265
- : undefined;
266
- }
267
-
268
- private parseTypeParameters(): TypeParameter[] | undefined {
269
- if (!this.atPunct("<")) return [];
270
- this.advance();
271
- const parameters: TypeParameter[] = [];
272
- while (!this.atPunct(">") && !this.at("eof")) {
273
- const name = this.expectIdent("expected a type parameter");
274
- if (!name) return undefined;
275
- parameters.push({ name, span: name.span });
276
- if (this.atPunct(",")) this.advance();
277
- }
278
- return this.expectPunct(">", "the type parameter list never closes")
279
- ? parameters
280
- : undefined;
281
- }
282
-
283
- private parseParameters(): Parameter[] | undefined {
284
- this.advance();
285
- const parameters: Parameter[] = [];
286
- while (!this.atPunct(")") && !this.at("eof")) {
287
- const name = this.expectIdent("expected a parameter name");
288
- if (!name) return undefined;
289
- if (!this.expectPunct(":", `parameter ${name.name} needs a type`)) {
290
- return undefined;
291
- }
292
- const type = this.parseExpr();
293
- if (!type) return undefined;
294
- parameters.push({
295
- name,
296
- span: { start: name.span.start, end: type.span.end },
297
- type,
298
- });
299
- if (this.atPunct(",")) this.advance();
300
- }
301
- return this.expectPunct(")", "the parameter list never closes")
302
- ? parameters
303
- : undefined;
304
- }
305
-
306
- private parseProgramDecl(): ProgramDecl | undefined {
307
- const start = this.advance();
308
- const name = this.expectIdent("the program needs a snake_case name");
309
- if (!name) return undefined;
310
- let title: StringExpr | undefined;
311
- if (this.at("string")) {
312
- const token = this.advance();
313
- title = { kind: "string", span: token.span, value: token.value };
314
- }
315
- return {
316
- kind: "program",
317
- name,
318
- span: this.spanFrom(start.span),
319
- ...(title ? { title } : {}),
320
- };
321
- }
322
-
323
- private parseUseDecl(): UseDecl | undefined {
324
- const start = this.advance();
325
- const instrument = this.expectIdent(
326
- "use needs a published instrument id, like: use held_settlement",
327
- );
328
- return instrument
329
- ? { instrument, kind: "use", span: this.spanFrom(start.span) }
330
- : undefined;
331
- }
332
-
333
- private parseExposeDecl(): ExposeDecl | undefined {
334
- const start = this.advance();
335
- const instrument = this.expectIdent(
336
- "expose needs an instrument action, like: expose held_settlement.release as releaseFunds",
337
- );
338
- if (!instrument) return undefined;
339
- if (
340
- !this.expectPunct(
341
- ".",
342
- "expose separates the instrument and action with .",
343
- )
344
- ) {
345
- return undefined;
346
- }
347
- const action = this.expectName(
348
- "expose needs an action after the instrument id",
349
- );
350
- if (!action) return undefined;
351
- if (!this.at("keyword") || this.peek().text !== "as") {
352
- this.error(
353
- this.peek().span,
354
- "expose needs as before its public action name",
355
- );
356
- return undefined;
357
- }
358
- this.advance();
359
- const publicName = this.expectIdent(
360
- "expose needs a camelCase public action name",
361
- );
362
- return publicName
363
- ? {
364
- action,
365
- instrument,
366
- kind: "expose",
367
- publicName,
368
- span: this.spanFrom(start.span),
369
- }
370
- : undefined;
371
- }
372
-
373
- private parseImportDecl(): ImportDecl | undefined {
374
- const start = this.advance();
375
- if (
376
- !this.expectPunct(
377
- "{",
378
- 'import lists its names in braces: import { held_payment } from "std/money_flows"',
379
- )
380
- ) {
381
- return undefined;
382
- }
383
- const names: IdentExpr[] = [];
384
- while (!this.atPunct("}") && !this.at("eof")) {
385
- const name = this.expectIdent("expected an imported name");
386
- if (!name) return undefined;
387
- names.push(name);
388
- if (this.atPunct(",")) this.advance();
389
- }
390
- if (!this.expectPunct("}", "the import name list never closes")) {
391
- return undefined;
392
- }
393
- if (!this.at("keyword") || this.peek().text !== "from") {
394
- this.error(
395
- this.peek().span,
396
- 'import needs from: import { held_payment } from "std/money_flows"',
397
- );
398
- return undefined;
399
- }
400
- this.advance();
401
- if (!this.at("string")) {
402
- this.error(
403
- this.peek().span,
404
- 'the import source must be a quoted module name like "std/money_flows"',
405
- );
406
- return undefined;
407
- }
408
- const sourceToken = this.advance();
409
- if (names.length === 0) {
410
- this.error(start.span, "import brings in at least one name");
411
- }
412
- return {
413
- from: {
414
- kind: "string",
415
- span: sourceToken.span,
416
- value: sourceToken.value,
417
- },
418
- kind: "import",
419
- names,
420
- span: this.spanFrom(start.span),
421
- };
422
- }
423
-
424
- private parsePartyDecl(): PartyDecl | undefined {
425
- const start = this.advance();
426
- const name = this.expectIdent(
427
- "the party needs a name, like: party buyer: person",
428
- );
429
- if (!name) return undefined;
430
- if (
431
- !this.expectPunct(
432
- ":",
433
- `party ${name.name} needs a kind, like: party ${name.name}: person`,
434
- )
435
- ) {
436
- return undefined;
437
- }
438
- const partyKind = this.expectIdent(
439
- `expected a kind for party ${name.name}`,
440
- );
441
- if (!partyKind) return undefined;
442
- const attrs = this.atPunct("{") ? this.parseBlock() : undefined;
443
- return {
444
- ...(attrs ? { attrs } : {}),
445
- kind: "party",
446
- name,
447
- partyKind,
448
- span: this.spanFrom(start.span),
449
- };
450
- }
451
-
452
- private parseAssetDecl(): AssetDecl | undefined {
453
- const start = this.advance();
454
- const name = this.expectIdent(
455
- "the asset needs a name, like: asset vehicle: good",
456
- );
457
- if (!name) return undefined;
458
- if (
459
- !this.expectPunct(
460
- ":",
461
- `asset ${name.name} needs a kind, like: asset ${name.name}: good`,
462
- )
463
- ) {
464
- return undefined;
465
- }
466
- const assetKind = this.expectIdent(
467
- `expected a kind for asset ${name.name}`,
468
- );
469
- if (!assetKind) return undefined;
470
- const attrs = this.atPunct("{") ? this.parseBlock() : undefined;
471
- return {
472
- assetKind,
473
- ...(attrs ? { attrs } : {}),
474
- kind: "asset",
475
- name,
476
- span: this.spanFrom(start.span),
477
- };
478
- }
479
-
480
- private parseSubjectDecl(exported: boolean): SubjectDecl | undefined {
481
- const start = this.advance();
482
- if (exported) {
483
- this.error(start.span, "a subject declaration cannot be exported");
484
- }
485
- const name = this.expectIdent("the subject needs a snake_case kind name");
486
- if (!name) return undefined;
487
- if (!this.atPunct("{")) {
488
- this.error(this.peek().span, `subject ${name.name} needs a body`);
489
- return undefined;
490
- }
491
- const body = this.parseBlock();
492
- return body
493
- ? { body, kind: "subject", name, span: this.spanFrom(start.span) }
494
- : undefined;
495
- }
496
-
497
- private parseSettlementDecl(): InstrumentApplyDecl | undefined {
498
- const start = this.advance();
499
- const name = this.expectIdent(
500
- "the settlement needs a name, like: settlement sale = held_payment { ... }",
501
- );
502
- if (!name) return undefined;
503
- if (
504
- !this.expectPunct(
505
- "=",
506
- `settlement ${name.name} instantiates a module: settlement ${name.name} = held_payment { ... }`,
507
- )
508
- ) {
509
- return undefined;
510
- }
511
- const moduleName = this.expectIdent(
512
- `expected a module name for settlement ${name.name}`,
513
- );
514
- if (!moduleName) return undefined;
515
- if (!this.atPunct("{")) {
516
- this.error(
517
- this.peek().span,
518
- `settlement ${name.name} needs a body in braces`,
519
- );
520
- return undefined;
521
- }
522
- const body = this.parseBlock();
523
- if (!body) return undefined;
524
- return {
525
- application: {
526
- args: body.entries.map((row) => ({
527
- kind: "binding" as const,
528
- name: row.key,
529
- span: row.value.span,
530
- type: row.value,
531
- })),
532
- callee: { kind: "path", parts: [moduleName], span: moduleName.span },
533
- kind: "apply",
534
- span: { start: moduleName.span.start, end: body.span.end },
535
- typeArgs: [],
536
- },
537
- exported: false,
538
- kind: "instrument_apply",
539
- name,
540
- span: this.spanFrom(start.span),
541
- };
63
+ if (token.kind !== "eof") this.index++;
64
+ return token;
542
65
  }
543
-
544
- private parsePortDecl(): PortDecl | undefined {
545
- const start = this.advance();
546
- const name = this.expectIdent(
547
- "the port needs a name, like: port confirm_handover { ... }",
548
- );
549
- if (!name) return undefined;
550
- if (!this.atPunct("{")) {
551
- this.error(this.peek().span, `port ${name.name} needs a body in braces`);
552
- return undefined;
553
- }
554
- const body = this.parseBlock();
555
- if (!body) return undefined;
556
- return { body, kind: "port", name, span: this.spanFrom(start.span) };
66
+ private at(text: string): boolean {
67
+ return this.peek().text === text;
557
68
  }
558
-
559
- // --- Entries and expressions ---------------------------------------------
560
-
561
- /**
562
- * Every recursive edge in the grammar passes through `parseExpr` or
563
- * `parseBlock`: the list, block, call-argument, and binding-type branches of
564
- * one, and the block to entry to block cycle of the other. Guarding those
565
- * two entry points is therefore the whole ceiling, and the guard lives in
566
- * one place instead of five.
567
- *
568
- * The budget counts those entries, not source levels, and the two are not
569
- * the same number: `k { ... }` spends one per level, while `k: { ... }`
570
- * spends two because the colon branch enters `parseExpr` and `parseExpr`
571
- * then enters `parseBlock`. So the message names a budget rather than a
572
- * depth. A builder told they exceeded "64 levels" would count 32 braces and
573
- * have nothing to act on.
574
- */
575
- private enterNesting(span: Span): boolean {
576
- if (this.depth >= HSX_LIMITS.maxNestingDepth) {
577
- this.error(
578
- span,
579
- `this nests past the parser's depth budget of ${HSX_LIMITS.maxNestingDepth}; flatten it`,
580
- );
581
- return false;
582
- }
583
- this.depth += 1;
69
+ private eat(text: string): boolean {
70
+ if (!this.at(text)) return false;
71
+ this.take();
584
72
  return true;
585
73
  }
586
-
587
- private parseBlock(context: BlockContext = "general"): BlockExpr | undefined {
588
- if (!this.enterNesting(this.peek().span)) return undefined;
589
- const block = this.parseBlockUnguarded(context);
590
- this.depth -= 1;
591
- return block;
74
+ private fail(message: string, fix: string): never {
75
+ throw new ParseFailure({
76
+ code: "HSX1000",
77
+ message,
78
+ fix,
79
+ span: this.peek().span,
80
+ });
81
+ }
82
+ private expect(text: string): void {
83
+ if (!this.eat(text))
84
+ this.fail(
85
+ `expected ${text}, found ${this.peek().text || "end of file"}`,
86
+ `write ${text} here`,
87
+ );
592
88
  }
593
-
594
- private parseBlockUnguarded(context: BlockContext): BlockExpr | undefined {
595
- const open = this.advance();
596
- const entries: Entry[] = [];
597
- while (!this.atPunct("}") && !this.at("eof")) {
598
- if (this.atPunct(";") || this.atPunct(",")) {
599
- this.advance();
89
+ private identifier(): string {
90
+ if (this.peek().kind !== "name")
91
+ this.fail("expected a name", "write a name starting with a letter");
92
+ return this.take().text;
93
+ }
94
+ private path(): string {
95
+ let name = this.identifier();
96
+ while (this.eat(".")) name += "." + this.identifier();
97
+ return name;
98
+ }
99
+ private separators(): void {
100
+ while (this.eat(",") || this.eat(";")) {}
101
+ }
102
+ private span(start: number): Span {
103
+ return { start, end: this.tokens[Math.max(0, this.index - 1)]!.span.end };
104
+ }
105
+ program(program: Program): Program {
106
+ if (this.eat("header")) program.header = true;
107
+ else this.expect("program");
108
+ program.name = this.identifier();
109
+ if (!program.header) {
110
+ if (this.peek().kind !== "string")
111
+ this.fail(
112
+ "program needs a title",
113
+ "write a quoted title after its name",
114
+ );
115
+ program.title = JSON.parse(this.take().text) as string;
116
+ }
117
+ while (this.peek().kind !== "eof") {
118
+ this.separators();
119
+ if (this.peek().kind === "eof") break;
120
+ const start = this.peek().span.start;
121
+ if (this.eat("currency")) {
122
+ program.currency = this.identifier();
600
123
  continue;
601
124
  }
602
- const before = this.index;
603
- const entry = this.parseEntry(context);
604
- if (!entry) {
605
- this.recoverInBlock();
606
- // recoverInBlock bails without consuming when it lands on a depth-0
607
- // keyword (e.g. `from` used as an entry key), and a failed
608
- // parseEntry may not have consumed either. Without forced progress
609
- // this loop never terminates.
610
- if (this.index === before) this.advance();
125
+ if (this.eat("use")) {
126
+ program.decls.push({
127
+ kind: "use",
128
+ name: this.identifier(),
129
+ span: this.span(start),
130
+ });
611
131
  continue;
612
132
  }
613
- entries.push(entry);
614
- if (this.atPunct(",") || this.atPunct(";")) this.advance();
615
- }
616
- if (!this.expectPunct("}", "this block never closes; add the matching }")) {
617
- return { entries, kind: "block", span: this.spanFrom(open.span) };
618
- }
619
- return { entries, kind: "block", span: this.spanFrom(open.span) };
620
- }
621
-
622
- private parseEntry(context: BlockContext): Entry | undefined {
623
- const token = this.peek();
624
- const key =
625
- token.kind === "string"
626
- ? (() => {
627
- this.advance();
628
- return {
629
- kind: "ident" as const,
630
- name: token.value,
631
- quoted: !token.value.includes("["),
632
- span: token.span,
633
- };
634
- })()
635
- : this.isName(token) && (token.text === "action" || token.text === "on")
636
- ? this.parseIdent()
637
- : this.parseTemplatedName("expected an entry name here");
638
- if (!key) return undefined;
639
-
640
- const qualifiers: IdentExpr[] = [];
641
- if (key.name === "for") {
642
- const binding = this.expectIdent("for needs a compile-time binding name");
643
- const inWord = binding
644
- ? this.expectName("for needs in before its finite bound")
645
- : undefined;
646
- if (!binding || inWord?.name !== "in") {
647
- this.error(
648
- this.peek().span,
649
- "write `for item in <finite bound> { ... }`",
650
- );
651
- return undefined;
133
+ if (this.eat("party")) {
134
+ const name = this.identifier();
135
+ this.expect(":");
136
+ const partyKind = this.identifier();
137
+ const role = this.eat("role") ? this.identifier() : undefined;
138
+ program.decls.push({
139
+ kind: "party",
140
+ name,
141
+ partyKind,
142
+ ...(role ? { role } : {}),
143
+ span: this.span(start),
144
+ });
145
+ continue;
652
146
  }
653
- const bound = this.parseExpr();
654
- if (!bound || !this.atPunct("{")) {
655
- this.error(
656
- this.peek().span,
657
- "a bounded comprehension needs a body in braces",
147
+ if (this.at("expose") || this.at("hide")) {
148
+ const kind = this.take().text as "expose" | "hide";
149
+ const target = this.path();
150
+ let name: string | undefined;
151
+ if (kind === "expose") {
152
+ this.expect("as");
153
+ name = this.identifier();
154
+ }
155
+ program.decls.push(
156
+ kind === "expose"
157
+ ? { kind, target, name: name!, span: this.span(start) }
158
+ : { kind, target, span: this.span(start) },
658
159
  );
659
- return undefined;
160
+ continue;
660
161
  }
661
- const value = this.parseBlock(context);
662
- return value
663
- ? {
664
- iteration: { binding, bound },
665
- key,
666
- qualifiers,
667
- span: { start: key.span.start, end: value.span.end },
668
- value,
669
- }
670
- : undefined;
671
- }
672
- if (
673
- key.name === "action" &&
674
- (this.isName(this.peek()) || this.atPunct("["))
675
- ) {
676
- const action = this.parseTemplatedName("action needs a name");
677
- if (!action) return undefined;
678
- qualifiers.push(action);
679
- if (!this.atPunct("{")) {
680
- this.error(
681
- this.peek().span,
682
- `action ${qualifiers[0]?.name ?? ""} needs a body`,
683
- );
684
- return undefined;
162
+ if (this.eat("instrument")) {
163
+ const name = this.identifier();
164
+ const parameters = this.eat("(") ? this.entries(")") : [];
165
+ const body = this.block();
166
+ program.decls.push({
167
+ kind: "instrument",
168
+ name,
169
+ parameters,
170
+ body,
171
+ span: this.span(start),
172
+ });
173
+ continue;
685
174
  }
686
- const value = this.parseBlock();
687
- return value
688
- ? {
689
- key,
690
- qualifiers,
691
- span: { start: key.span.start, end: value.span.end },
692
- value,
693
- }
694
- : undefined;
175
+ const name = this.identifier();
176
+ this.expect("=");
177
+ const object = this.path();
178
+ const body = this.block();
179
+ program.decls.push({
180
+ kind: "object",
181
+ name,
182
+ object,
183
+ body,
184
+ span: this.span(start),
185
+ });
695
186
  }
696
- if (context === "lifecycle" && key.name === "states") {
697
- const items: Expr[] = [];
698
- while (!this.atPunct(";") && !this.atPunct("}") && !this.at("eof")) {
699
- const state = this.parseTemplatedName("expected a lifecycle state");
700
- if (!state) return undefined;
701
- items.push(state);
187
+ return program;
188
+ }
189
+ private entries(end: string): Entry[] {
190
+ const entries: Entry[] = [];
191
+ while (!this.eat(end)) {
192
+ this.separators();
193
+ if (this.eat(end)) break;
194
+ if (this.peek().kind === "eof")
195
+ this.fail(`unclosed block, expected ${end}`, `add ${end}`);
196
+ const start = this.peek().span.start;
197
+ let key = this.path();
198
+ if (key === "action" && !this.at(":")) key += " " + this.identifier();
199
+ if (key === "when") {
200
+ const tunable = this.identifier();
201
+ this.expect("is");
202
+ const choice = this.identifier();
203
+ entries.push({
204
+ key: `when ${tunable} is ${choice}`,
205
+ value: this.block(),
206
+ span: this.span(start),
207
+ });
208
+ continue;
702
209
  }
703
- const end = items.at(-1)?.span.end ?? key.span.end;
704
- return {
210
+ const clause = ["requires", "invariants", "moves"].includes(key);
211
+ const value =
212
+ clause && !this.at(":") && !this.at("{")
213
+ ? {
214
+ kind: "list" as const,
215
+ items: [key === "moves" ? this.move() : this.requirement()],
216
+ span: this.span(start),
217
+ }
218
+ : this.at("{")
219
+ ? this.block()
220
+ : (this.expect(":"), this.expression());
221
+ entries.push({ key, value, span: this.span(start) });
222
+ this.separators();
223
+ }
224
+ return entries;
225
+ }
226
+ private node(value: string): Expr {
227
+ return { kind: "text", value, span: this.peek().span };
228
+ }
229
+ private record(values: Record<string, Expr>): BlockExpr {
230
+ const span = this.peek().span;
231
+ return {
232
+ kind: "block",
233
+ entries: Object.entries(values).map(([key, value]) => ({
705
234
  key,
706
- qualifiers,
707
- span: { start: key.span.start, end },
708
- value: { items, kind: "list", span: { start: key.span.end, end } },
235
+ value,
236
+ span: value.span,
237
+ })),
238
+ span,
239
+ };
240
+ }
241
+ private operand(): BlockExpr {
242
+ const value = this.atom();
243
+ return this.record({
244
+ [value.kind === "name" && /^(self|input|party)\./.test(value.value)
245
+ ? "field"
246
+ : "literal"]: value,
247
+ });
248
+ }
249
+ private operator(): Expr {
250
+ const operator = this.take();
251
+ if (!["==", "!=", "<", "<=", ">", ">="].includes(operator.text))
252
+ this.fail("expected a comparison", "write ==, !=, <, <=, >, or >=");
253
+ return this.node(operator.text);
254
+ }
255
+ private requirement(): BlockExpr {
256
+ if (this.eat("approval")) {
257
+ this.expect("by");
258
+ const party = this.atom();
259
+ const values: Record<string, Expr> = {
260
+ kind: this.node("approval"),
261
+ party,
262
+ decision: this.node("approved"),
709
263
  };
264
+ if (this.eat("for")) values.action = this.atom();
265
+ if (this.eat("is")) values.decision = this.atom();
266
+ return this.record(values);
267
+ }
268
+ if (this.eat("unique")) {
269
+ const namespace = this.atom();
270
+ this.expect("on");
271
+ return this.record({
272
+ kind: this.node("unique"),
273
+ namespace,
274
+ fields: this.atom(),
275
+ });
710
276
  }
711
- if (context === "lifecycle" && key.name === "initial") {
712
- const value = this.parseTemplatedName(
713
- "initial needs one declared lifecycle state",
714
- );
715
- return value
716
- ? {
717
- key,
718
- qualifiers,
719
- span: { start: key.span.start, end: value.span.end },
720
- value,
721
- }
722
- : undefined;
723
- }
724
- if (context === "lifecycle" && key.name === "parked") {
725
- const state = this.parseTemplatedName("parked needs a lifecycle state");
726
- if (!state) return undefined;
727
- qualifiers.push(state);
728
- const reasonWord = this.expectName('parked needs reason "..."');
729
- if (!reasonWord || reasonWord.name !== "reason" || !this.at("string")) {
730
- this.error(this.peek().span, 'parked needs reason "..."');
731
- return undefined;
732
- }
733
- const token = this.advance();
734
- const value: StringExpr = {
735
- kind: "string",
736
- span: token.span,
737
- value: token.value,
738
- };
739
- return {
740
- key,
741
- qualifiers,
742
- span: { start: key.span.start, end: value.span.end },
277
+ if (this.at("count") || this.at("sum")) {
278
+ const measure = this.eat("count")
279
+ ? this.node("count")
280
+ : (this.expect("sum"), this.record({ sum: this.atom() }));
281
+ this.expect("of");
282
+ const selection = this.block();
283
+ const operator = this.operator();
284
+ const value = this.operand();
285
+ return this.record({
286
+ kind: this.node("aggregate"),
287
+ selection,
288
+ measure,
289
+ operator,
743
290
  value,
744
- };
291
+ });
745
292
  }
746
- if (context === "lifecycle" && key.name === "on") {
747
- const action = this.parseTemplatedName("on needs an action name");
748
- if (!action) return undefined;
749
- qualifiers.push(action);
750
- if (
751
- !this.expectPunct(
752
- ":",
753
- `on ${action.name} needs : before its source states`,
754
- )
755
- ) {
756
- return undefined;
757
- }
758
- while (!this.atPunct("->") && !this.at("eof")) {
759
- const state = this.parseTemplatedName(
760
- "expected a source lifecycle state",
761
- );
762
- if (!state) return undefined;
763
- qualifiers.push(state);
764
- if (this.atPunct("|")) this.advance();
765
- }
766
- if (
767
- !this.expectPunct(
768
- "->",
769
- `on ${action.name} needs -> before its target state`,
770
- )
771
- ) {
772
- return undefined;
773
- }
774
- const value = this.parseTemplatedName(
775
- "expected a target lifecycle state",
776
- );
777
- return value
778
- ? {
779
- key,
780
- qualifiers,
781
- span: { start: key.span.start, end: value.span.end },
782
- value,
783
- }
784
- : undefined;
293
+ if (this.eat("hours")) {
294
+ const at = this.atom();
295
+ this.expect("between");
296
+ const start = this.atom();
297
+ this.expect("and");
298
+ const end = this.atom();
299
+ this.expect("timezone");
300
+ return this.record({
301
+ kind: this.node("hours"),
302
+ at,
303
+ start,
304
+ end,
305
+ timezone: this.atom(),
306
+ });
785
307
  }
786
- if (key.name === "notify") {
787
- const role = this.expectName("notify needs a declared role");
788
- const via = role
789
- ? this.expectName("notify needs via before its channel")
790
- : undefined;
791
- const channel = via
792
- ? this.expectName("notify needs a channel")
793
- : undefined;
794
- if (!role || via?.name !== "via" || !channel) return undefined;
795
- qualifiers.push(role, channel);
796
- return {
797
- key,
798
- qualifiers,
799
- span: { start: key.span.start, end: channel.span.end },
800
- value: { kind: "boolean", span: channel.span, value: true },
308
+ if (this.eat("evidence")) {
309
+ const subject = this.atom();
310
+ const values: Record<string, Expr> = {
311
+ kind: this.node("evidence"),
312
+ subject,
801
313
  };
802
- }
803
- if (this.atPunct("(")) {
804
- this.advance();
805
- while (!this.atPunct(")") && !this.at("eof")) {
806
- const qualifier = this.at("number")
807
- ? this.parseIdent()
808
- : this.expectIdent(`expected a qualifier inside ${key.name}( ... )`);
809
- if (!qualifier) return undefined;
810
- qualifiers.push(qualifier);
811
- if (this.atPunct(",")) this.advance();
314
+ for (const key of ["family", "check", "result", "maxAge"]) {
315
+ this.expect(key);
316
+ values[key] = this.atom();
812
317
  }
813
- if (!this.expectPunct(")", `${key.name}( ... ) never closes`)) {
814
- return undefined;
815
- }
816
- }
817
-
818
- if (compoundClauseHeads.has(key.name) && this.isName(this.peek())) {
819
- while (this.isName(this.peek())) qualifiers.push(this.parseIdent());
318
+ return this.record(values);
319
+ }
320
+ const left = this.operand();
321
+ if (this.eat("in")) {
322
+ const reference = left.entries.find(
323
+ (entry) => entry.key === "field",
324
+ )?.value;
325
+ if (!reference)
326
+ this.fail(
327
+ "state requirement needs a reference",
328
+ "write requires self.record in [state]",
329
+ );
330
+ return this.record({
331
+ kind: this.node("state"),
332
+ reference,
333
+ states: this.atom(),
334
+ });
820
335
  }
821
-
822
- let value: Expr | undefined;
823
- if (this.atPunct("{")) {
824
- value = this.parseBlock(
825
- key.name === "lifecycle" || context === "lifecycle"
826
- ? "lifecycle"
827
- : "general",
828
- );
829
- } else if (this.atPunct(":")) {
830
- this.advance();
831
- value = this.atPunct("{")
832
- ? this.parseBlock(
833
- key.name === "lifecycle" || context === "lifecycle"
834
- ? "lifecycle"
835
- : "general",
836
- )
837
- : this.parseExpr();
838
- } else if (this.canStartExpr(this.peek())) {
839
- value = this.parseExpr();
336
+ const operator = this.operator();
337
+ return this.record({
338
+ kind: this.node("compare"),
339
+ left,
340
+ operator,
341
+ right: this.operand(),
342
+ });
343
+ }
344
+ private move(): BlockExpr {
345
+ const values: Record<string, Expr> = {};
346
+ if (this.at("post") || this.at("void")) {
347
+ values.operation = this.node("internal_transfer." + this.take().text);
348
+ values.transfer = this.atom();
840
349
  } else {
841
- this.error(
842
- this.peek().span,
843
- `entry ${key.name} needs a value: either "${key.name}: <value>" or "${key.name} { ... }"`,
844
- );
845
- return undefined;
350
+ if (this.eat("reserve"))
351
+ values.operation = this.node("internal_transfer.reserve");
352
+ values.amount = this.atom();
353
+ this.expect("from");
354
+ values.from = this.atom();
355
+ if (this.eat("to")) values.to = this.atom();
356
+ else {
357
+ this.expect("shares");
358
+ values.shares = this.atom();
359
+ }
846
360
  }
847
- if (!value) return undefined;
848
- return {
849
- key,
850
- qualifiers,
851
- span: { end: value.span.end, start: key.span.start },
852
- value,
853
- };
854
- }
855
-
856
- private parseExpr(): Expr | undefined {
857
- if (!this.enterNesting(this.peek().span)) return undefined;
858
- const expr = this.parseExprUnguarded();
859
- this.depth -= 1;
860
- return expr;
361
+ for (const key of ["fee", "capture", "key"])
362
+ if (this.eat(key)) values[key] = this.atom();
363
+ return this.record(values);
364
+ }
365
+ private block(): BlockExpr {
366
+ const start = this.peek().span.start;
367
+ this.expect("{");
368
+ if (++this.depth > 32)
369
+ this.fail("block nesting exceeds 32", "reduce nested blocks");
370
+ const entries = this.entries("}");
371
+ this.depth--;
372
+ return { kind: "block", entries, span: this.span(start) };
373
+ }
374
+ private expression(): Expr {
375
+ if (++this.depth > 32)
376
+ this.fail("expression nesting exceeds 32", "reduce nested values");
377
+ const start = this.peek().span.start;
378
+ let value = this.atom();
379
+ if (this.eat("cap"))
380
+ value = {
381
+ kind: "capped",
382
+ rate: value,
383
+ cap: this.atom(),
384
+ span: this.span(start),
385
+ };
386
+ if (this.eat("="))
387
+ value = {
388
+ kind: "default",
389
+ type: value,
390
+ value: this.expression(),
391
+ span: this.span(start),
392
+ };
393
+ this.depth--;
394
+ return value;
861
395
  }
862
-
863
- private parseExprUnguarded(): Expr | undefined {
396
+ private atom(): Expr {
864
397
  const token = this.peek();
865
-
866
- if (token.kind === "string") {
867
- this.advance();
868
- return { kind: "string", span: token.span, value: token.value };
869
- }
870
- if (token.kind === "number") {
871
- this.advance();
872
- return { kind: "number", raw: token.value, span: token.span };
873
- }
874
- if (token.kind === "percent") {
875
- this.advance();
876
- const bps = percentToBps(token.value);
877
- if (bps === undefined) {
878
- this.error(
879
- token.span,
880
- `${token.text} is finer than the money system can settle; percents go down to a hundredth (basis point), like 99.75%`,
881
- );
882
- return { bps: 0, kind: "percent", raw: token.value, span: token.span };
883
- }
884
- return { bps, kind: "percent", raw: token.value, span: token.span };
885
- }
886
- if (this.atPunct("[")) {
887
- const open = this.advance();
398
+ const start = token.span.start;
399
+ if (this.at("{")) return this.block();
400
+ if (this.eat("[")) {
888
401
  const items: Expr[] = [];
889
- while (!this.atPunct("]") && !this.at("eof")) {
890
- const item = this.parseExpr();
891
- if (!item) return undefined;
892
- items.push(item);
893
- if (this.atPunct(",")) this.advance();
402
+ while (!this.eat("]")) {
403
+ if (this.peek().kind === "eof") this.fail("unclosed list", "add ]");
404
+ items.push(this.expression());
405
+ this.separators();
894
406
  }
895
- if (
896
- !this.expectPunct("]", "this list never closes; add the matching ]")
897
- ) {
898
- return undefined;
899
- }
900
- return { items, kind: "list", span: this.spanFrom(open.span) };
901
- }
902
- if (this.atPunct("{")) {
903
- return this.parseBlock();
407
+ return { kind: "list", items, span: this.span(start) };
904
408
  }
905
- if (token.kind === "keyword" && token.text === "port") {
906
- const start = this.advance();
907
- const name = this.expectIdent(
908
- "expected a port name after the port keyword",
909
- );
910
- if (!name) return undefined;
911
- let within: IdentExpr | undefined;
912
- if (this.at("ident") && this.peek().text === "within") {
913
- this.advance();
914
- within = this.expectIdent(
915
- "expected a fixed duration after within, like P14D",
916
- );
917
- if (!within) return undefined;
918
- }
919
- let deadline: IdentExpr | undefined;
920
- if (this.atPunct("|")) {
921
- this.advance();
922
- if (!this.at("ident") || this.peek().text !== "at") {
923
- this.error(
924
- this.peek().span,
925
- "after | comes the date the platform decides on, like: | at(releaseDueAt)",
926
- );
927
- return undefined;
928
- }
929
- this.advance();
930
- if (
931
- !this.expectPunct(
932
- "(",
933
- "at names its date field in parentheses: at(releaseDueAt)",
934
- )
935
- ) {
936
- return undefined;
937
- }
938
- deadline = this.expectIdent(
939
- "expected a stored date field inside at( ... ), like at(releaseDueAt)",
940
- );
941
- if (!deadline) return undefined;
942
- if (!this.expectPunct(")", "at( ... ) never closes")) return undefined;
943
- }
944
- return {
945
- ...(deadline ? { deadline } : {}),
946
- kind: "port_ref",
947
- name,
948
- span: this.spanFrom(start.span),
949
- ...(within ? { within } : {}),
950
- };
951
- }
952
- if (token.kind === "keyword") {
953
- return this.parseIdent();
954
- }
955
- if (
956
- token.kind === "ident" &&
957
- /^[A-Z]{3}$/.test(token.text) &&
958
- this.peekAt(1).kind === "number"
959
- ) {
960
- const currency = this.parseIdent();
961
- const amount = this.advance();
962
- return {
963
- currency,
964
- kind: "money",
965
- raw: amount.value,
966
- span: { start: currency.span.start, end: amount.span.end },
967
- };
968
- }
969
- if (token.kind === "ident") {
970
- const ident = this.parseIdent();
971
- if (ident.name === "true" || ident.name === "false") {
972
- return {
973
- kind: "boolean",
974
- span: ident.span,
975
- value: ident.name === "true",
976
- };
977
- }
978
- if (ident.name === "decided" && this.atPunct("{")) {
979
- const body = this.parseBlock();
980
- if (!body) return undefined;
981
- return {
982
- body,
983
- kind: "decided_amount",
984
- span: { end: body.span.end, start: ident.span.start },
985
- };
986
- }
987
- if (this.atPunct(".")) {
988
- this.advance();
989
- const member = this.expectIdent(
990
- `expected the exit after ${ident.name}., like ${ident.name}.release`,
991
- );
992
- if (!member) return undefined;
993
- return {
994
- kind: "settlement_ref",
995
- member,
996
- owner: ident,
997
- span: { end: member.span.end, start: ident.span.start },
998
- };
999
- }
1000
- if (this.atPunct("<")) {
1001
- const args = this.parseAngleArguments();
1002
- if (!args) return undefined;
1003
- return {
1004
- args,
1005
- callee: ident,
1006
- kind: "type_apply",
1007
- span: this.spanFrom(ident.span),
1008
- };
1009
- }
1010
- if (this.atPunct("(")) {
1011
- this.advance();
1012
- const args: Expr[] = [];
1013
- while (!this.atPunct(")") && !this.at("eof")) {
1014
- const arg = this.parseExpr();
1015
- if (!arg) return undefined;
1016
- args.push(arg);
1017
- if (this.atPunct(",")) this.advance();
1018
- }
1019
- if (!this.expectPunct(")", `${ident.name}( ... ) never closes`)) {
1020
- return undefined;
1021
- }
409
+ if (token.kind === "number") {
410
+ this.take();
411
+ if (token.text.endsWith("%"))
1022
412
  return {
1023
- args,
1024
- callee: ident,
1025
- kind: "call",
1026
- span: this.spanFrom(ident.span),
413
+ kind: "percent",
414
+ value: token.text.slice(0, -1),
415
+ span: token.span,
1027
416
  };
1028
- }
1029
- if (this.atPunct(":")) {
1030
- this.advance();
1031
- const type = this.parseExpr();
1032
- if (!type) return undefined;
417
+ if (/[a-z]$/.test(token.text))
418
+ return { kind: "duration", value: token.text, span: token.span };
419
+ if (/^[A-Z]{3}$/.test(this.peek().text)) {
420
+ const currency = this.take().text;
1033
421
  return {
1034
- kind: "binding",
1035
- name: ident,
1036
- span: { end: type.span.end, start: ident.span.start },
1037
- type,
422
+ kind: "money",
423
+ value: token.text + " " + currency,
424
+ span: this.span(start),
1038
425
  };
1039
426
  }
1040
- return ident;
1041
- }
1042
-
1043
- this.error(
1044
- token.span,
1045
- token.kind === "eof"
1046
- ? "the program ends where a value was expected"
1047
- : `"${token.text}" is not a value HSX understands here`,
1048
- );
1049
- return undefined;
1050
- }
1051
-
1052
- // --- Recovery ------------------------------------------------------------
1053
-
1054
- private recoverToDecl(): void {
1055
- while (!this.at("eof")) {
1056
- const token = this.peek();
1057
- if (token.kind === "keyword" && token.text !== "from") return;
1058
- this.advance();
427
+ return { kind: "number", value: token.text, span: token.span };
1059
428
  }
1060
- }
1061
-
1062
- /** Skip to the next plausible entry start or the end of the block. */
1063
- private recoverInBlock(): void {
1064
- let depth = 0;
1065
- while (!this.at("eof")) {
1066
- const token = this.peek();
1067
- if (token.kind === "punct") {
1068
- if (token.text === "{" || token.text === "[" || token.text === "(")
1069
- depth += 1;
1070
- if (token.text === "}" || token.text === "]" || token.text === ")") {
1071
- if (depth === 0) return;
1072
- depth -= 1;
1073
- }
1074
- if (token.text === "," && depth === 0) {
1075
- this.advance();
1076
- return;
1077
- }
1078
- }
1079
- if (token.kind === "keyword" && depth === 0) return;
1080
- this.advance();
429
+ if (token.kind === "string" || token.kind === "date") {
430
+ this.take();
431
+ return {
432
+ kind: token.kind === "string" ? "text" : "date",
433
+ value:
434
+ token.kind === "string"
435
+ ? (JSON.parse(token.text) as string)
436
+ : token.text,
437
+ span: token.span,
438
+ };
1081
439
  }
1082
- }
1083
-
1084
- // --- Token helpers -------------------------------------------------------
1085
-
1086
- private peek(): Token {
1087
- return this.tokens[this.index] as Token;
1088
- }
1089
-
1090
- private peekAt(offset: number): Token {
1091
- return this.tokens[
1092
- Math.min(this.index + offset, this.tokens.length - 1)
1093
- ] as Token;
1094
- }
1095
-
1096
- private previous(): Token {
1097
- return this.tokens[Math.max(0, this.index - 1)] as Token;
1098
- }
1099
-
1100
- private advance(): Token {
1101
- const token = this.peek();
1102
- if (token.kind !== "eof") this.index += 1;
1103
- return token;
1104
- }
1105
-
1106
- private at(kind: Token["kind"]): boolean {
1107
- return this.peek().kind === kind;
1108
- }
1109
-
1110
- private atPunct(glyph: string): boolean {
1111
- const token = this.peek();
1112
- return token.kind === "punct" && token.text === glyph;
1113
- }
1114
-
1115
- private parseIdent(): IdentExpr {
1116
- const token = this.advance();
1117
- return { kind: "ident", name: token.text, span: token.span };
1118
- }
1119
-
1120
- private isName(token: Token): boolean {
1121
- return token.kind === "ident" || token.kind === "keyword";
1122
- }
1123
-
1124
- private expectName(message: string): IdentExpr | undefined {
1125
- if (this.isName(this.peek())) return this.parseIdent();
1126
- this.error(this.peek().span, message);
1127
- return undefined;
1128
- }
1129
-
1130
- private parseTemplatedName(message: string): IdentExpr | undefined {
1131
- if (this.atPunct("[")) {
1132
- const open = this.advance();
1133
- const binding = this.expectIdent(
1134
- "an indexed name needs its loop binding",
1135
- );
1136
- if (!binding || !this.expectPunct("]", "an indexed name needs ]")) {
1137
- return undefined;
440
+ const name = this.path();
441
+ if (this.eat("(")) {
442
+ const args: Expr[] = [];
443
+ while (!this.eat(")")) {
444
+ args.push(this.expression());
445
+ this.separators();
1138
446
  }
1139
- const suffix = this.isName(this.peek()) ? this.parseIdent() : undefined;
447
+ return { kind: "call", name, args, span: this.span(start) };
448
+ }
449
+ let target: string | undefined;
450
+ let owner: string | undefined;
451
+ if (["ref", "list"].includes(name) && this.eat("<")) {
452
+ target = this.path();
453
+ this.expect(">");
454
+ }
455
+ const many = name === "ref" && this.eat("[");
456
+ if (many) this.expect("]");
457
+ if (this.eat("of")) owner = this.path();
458
+ const optional = this.eat("?");
459
+ if (target || owner || optional || many)
1140
460
  return {
1141
- kind: "ident",
1142
- name: `[${binding.name}]${suffix?.name ?? ""}`,
1143
- span: {
1144
- start: open.span.start,
1145
- end: suffix?.span.end ?? this.previous().span.end,
1146
- },
461
+ kind: "type",
462
+ name,
463
+ ...(target ? { target } : {}),
464
+ ...(owner ? { owner } : {}),
465
+ optional,
466
+ ...(many ? { many: true } : {}),
467
+ span: this.span(start),
1147
468
  };
1148
- }
1149
- const base = this.expectName(message);
1150
- if (!base || !this.atPunct("[")) return base;
1151
- this.advance();
1152
- const binding = this.expectIdent("an indexed name needs its loop binding");
1153
- if (!binding || !this.expectPunct("]", "an indexed name needs ]")) {
1154
- return undefined;
1155
- }
1156
- const suffix = this.isName(this.peek()) ? this.parseIdent() : undefined;
1157
- return {
1158
- kind: "ident",
1159
- name: `${base.name}[${binding.name}]${suffix?.name ?? ""}`,
1160
- span: {
1161
- start: base.span.start,
1162
- end: suffix?.span.end ?? this.previous().span.end,
1163
- },
1164
- };
1165
- }
1166
-
1167
- private canStartExpr(token: Token): boolean {
1168
- return (
1169
- token.kind === "ident" ||
1170
- token.kind === "keyword" ||
1171
- token.kind === "number" ||
1172
- token.kind === "percent" ||
1173
- token.kind === "string" ||
1174
- (token.kind === "punct" && (token.text === "{" || token.text === "["))
1175
- );
1176
- }
1177
-
1178
- private parsePath(message: string): import("./ast.ts").PathExpr | undefined {
1179
- const first = this.expectName(message);
1180
- if (!first) return undefined;
1181
- const parts = [first];
1182
- while (this.atPunct(".")) {
1183
- this.advance();
1184
- const part = this.expectName("expected a name after .");
1185
- if (!part) return undefined;
1186
- parts.push(part);
1187
- }
1188
- return {
1189
- kind: "path",
1190
- parts,
1191
- span: {
1192
- start: first.span.start,
1193
- end: parts.at(-1)?.span.end ?? first.span.end,
1194
- },
1195
- };
1196
- }
1197
-
1198
- private parseAngleArguments(): Expr[] | undefined {
1199
- this.advance();
1200
- const args: Expr[] = [];
1201
- while (!this.atPunct(">") && !this.at("eof")) {
1202
- const arg = this.parseExpr();
1203
- if (!arg) return undefined;
1204
- args.push(arg);
1205
- if (this.atPunct(",")) this.advance();
1206
- }
1207
- return this.expectPunct(">", "the type argument list never closes")
1208
- ? args
1209
- : undefined;
469
+ return { kind: "name", value: name, span: this.span(start) };
1210
470
  }
1211
-
1212
- private parseApplication(): ApplyExpr | undefined {
1213
- const callee = this.parsePath("expected an instrument function name");
1214
- if (!callee) return undefined;
1215
- const typeArgs = this.atPunct("<") ? this.parseAngleArguments() : [];
1216
- if (!typeArgs) return undefined;
1217
- if (
1218
- !this.expectPunct(
1219
- "(",
1220
- "an instrument application needs arguments in parentheses",
1221
- )
1222
- ) {
1223
- return undefined;
1224
- }
1225
- const args: Expr[] = [];
1226
- while (!this.atPunct(")") && !this.at("eof")) {
1227
- const arg = this.parseExpr();
1228
- if (!arg) return undefined;
1229
- args.push(arg);
1230
- if (this.atPunct(",")) this.advance();
1231
- }
1232
- if (!this.expectPunct(")", "the instrument argument list never closes")) {
1233
- return undefined;
1234
- }
1235
- return {
1236
- args,
1237
- callee,
1238
- kind: "apply",
1239
- span: { start: callee.span.start, end: this.previous().span.end },
1240
- typeArgs,
1241
- };
1242
- }
1243
-
1244
- private expectIdent(message: string): IdentExpr | undefined {
1245
- if (this.at("ident")) return this.parseIdent();
1246
- this.error(this.peek().span, message);
1247
- return undefined;
1248
- }
1249
-
1250
- private expectPunct(glyph: string, message: string): boolean {
1251
- if (this.atPunct(glyph)) {
1252
- this.advance();
1253
- return true;
1254
- }
1255
- this.error(this.peek().span, message);
1256
- return false;
1257
- }
1258
-
1259
- private spanFrom(start: Span): Span {
1260
- return { end: this.previous().span.end, start: start.start };
1261
- }
1262
-
1263
- private error(span: Span, message: string): void {
1264
- this.diagnostics.push({ message, span });
1265
- }
1266
- }
1267
-
1268
- /**
1269
- * Convert a percent literal's raw digits to exact basis points, or refuse
1270
- * when the literal is finer than a basis point. "99.5" -> 9950; "0.05" -> 5.
1271
- */
1272
- export function percentToBps(raw: string): number | undefined {
1273
- const [whole = "0", fraction = ""] = raw.split(".");
1274
- if (fraction.length > 2) return undefined;
1275
- const scaled = fraction.padEnd(2, "0");
1276
- return Number(whole) * 100 + Number(scaled === "" ? "0" : scaled);
1277
471
  }