@the_dissidents/libemmm 0.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.
package/dist/index.js ADDED
@@ -0,0 +1,1558 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ArgumentInterpolatorDefinition: () => ArgumentInterpolatorDefinition,
24
+ ArgumentsTooFewMessage: () => ArgumentsTooFewMessage,
25
+ ArgumentsTooManyMessage: () => ArgumentsTooManyMessage,
26
+ BlockModifierDefinition: () => BlockModifierDefinition,
27
+ BuiltinConfiguration: () => BuiltinConfiguration,
28
+ Configuration: () => Configuration,
29
+ ContentShouldBeOnNewlineMessage: () => ContentShouldBeOnNewlineMessage,
30
+ Document: () => Document2,
31
+ ExpectedMessage: () => ExpectedMessage,
32
+ InlineDefinitonInvalidEntityMessage: () => InlineDefinitonInvalidEntityMessage,
33
+ InlineModifierDefinition: () => InlineModifierDefinition,
34
+ InvalidArgumentMessage: () => InvalidArgumentMessage,
35
+ MessageSeverity: () => MessageSeverity,
36
+ ModifierFlags: () => ModifierFlags,
37
+ NameAlreadyDefinedMessage: () => NameAlreadyDefinedMessage,
38
+ NewBlockShouldBeOnNewlineMessage: () => NewBlockShouldBeOnNewlineMessage,
39
+ NodeType: () => NodeType,
40
+ ParseContext: () => ParseContext,
41
+ ReachedRecursionLimitMessage: () => ReachedRecursionLimitMessage,
42
+ ReferredMessage: () => ReferredMessage,
43
+ SimpleScanner: () => SimpleScanner,
44
+ SlotUsedOutsideDefinitionMessage: () => SlotUsedOutsideDefinitionMessage,
45
+ SystemModifierDefinition: () => SystemModifierDefinition,
46
+ UnclosedInlineModifierMessage: () => UnclosedInlineModifierMessage,
47
+ UndefinedVariableMessage: () => UndefinedVariableMessage,
48
+ UnknownModifierMessage: () => UnknownModifierMessage,
49
+ UnnecessaryNewlineMessage: () => UnnecessaryNewlineMessage,
50
+ parse: () => parse
51
+ });
52
+ module.exports = __toCommonJS(index_exports);
53
+
54
+ // src/debug.ts
55
+ var debug = {
56
+ level: 1 /* Info */,
57
+ trace(arg0, ...args) {
58
+ if (this.level > 0 /* Trace */) return;
59
+ if (typeof arg0 == "function") arg0 = arg0();
60
+ console.info("TRACE", arg0, ...args);
61
+ },
62
+ info(arg0, ...args) {
63
+ if (this.level > 1 /* Info */) return;
64
+ if (typeof arg0 == "function") arg0 = arg0();
65
+ console.info(" INFO", arg0, ...args);
66
+ },
67
+ warning(arg0, ...args) {
68
+ if (this.level > 2 /* Warning */) return;
69
+ if (typeof arg0 == "function") arg0 = arg0();
70
+ console.warn(" WARN", arg0, ...args);
71
+ },
72
+ error(arg0, ...args) {
73
+ if (this.level > 3 /* Error */) return;
74
+ if (typeof arg0 == "function") arg0 = arg0();
75
+ console.error("ERROR", arg0, ...args);
76
+ },
77
+ never(_) {
78
+ assert(false);
79
+ }
80
+ };
81
+
82
+ // src/messages.ts
83
+ var ReferredMessage = class {
84
+ constructor(original, position, length) {
85
+ this.original = original;
86
+ this.position = position;
87
+ this.length = length;
88
+ }
89
+ get severity() {
90
+ return this.original.severity;
91
+ }
92
+ get info() {
93
+ return this.original.info;
94
+ }
95
+ get code() {
96
+ return this.original.code;
97
+ }
98
+ fixes = [];
99
+ };
100
+ var AddThingMessage = class {
101
+ constructor(code, severity, position, length, info, fixstr, what) {
102
+ this.code = code;
103
+ this.severity = severity;
104
+ this.position = position;
105
+ this.length = length;
106
+ this.info = info;
107
+ this.fixstr = fixstr;
108
+ this.what = what;
109
+ }
110
+ get fixes() {
111
+ let [pos, what, fixstr] = [this.position, this.what, this.fixstr];
112
+ return [{
113
+ get info() {
114
+ return fixstr;
115
+ },
116
+ apply(src, cursor) {
117
+ let newCursor = cursor < pos ? cursor : cursor + what.length;
118
+ return [src.substring(0, pos) + what + src.substring(pos), newCursor];
119
+ }
120
+ }];
121
+ }
122
+ };
123
+ var RemoveThingMessage = class {
124
+ constructor(code, severity, position, length, info, fixstr) {
125
+ this.code = code;
126
+ this.severity = severity;
127
+ this.position = position;
128
+ this.length = length;
129
+ this.info = info;
130
+ this.fixstr = fixstr;
131
+ }
132
+ get fixes() {
133
+ let [pos, len, fixstr] = [this.position, this.length, this.fixstr];
134
+ return [{
135
+ get info() {
136
+ return fixstr;
137
+ },
138
+ apply(src, cursor) {
139
+ let newCursor = cursor < pos + len && cursor >= pos ? pos : cursor - len;
140
+ return [src.substring(0, pos) + src.substring(pos + len), newCursor];
141
+ }
142
+ }];
143
+ }
144
+ };
145
+ var ExpectedMessage = class {
146
+ constructor(position, what) {
147
+ this.position = position;
148
+ this.what = what;
149
+ }
150
+ code = 1;
151
+ severity = 2 /* Error */;
152
+ get length() {
153
+ return this.what.length;
154
+ }
155
+ get info() {
156
+ return `expected '${this.what}'`;
157
+ }
158
+ get fixes() {
159
+ return [];
160
+ }
161
+ };
162
+ var UnknownModifierMessage = class {
163
+ constructor(position, length) {
164
+ this.position = position;
165
+ this.length = length;
166
+ }
167
+ code = 2;
168
+ severity = 2 /* Error */;
169
+ info = `unknown modifier; did you forget to escape it?`;
170
+ get fixes() {
171
+ let [pos, len] = [this.position, this.length];
172
+ return [{
173
+ get info() {
174
+ return "this is not a modifier -- escape it";
175
+ },
176
+ apply(src, cursor) {
177
+ let newCursor = cursor < pos ? cursor : cursor + 1;
178
+ return [src.substring(0, pos) + "\\" + src.substring(pos), newCursor];
179
+ }
180
+ }];
181
+ }
182
+ };
183
+ var UnclosedInlineModifierMessage = class {
184
+ constructor(position, what) {
185
+ this.position = position;
186
+ this.what = what;
187
+ }
188
+ code = 3;
189
+ severity = 2 /* Error */;
190
+ length = 0;
191
+ fixes = [];
192
+ get info() {
193
+ return `unclosed inline modifier ${this.what}'`;
194
+ }
195
+ };
196
+ var ArgumentsTooFewMessage = class {
197
+ constructor(position, length, expected) {
198
+ this.position = position;
199
+ this.length = length;
200
+ this.expected = expected;
201
+ }
202
+ code = 4;
203
+ severity = 2 /* Error */;
204
+ fixes = [];
205
+ get info() {
206
+ return `too few argument(s)` + (this.expected === void 0 ? "" : `, ${this.expected} expected`);
207
+ }
208
+ };
209
+ var ArgumentsTooManyMessage = class extends RemoveThingMessage {
210
+ constructor(pos, len, expected) {
211
+ super(
212
+ 5,
213
+ 1 /* Warning */,
214
+ pos,
215
+ len,
216
+ "too many arguments" + (expected === void 0 ? "" : `, ${expected} expected`),
217
+ "remove them"
218
+ );
219
+ }
220
+ };
221
+ var InvalidArgumentMessage = class {
222
+ constructor(position, length, what) {
223
+ this.position = position;
224
+ this.length = length;
225
+ this.what = what;
226
+ }
227
+ code = 6;
228
+ severity = 2 /* Error */;
229
+ fixes = [];
230
+ get info() {
231
+ return `invalid argument` + (this.what === void 0 ? "" : `: ${this.what}`);
232
+ }
233
+ };
234
+ var InlineDefinitonInvalidEntityMessage = class {
235
+ constructor(position, length) {
236
+ this.position = position;
237
+ this.length = length;
238
+ }
239
+ code = 7;
240
+ severity = 2 /* Error */;
241
+ fixes = [];
242
+ get info() {
243
+ return `Invalid entity in inline modifier definition`;
244
+ }
245
+ };
246
+ var ReachedRecursionLimitMessage = class {
247
+ constructor(position, length, limit, what) {
248
+ this.position = position;
249
+ this.length = length;
250
+ this.limit = limit;
251
+ this.what = what;
252
+ }
253
+ code = 8;
254
+ severity = 2 /* Error */;
255
+ fixes = [];
256
+ get info() {
257
+ return `Reached recursion limit ${this.limit} when expanding ${this.what}`;
258
+ }
259
+ };
260
+ var SlotUsedOutsideDefinitionMessage = class {
261
+ constructor(position, length) {
262
+ this.position = position;
263
+ this.length = length;
264
+ }
265
+ code = 9;
266
+ severity = 2 /* Error */;
267
+ fixes = [];
268
+ get info() {
269
+ return `[.slot] used outside a block definition`;
270
+ }
271
+ };
272
+ var UnnecessaryNewlineMessage = class extends RemoveThingMessage {
273
+ constructor(pos, len) {
274
+ super(
275
+ 1,
276
+ 1 /* Warning */,
277
+ pos,
278
+ len,
279
+ "more than one newlines have the same effect as one",
280
+ "remove the redundant newlines"
281
+ );
282
+ }
283
+ };
284
+ var NewBlockShouldBeOnNewlineMessage = class extends AddThingMessage {
285
+ constructor(pos) {
286
+ super(
287
+ 2,
288
+ 1 /* Warning */,
289
+ pos,
290
+ 0,
291
+ "a new block should begin in a new line to avoid confusion",
292
+ "add a line break",
293
+ "\n"
294
+ );
295
+ }
296
+ };
297
+ var ContentShouldBeOnNewlineMessage = class extends AddThingMessage {
298
+ constructor(pos) {
299
+ super(
300
+ 3,
301
+ 1 /* Warning */,
302
+ pos,
303
+ 0,
304
+ "the content should begin in a new line to avoid confusion",
305
+ "add a line break",
306
+ "\n"
307
+ );
308
+ }
309
+ };
310
+ var NameAlreadyDefinedMessage = class {
311
+ constructor(position, length, what) {
312
+ this.position = position;
313
+ this.length = length;
314
+ this.what = what;
315
+ }
316
+ code = 4;
317
+ severity = 1 /* Warning */;
318
+ fixes = [];
319
+ get info() {
320
+ return `name is already defined, will overwrite: ${this.what}`;
321
+ }
322
+ };
323
+ var UndefinedVariableMessage = class {
324
+ constructor(position, length, what) {
325
+ this.position = position;
326
+ this.length = length;
327
+ this.what = what;
328
+ }
329
+ code = 5;
330
+ severity = 1 /* Warning */;
331
+ fixes = [];
332
+ get info() {
333
+ return `variable is undefined, will expand to empty string: ${this.what}`;
334
+ }
335
+ };
336
+
337
+ // src/util.ts
338
+ var NameManager = class {
339
+ array = [];
340
+ data;
341
+ constructor(from) {
342
+ this.array = [...from?.array ?? []];
343
+ this.data = new Map(from?.data);
344
+ }
345
+ get(name) {
346
+ return this.data.get(name);
347
+ }
348
+ has(name) {
349
+ return this.data.has(name);
350
+ }
351
+ remove(name) {
352
+ let i = this.data.get(name);
353
+ assert(i !== void 0);
354
+ this.data.delete(name);
355
+ this.array.splice(this.array.findIndex((x) => x.k == name), 1);
356
+ }
357
+ add(...elems) {
358
+ for (const elem of elems) {
359
+ assert(!this.has(elem.name));
360
+ this.data.set(elem.name, elem);
361
+ const len = elem.name.length;
362
+ let i = 0;
363
+ while (i < this.array.length && this.array[i].k.length > len) i++;
364
+ this.array.splice(i, 0, { k: elem.name, v: elem });
365
+ }
366
+ }
367
+ find(predicate) {
368
+ const result = this.array.find((x) => predicate(x.v));
369
+ return result ? result.v : void 0;
370
+ }
371
+ };
372
+ function assert(x) {
373
+ if (!!!x) {
374
+ let error = new Error("assertion failed");
375
+ console.log(error.stack);
376
+ throw error;
377
+ }
378
+ }
379
+ function has(v, f) {
380
+ return (v & f) === f;
381
+ }
382
+ function cloneNode(node, referring) {
383
+ switch (node.type) {
384
+ case 7 /* BlockModifier */:
385
+ case 6 /* InlineModifier */:
386
+ case 5 /* SystemModifier */:
387
+ return {
388
+ start: node.start,
389
+ end: node.end,
390
+ type: node.type,
391
+ mod: node.mod,
392
+ state: void 0,
393
+ head: structuredClone(node.head),
394
+ arguments: structuredClone(node.arguments),
395
+ content: node.content.map((x) => cloneNode(x, referring)),
396
+ expansion: node.expansion ? cloneNodes(node.expansion) : void 0
397
+ };
398
+ case 0 /* Root */:
399
+ case 1 /* Paragraph */:
400
+ return {
401
+ type: node.type,
402
+ start: node.start,
403
+ end: node.end,
404
+ content: node.content.map((x) => cloneNode(x))
405
+ };
406
+ case 2 /* Preformatted */:
407
+ case 3 /* Text */:
408
+ case 4 /* Escaped */:
409
+ return structuredClone(node);
410
+ default:
411
+ return debug.never(node);
412
+ }
413
+ }
414
+ function cloneNodes(nodes) {
415
+ return nodes.map((x) => cloneNode(x));
416
+ }
417
+ function debugPrintArgEntity(node) {
418
+ switch (node.type) {
419
+ case 3 /* Text */:
420
+ return node.content;
421
+ case 4 /* Escaped */:
422
+ return `<Escaped:${node.content}>`;
423
+ case 8 /* Interpolation */:
424
+ return `<Interp:${node.definition.name}-${node.definition.postfix}:${debugPrintArgument(node.arg)}>`;
425
+ default:
426
+ return debug.never(node);
427
+ }
428
+ }
429
+ function debugPrintArgument(arg) {
430
+ return arg.content.map(debugPrintArgEntity).join("");
431
+ }
432
+ function debugPrintNode(node, prefix = "") {
433
+ let result = `<${node.type}@${node.start}`;
434
+ switch (node.type) {
435
+ case 0 /* Root */:
436
+ case 1 /* Paragraph */:
437
+ const content = debugPrintNodes(node.content, prefix);
438
+ if (content.length > 0)
439
+ result += `>
440
+ ${content}
441
+ ${prefix}</${node.type}@${node.end}>`;
442
+ else result += `-${node.end} />`;
443
+ break;
444
+ case 4 /* Escaped */:
445
+ case 2 /* Preformatted */:
446
+ result += `>
447
+ ${prefix} ${node.content}
448
+ ${prefix}</${node.type}@${node.end}>`;
449
+ break;
450
+ case 6 /* InlineModifier */:
451
+ case 7 /* BlockModifier */:
452
+ case 5 /* SystemModifier */:
453
+ const args = node.arguments.map((x, i) => `
454
+ ${prefix} (${i})@${x.start}-${x.end}=${debugPrintArgument(x)}`).join("");
455
+ if (node.content.length > 0) {
456
+ result += ` id=${node.mod.name}${args}>
457
+ ` + debugPrintNodes(node.content, prefix) + `
458
+ ${prefix}</${node.type}@${node.end}>`;
459
+ } else result += `-${node.end} id=${node.mod.name}${args} />`;
460
+ if (node.expansion) {
461
+ const content2 = debugPrintNodes(node.expansion, prefix);
462
+ if (content2.length > 0)
463
+ result += `
464
+ ${prefix}<expansion>
465
+ ${content2}
466
+ ${prefix}</expansion>`;
467
+ else if (node.type != 5 /* SystemModifier */)
468
+ result += `
469
+ ${prefix}<expansion />`;
470
+ }
471
+ break;
472
+ case 3 /* Text */:
473
+ return node.content;
474
+ default:
475
+ return debug.never(node);
476
+ }
477
+ return result;
478
+ }
479
+ function debugPrintNodes(content, prefix = "") {
480
+ let dumps = content.map((x) => debugPrintNode(x, prefix + " ")).filter((x) => x.length > 0);
481
+ if (dumps.length == 0) return "";
482
+ return dumps.map((x) => `${prefix} ${x}`).join("\n");
483
+ }
484
+
485
+ // src/interface.ts
486
+ var MessageSeverity = /* @__PURE__ */ ((MessageSeverity2) => {
487
+ MessageSeverity2[MessageSeverity2["Info"] = 0] = "Info";
488
+ MessageSeverity2[MessageSeverity2["Warning"] = 1] = "Warning";
489
+ MessageSeverity2[MessageSeverity2["Error"] = 2] = "Error";
490
+ return MessageSeverity2;
491
+ })(MessageSeverity || {});
492
+ var NodeType = /* @__PURE__ */ ((NodeType2) => {
493
+ NodeType2[NodeType2["Root"] = 0] = "Root";
494
+ NodeType2[NodeType2["Paragraph"] = 1] = "Paragraph";
495
+ NodeType2[NodeType2["Preformatted"] = 2] = "Preformatted";
496
+ NodeType2[NodeType2["Text"] = 3] = "Text";
497
+ NodeType2[NodeType2["Escaped"] = 4] = "Escaped";
498
+ NodeType2[NodeType2["SystemModifier"] = 5] = "SystemModifier";
499
+ NodeType2[NodeType2["InlineModifier"] = 6] = "InlineModifier";
500
+ NodeType2[NodeType2["BlockModifier"] = 7] = "BlockModifier";
501
+ NodeType2[NodeType2["Interpolation"] = 8] = "Interpolation";
502
+ return NodeType2;
503
+ })(NodeType || {});
504
+ var ModifierFlags = /* @__PURE__ */ ((ModifierFlags2) => {
505
+ ModifierFlags2[ModifierFlags2["Normal"] = 0] = "Normal";
506
+ ModifierFlags2[ModifierFlags2["Preformatted"] = 1] = "Preformatted";
507
+ ModifierFlags2[ModifierFlags2["Marker"] = 2] = "Marker";
508
+ return ModifierFlags2;
509
+ })(ModifierFlags || {});
510
+ var ModifierBase = class {
511
+ constructor(name, flags = 0 /* Normal */, args) {
512
+ this.name = name;
513
+ this.flags = flags;
514
+ if (args) Object.assign(this, args);
515
+ }
516
+ delayContentExpansion = false;
517
+ alwaysTryExpand = false;
518
+ beforeParseContent;
519
+ afterParseContent;
520
+ beforeProcessExpansion;
521
+ afterProcessExpansion;
522
+ prepareExpand;
523
+ expand;
524
+ };
525
+ var BlockModifierDefinition = class extends ModifierBase {
526
+ };
527
+ var InlineModifierDefinition = class extends ModifierBase {
528
+ };
529
+ var SystemModifierDefinition = class extends ModifierBase {
530
+ };
531
+ var ArgumentInterpolatorDefinition = class {
532
+ constructor(name, postfix, expand) {
533
+ this.name = name;
534
+ this.postfix = postfix;
535
+ this.expand = expand;
536
+ }
537
+ };
538
+ var ParseContext = class {
539
+ constructor(config, variables = /* @__PURE__ */ new Map()) {
540
+ this.config = config;
541
+ this.variables = variables;
542
+ config.initializers.forEach((x) => x(this));
543
+ }
544
+ data = {};
545
+ init(key, obj) {
546
+ assert(!(key in this.data));
547
+ this.data[key] = obj;
548
+ }
549
+ set(key, obj) {
550
+ assert(key in this.data);
551
+ this.data[key] = obj;
552
+ }
553
+ get(key) {
554
+ assert(key in this.data);
555
+ return this.data[key];
556
+ }
557
+ #evalEntity(e) {
558
+ switch (e.type) {
559
+ case 3 /* Text */:
560
+ case 4 /* Escaped */:
561
+ return e.content;
562
+ case 8 /* Interpolation */:
563
+ const inner = this.evaluateArgument(e.arg);
564
+ return e.definition.expand(inner, this);
565
+ default:
566
+ assert(false);
567
+ }
568
+ }
569
+ evaluateArgument(arg) {
570
+ return arg.content.map((x) => this.#evalEntity(x)).join("");
571
+ }
572
+ };
573
+ var Document2 = class {
574
+ constructor(root, context, messages) {
575
+ this.root = root;
576
+ this.context = context;
577
+ this.messages = messages;
578
+ }
579
+ };
580
+ var Configuration = class {
581
+ initializers = [];
582
+ blockModifiers;
583
+ inlineModifiers;
584
+ systemModifiers;
585
+ argumentInterpolators;
586
+ reparseDepthLimit = 10;
587
+ constructor(from) {
588
+ this.blockModifiers = new NameManager(from?.blockModifiers);
589
+ this.inlineModifiers = new NameManager(from?.inlineModifiers);
590
+ this.systemModifiers = new NameManager(from?.systemModifiers);
591
+ this.argumentInterpolators = new NameManager(from?.argumentInterpolators);
592
+ if (from) {
593
+ this.initializers = [...from.initializers];
594
+ this.reparseDepthLimit = from.reparseDepthLimit;
595
+ }
596
+ }
597
+ };
598
+
599
+ // src/front.ts
600
+ var SimpleScanner = class {
601
+ constructor(src) {
602
+ this.src = src;
603
+ }
604
+ pos = 0;
605
+ position() {
606
+ return this.pos;
607
+ }
608
+ isEOF() {
609
+ return this.pos >= this.src.length;
610
+ }
611
+ peek(str) {
612
+ let next = this.pos + str.length;
613
+ if (next > this.src.length) return false;
614
+ return this.src.slice(this.pos, this.pos + str.length) == str;
615
+ }
616
+ acceptChar() {
617
+ if (this.isEOF()) throw new RangeError("EOF");
618
+ let char = this.src[this.pos];
619
+ this.pos++;
620
+ return char;
621
+ }
622
+ accept(str) {
623
+ if (!this.peek(str)) return false;
624
+ this.pos += str.length;
625
+ return true;
626
+ }
627
+ acceptWhitespaceChar() {
628
+ if (this.isEOF()) return null;
629
+ let char = this.src[this.pos];
630
+ if (!" ".includes(char)) return null;
631
+ this.pos++;
632
+ return char;
633
+ }
634
+ acceptUntil(str) {
635
+ let start = this.pos;
636
+ while (!this.isEOF()) {
637
+ if (this.peek(str)) {
638
+ let result = this.src.slice(start, this.pos);
639
+ return result;
640
+ }
641
+ this.pos++;
642
+ }
643
+ return null;
644
+ }
645
+ };
646
+
647
+ // src/parser.ts
648
+ var GROUP_BEGIN = ":--";
649
+ var GROUP_END = "--:";
650
+ var MODIFIER_BLOCK_OPEN = "[.";
651
+ var MODIFIER_CLOSE_SIGN = "]";
652
+ var MODIFIER_END_SIGN = ";";
653
+ var MODIFIER_INLINE_OPEN = "[/";
654
+ var MODIFIER_INLINE_END_TAG = "[;]";
655
+ var MODIFIER_SYSTEM_OPEN = "[-";
656
+ var UnknownModifier = {
657
+ [7 /* BlockModifier */]: new BlockModifierDefinition("UNKNOWN", 0 /* Normal */),
658
+ [6 /* InlineModifier */]: new InlineModifierDefinition("UNKNOWN", 0 /* Normal */),
659
+ [5 /* SystemModifier */]: new SystemModifierDefinition("UNKNOWN", 0 /* Normal */)
660
+ };
661
+ var EmitEnvironment = class {
662
+ constructor(scanner) {
663
+ this.scanner = scanner;
664
+ }
665
+ root = { type: 0 /* Root */, start: 0, end: -1, content: [] };
666
+ messages = [];
667
+ blockStack = [this.root];
668
+ inlineStack = [];
669
+ referringStack = [];
670
+ message(...m) {
671
+ const referringReverse = [...this.referringStack].reverse();
672
+ for (let msg of m) {
673
+ for (const range of referringReverse)
674
+ msg = new ReferredMessage(msg, range.start, range.end - range.start);
675
+ this.messages.push(msg);
676
+ debug.trace("issued msg", msg.code, msg.info);
677
+ }
678
+ }
679
+ pushReferring(start, end) {
680
+ this.referringStack.push({ start, end });
681
+ }
682
+ popReferring() {
683
+ assert(this.referringStack.length > 0);
684
+ this.referringStack.pop();
685
+ }
686
+ addBlockNode(n) {
687
+ assert(this.blockStack.length > 0);
688
+ this.blockStack.at(-1).content.push(n);
689
+ return n;
690
+ }
691
+ addInlineNode(n) {
692
+ assert(this.inlineStack.length > 0);
693
+ this.inlineStack.at(-1).content.push(n);
694
+ return n;
695
+ }
696
+ addString(str) {
697
+ assert(this.inlineStack.length > 0);
698
+ const content = this.inlineStack.at(-1).content;
699
+ const last = content.at(-1);
700
+ if (last?.type == 3 /* Text */) {
701
+ last.content += str;
702
+ last.end = this.scanner.position();
703
+ } else content.push({
704
+ type: 3 /* Text */,
705
+ start: this.scanner.position() - str.length,
706
+ end: this.scanner.position(),
707
+ content: str
708
+ });
709
+ }
710
+ startBlock(block) {
711
+ this.addBlockNode(block);
712
+ this.blockStack.push(block);
713
+ }
714
+ endBlock() {
715
+ assert(this.blockStack.length >= 2);
716
+ const node = this.blockStack.pop();
717
+ node.end = this.scanner.position();
718
+ }
719
+ startInline(n) {
720
+ if (n.type == 1 /* Paragraph */) this.addBlockNode(n);
721
+ else this.addInlineNode(n);
722
+ this.inlineStack.push(n);
723
+ }
724
+ endInline() {
725
+ assert(this.inlineStack.length > 0);
726
+ const node = this.inlineStack.pop();
727
+ node.end = this.scanner.position();
728
+ }
729
+ };
730
+ var Parser = class {
731
+ constructor(scanner, config) {
732
+ this.scanner = scanner;
733
+ this.emit = new EmitEnvironment(scanner);
734
+ this.cxt = new ParseContext(config);
735
+ }
736
+ emit;
737
+ cxt;
738
+ delayDepth = 0;
739
+ groupDepth = 0;
740
+ #defs(type) {
741
+ switch (type) {
742
+ case 5 /* SystemModifier */:
743
+ return this.cxt.config.systemModifiers;
744
+ case 6 /* InlineModifier */:
745
+ return this.cxt.config.inlineModifiers;
746
+ case 7 /* BlockModifier */:
747
+ return this.cxt.config.blockModifiers;
748
+ default:
749
+ return debug.never(type);
750
+ }
751
+ }
752
+ #reparse(nodes, depth) {
753
+ if (depth > this.cxt.config.reparseDepthLimit) return false;
754
+ let ok = true;
755
+ for (const node of nodes) {
756
+ switch (node.type) {
757
+ case 2 /* Preformatted */:
758
+ case 3 /* Text */:
759
+ case 4 /* Escaped */:
760
+ continue;
761
+ case 1 /* Paragraph */:
762
+ ok = this.#reparse(node.content, depth + 1) && ok;
763
+ continue;
764
+ case 7 /* BlockModifier */:
765
+ case 6 /* InlineModifier */:
766
+ case 5 /* SystemModifier */:
767
+ ok = this.#expand(node, depth + 1) && ok;
768
+ continue;
769
+ default:
770
+ debug.never(node);
771
+ }
772
+ }
773
+ return ok;
774
+ }
775
+ #expand(node, depth = 0) {
776
+ if (node.expansion !== void 0) {
777
+ debug.trace("already expanded, skipping:", node.mod.name);
778
+ return true;
779
+ }
780
+ if (this.delayDepth > 0 && !node.mod.alwaysTryExpand) {
781
+ debug.trace("delaying expansion of", node.mod.name);
782
+ return true;
783
+ }
784
+ const immediate = this.delayDepth == 0;
785
+ if (node.content.length > 0 && depth > 0) {
786
+ if (node.mod.beforeParseContent)
787
+ this.emit.message(...node.mod.beforeParseContent(node, this.cxt, immediate));
788
+ if (node.mod.delayContentExpansion) this.delayDepth++;
789
+ this.#reparse(node.content, depth);
790
+ if (node.mod.delayContentExpansion) this.delayDepth--;
791
+ if (node.mod.afterParseContent)
792
+ this.emit.message(...node.mod.afterParseContent(node, this.cxt, immediate));
793
+ }
794
+ if (node.mod.prepareExpand)
795
+ this.emit.message(...node.mod.prepareExpand(node, this.cxt, immediate));
796
+ if (node.mod.expand) {
797
+ node.expansion = node.mod.expand(node, this.cxt, immediate);
798
+ if (!node.expansion) {
799
+ return true;
800
+ } else if (node.expansion.length > 0) {
801
+ debug.trace(`${this.delayDepth > 0 ? "early " : ""}expanding:`, node.mod.name);
802
+ debug.trace(() => "-->\n" + debugPrintNodes(node.expansion, " "));
803
+ } else {
804
+ debug.trace(`${this.delayDepth > 0 ? "early " : ""}expanding:`, node.mod.name);
805
+ }
806
+ }
807
+ const expansion = node.expansion ?? node.content;
808
+ if (expansion.length == 0) return true;
809
+ if (node.mod.beforeProcessExpansion)
810
+ this.emit.message(...node.mod.beforeProcessExpansion(node, this.cxt, immediate));
811
+ this.emit.pushReferring(node.start, node.end);
812
+ let ok = this.#reparse(expansion, depth);
813
+ this.emit.popReferring();
814
+ if (node.mod.afterProcessExpansion)
815
+ this.emit.message(...node.mod.afterProcessExpansion(node, this.cxt, immediate));
816
+ if (!ok && depth == 0) {
817
+ const limit = this.cxt.config.reparseDepthLimit;
818
+ this.emit.message(new ReachedRecursionLimitMessage(
819
+ node.start,
820
+ node.end - node.start,
821
+ limit,
822
+ node.mod.name
823
+ ));
824
+ }
825
+ return ok;
826
+ }
827
+ parse() {
828
+ this.DOCUMENT();
829
+ return new Document2(this.emit.root, this.cxt, this.emit.messages);
830
+ }
831
+ WHITESPACES_OR_NEWLINES() {
832
+ while (this.scanner.acceptWhitespaceChar() !== null || this.scanner.accept("\n")) {
833
+ }
834
+ }
835
+ SHOULD_BE_A_NEWLINE() {
836
+ while (this.scanner.acceptWhitespaceChar() !== null) {
837
+ }
838
+ if (!this.scanner.accept("\n")) this.emit.message(
839
+ new ContentShouldBeOnNewlineMessage(this.scanner.position())
840
+ );
841
+ }
842
+ // TODO: this is awkward and doesn't emit messages in the most appropriate way
843
+ WARN_IF_MORE_NEWLINES_THAN(n) {
844
+ let nlines = 0;
845
+ const start = this.scanner.position();
846
+ while (true) {
847
+ if (this.scanner.accept("\n")) {
848
+ nlines++;
849
+ continue;
850
+ }
851
+ if (this.scanner.acceptWhitespaceChar() == null) break;
852
+ }
853
+ const end = this.scanner.position();
854
+ if (nlines > n) this.emit.message(
855
+ new UnnecessaryNewlineMessage(start, end - start)
856
+ );
857
+ }
858
+ DOCUMENT() {
859
+ this.WHITESPACES_OR_NEWLINES();
860
+ while (!this.scanner.isEOF()) {
861
+ this.BLOCK_ENTITY();
862
+ this.WHITESPACES_OR_NEWLINES();
863
+ }
864
+ }
865
+ BLOCK_ENTITY() {
866
+ assert(!this.scanner.isEOF());
867
+ if (this.scanner.peek(MODIFIER_BLOCK_OPEN)) {
868
+ this.MODIFIER(7 /* BlockModifier */);
869
+ return;
870
+ }
871
+ if (this.scanner.peek(MODIFIER_SYSTEM_OPEN)) {
872
+ this.MODIFIER(5 /* SystemModifier */);
873
+ return;
874
+ }
875
+ this.MAYBE_GROUPED_PARAGRAPH();
876
+ }
877
+ MODIFIER(type) {
878
+ const posStart = this.scanner.position();
879
+ assert(this.scanner.accept({
880
+ [7 /* BlockModifier */]: MODIFIER_BLOCK_OPEN,
881
+ [5 /* SystemModifier */]: MODIFIER_SYSTEM_OPEN,
882
+ [6 /* InlineModifier */]: MODIFIER_INLINE_OPEN
883
+ }[type]));
884
+ const result = this.#defs(type).find((x) => this.scanner.accept(x.name));
885
+ const mod = result ?? UnknownModifier[type];
886
+ if (result === void 0) {
887
+ const args2 = this.scanner.acceptUntil(MODIFIER_CLOSE_SIGN);
888
+ if (args2 === null) this.emit.message(
889
+ new ExpectedMessage(this.scanner.position(), MODIFIER_CLOSE_SIGN)
890
+ );
891
+ this.emit.message(
892
+ new UnknownModifierMessage(posStart, this.scanner.position() - posStart)
893
+ );
894
+ }
895
+ const args = this.ARGUMENTS();
896
+ debug.trace(`PARSE ${type} modifier:`, mod.name);
897
+ const endsign = this.scanner.accept(MODIFIER_END_SIGN);
898
+ const flagMarker = has(mod.flags, 2 /* Marker */);
899
+ const isMarker = flagMarker || endsign;
900
+ if (!this.scanner.accept(MODIFIER_CLOSE_SIGN))
901
+ this.emit.message(new ExpectedMessage(
902
+ this.scanner.position(),
903
+ MODIFIER_CLOSE_SIGN
904
+ ));
905
+ const node = {
906
+ type,
907
+ mod,
908
+ head: { start: posStart, end: this.scanner.position() },
909
+ arguments: args,
910
+ start: posStart,
911
+ end: -1,
912
+ content: [],
913
+ expansion: void 0
914
+ };
915
+ const immediate = this.delayDepth == 0;
916
+ if (node.mod.beforeParseContent)
917
+ this.emit.message(...node.mod.beforeParseContent(node, this.cxt, immediate));
918
+ if (node.mod.delayContentExpansion) this.delayDepth++;
919
+ let ok = true;
920
+ if (isMarker) {
921
+ if (type === 6 /* InlineModifier */) this.emit.addInlineNode(node);
922
+ else this.emit.addBlockNode(node);
923
+ } else if (type == 6 /* InlineModifier */) {
924
+ this.emit.startInline(node);
925
+ const entity = has(mod.flags, 1 /* Preformatted */) ? this.PREFORMATTED_INLINE_ENTITY.bind(this) : this.INLINE_ENTITY.bind(this);
926
+ while (true) {
927
+ if (this.scanner.accept(MODIFIER_INLINE_END_TAG)) break;
928
+ if (this.scanner.isEOF() || !(ok = entity())) {
929
+ this.emit.message(new UnclosedInlineModifierMessage(
930
+ this.scanner.position(),
931
+ mod.name
932
+ ));
933
+ break;
934
+ }
935
+ }
936
+ this.emit.endInline();
937
+ } else {
938
+ this.emit.startBlock(node);
939
+ this.WARN_IF_MORE_NEWLINES_THAN(1);
940
+ if (!this.scanner.isEOF()) {
941
+ if (has(mod.flags, 1 /* Preformatted */))
942
+ this.PRE_PARAGRAPH();
943
+ else
944
+ this.BLOCK_ENTITY();
945
+ }
946
+ this.emit.endBlock();
947
+ }
948
+ if (node.mod.delayContentExpansion) this.delayDepth--;
949
+ if (node.mod.afterParseContent)
950
+ this.emit.message(...node.mod.afterParseContent(node, this.cxt, immediate));
951
+ this.#expand(node);
952
+ return ok;
953
+ }
954
+ // also handles "grouped" (delimited) pre-paragraphs
955
+ PRE_PARAGRAPH() {
956
+ assert(!this.scanner.isEOF());
957
+ const posStart = this.scanner.position();
958
+ const grouped = this.scanner.accept(GROUP_BEGIN);
959
+ if (grouped) this.SHOULD_BE_A_NEWLINE();
960
+ const posContentStart = this.scanner.position();
961
+ let posContentEnd = this.scanner.position();
962
+ let string = "";
963
+ while (!this.scanner.isEOF()) {
964
+ if (this.scanner.accept("\n")) {
965
+ let white = "\n";
966
+ let char = "";
967
+ while ((char = this.scanner.acceptWhitespaceChar()) !== null)
968
+ white += char;
969
+ if (grouped && this.scanner.accept(GROUP_END) || !grouped && this.scanner.accept("\n")) break;
970
+ if (this.scanner.isEOF()) {
971
+ if (grouped) this.emit.message(new ExpectedMessage(
972
+ this.scanner.position(),
973
+ GROUP_END
974
+ ));
975
+ break;
976
+ }
977
+ string += white;
978
+ } else {
979
+ string += this.scanner.acceptChar();
980
+ }
981
+ posContentEnd = this.scanner.position();
982
+ }
983
+ const node = {
984
+ type: 2 /* Preformatted */,
985
+ start: posStart,
986
+ end: this.scanner.position(),
987
+ content: {
988
+ start: posContentStart,
989
+ end: posContentEnd,
990
+ text: string
991
+ }
992
+ };
993
+ this.emit.addBlockNode(node);
994
+ }
995
+ MAYBE_GROUPED_PARAGRAPH() {
996
+ assert(!this.scanner.isEOF());
997
+ if (this.scanner.accept(GROUP_BEGIN)) {
998
+ this.groupDepth++;
999
+ this.SHOULD_BE_A_NEWLINE();
1000
+ this.WARN_IF_MORE_NEWLINES_THAN(1);
1001
+ while (!this.scanner.isEOF()) {
1002
+ if (this.scanner.accept(GROUP_END)) {
1003
+ this.groupDepth--;
1004
+ return;
1005
+ }
1006
+ this.BLOCK_ENTITY();
1007
+ this.WARN_IF_MORE_NEWLINES_THAN(1);
1008
+ }
1009
+ this.emit.message(new ExpectedMessage(
1010
+ this.scanner.position(),
1011
+ GROUP_END
1012
+ ));
1013
+ } else {
1014
+ this.PARAGRAPH();
1015
+ }
1016
+ }
1017
+ PARAGRAPH() {
1018
+ assert(!this.scanner.isEOF());
1019
+ const node = {
1020
+ type: 1 /* Paragraph */,
1021
+ start: this.scanner.position(),
1022
+ end: -1,
1023
+ content: []
1024
+ };
1025
+ debug.trace("PARSE para");
1026
+ this.emit.startInline(node);
1027
+ while (!this.scanner.isEOF() && this.INLINE_ENTITY()) {
1028
+ }
1029
+ this.emit.endInline();
1030
+ debug.trace("PARSE para end");
1031
+ }
1032
+ // returns false if breaking out of paragraph
1033
+ INLINE_ENTITY() {
1034
+ assert(!this.scanner.isEOF());
1035
+ if (this.scanner.peek(MODIFIER_BLOCK_OPEN)) {
1036
+ this.emit.message(new NewBlockShouldBeOnNewlineMessage(this.scanner.position()));
1037
+ return false;
1038
+ }
1039
+ if (this.scanner.peek(MODIFIER_INLINE_OPEN)) {
1040
+ return this.MODIFIER(6 /* InlineModifier */);
1041
+ }
1042
+ if (this.scanner.peek(MODIFIER_SYSTEM_OPEN)) {
1043
+ return false;
1044
+ }
1045
+ if (this.scanner.accept("\\")) {
1046
+ if (this.scanner.isEOF()) {
1047
+ this.emit.addString("\\");
1048
+ return true;
1049
+ }
1050
+ const node = {
1051
+ type: 4 /* Escaped */,
1052
+ start: this.scanner.position() - 1,
1053
+ content: this.scanner.acceptChar(),
1054
+ end: this.scanner.position()
1055
+ };
1056
+ this.emit.addInlineNode(node);
1057
+ return true;
1058
+ }
1059
+ return this.PREFORMATTED_INLINE_ENTITY();
1060
+ }
1061
+ // returns false if breaking out of paragraph
1062
+ PREFORMATTED_INLINE_ENTITY() {
1063
+ assert(!this.scanner.isEOF());
1064
+ if (this.scanner.accept("\n")) {
1065
+ while (this.scanner.acceptWhitespaceChar() !== null) {
1066
+ }
1067
+ if (this.scanner.peek(MODIFIER_BLOCK_OPEN) || this.scanner.peek(MODIFIER_SYSTEM_OPEN) || this.scanner.peek(GROUP_END) && this.groupDepth > 0 || this.scanner.isEOF()) return false;
1068
+ if (this.scanner.accept("\n")) {
1069
+ this.WARN_IF_MORE_NEWLINES_THAN(0);
1070
+ return false;
1071
+ }
1072
+ this.emit.addString("\n");
1073
+ return true;
1074
+ }
1075
+ this.emit.addString(this.scanner.acceptChar());
1076
+ return true;
1077
+ }
1078
+ ARGUMENT_CONTENT(end) {
1079
+ let ok = true;
1080
+ const content = [];
1081
+ const posStart = this.scanner.position();
1082
+ let posEnd = this.scanner.position();
1083
+ const emitString = (s) => {
1084
+ const last = content.at(-1);
1085
+ if (last?.type == 3 /* Text */) {
1086
+ last.content += s;
1087
+ last.end += s.length;
1088
+ } else {
1089
+ const end2 = this.scanner.position();
1090
+ content.push({
1091
+ type: 3 /* Text */,
1092
+ end: end2,
1093
+ start: end2 - s.length,
1094
+ content: s
1095
+ });
1096
+ }
1097
+ };
1098
+ while (true) {
1099
+ if (end !== void 0 && this.scanner.accept(end)) {
1100
+ debug.trace("found end", end);
1101
+ break;
1102
+ }
1103
+ if (this.scanner.accept(":")) {
1104
+ ok = end === void 0;
1105
+ break;
1106
+ }
1107
+ if (this.scanner.peek(MODIFIER_END_SIGN) || this.scanner.peek(MODIFIER_CLOSE_SIGN) || this.scanner.isEOF()) {
1108
+ ok = false;
1109
+ break;
1110
+ }
1111
+ if (this.scanner.accept("\\")) {
1112
+ posEnd = this.scanner.position();
1113
+ if (this.scanner.isEOF()) {
1114
+ emitString("\\");
1115
+ ok = false;
1116
+ break;
1117
+ }
1118
+ content.push({
1119
+ type: 4 /* Escaped */,
1120
+ content: this.scanner.acceptChar(),
1121
+ start: posEnd - 2,
1122
+ end: posEnd
1123
+ });
1124
+ continue;
1125
+ }
1126
+ const result = this.cxt.config.argumentInterpolators.find(
1127
+ (x) => this.scanner.accept(x.name)
1128
+ );
1129
+ if (result !== void 0) {
1130
+ const [inner, ok2] = this.ARGUMENT_CONTENT(result.postfix);
1131
+ posEnd = this.scanner.position();
1132
+ content.push({
1133
+ type: 8 /* Interpolation */,
1134
+ definition: result,
1135
+ arg: inner,
1136
+ start: posEnd - 2,
1137
+ end: posEnd
1138
+ });
1139
+ if (!ok2) {
1140
+ this.emit.message(new ExpectedMessage(posEnd, result.postfix));
1141
+ ok = false;
1142
+ break;
1143
+ }
1144
+ } else {
1145
+ emitString(this.scanner.acceptChar());
1146
+ posEnd = this.scanner.position();
1147
+ }
1148
+ }
1149
+ return [{
1150
+ start: posStart,
1151
+ end: posEnd,
1152
+ content
1153
+ }, ok];
1154
+ }
1155
+ ARGUMENTS() {
1156
+ const firstSemicolon = this.scanner.accept(":");
1157
+ if (!firstSemicolon) this.WHITESPACES_OR_NEWLINES();
1158
+ const list = [];
1159
+ let end = false;
1160
+ while (!end) {
1161
+ const [arg, ok] = this.ARGUMENT_CONTENT();
1162
+ if (!ok) {
1163
+ end = true;
1164
+ if (list.length == 0 && arg.content.length == 0 && !firstSemicolon)
1165
+ break;
1166
+ }
1167
+ list.push(arg);
1168
+ }
1169
+ return list;
1170
+ }
1171
+ };
1172
+ function parse(scanner, config) {
1173
+ return new Parser(scanner, config).parse();
1174
+ }
1175
+
1176
+ // src/builtin/internal.ts
1177
+ var builtins = Symbol();
1178
+ function initParseContext(cxt) {
1179
+ cxt.init(builtins, {
1180
+ blockSlotDelayedStack: [],
1181
+ inlineSlotDelayedStack: [],
1182
+ blockSlotData: [],
1183
+ inlineSlotData: []
1184
+ });
1185
+ }
1186
+ function checkArgumentLength(node, n) {
1187
+ if (node.arguments.length < n)
1188
+ return new ArgumentsTooFewMessage(node.head.end - 1, 0, n);
1189
+ if (node.arguments.length > n) {
1190
+ const start = node.arguments[n].start - 1;
1191
+ return new ArgumentsTooManyMessage(start, node.head.end - start, n);
1192
+ }
1193
+ return null;
1194
+ }
1195
+ function customModifier(type, name, argNames, slotName, content) {
1196
+ debug.info(`registered custom ${type} modifier:`, name);
1197
+ debug.info("args:", argNames, `with ${slotName == "" ? "no slot name" : "slot name: " + slotName}`);
1198
+ debug.trace(() => "content is\n" + debugPrintNodes(content));
1199
+ const mod = type == 7 /* BlockModifier */ ? new BlockModifierDefinition(name, 0 /* Normal */) : new InlineModifierDefinition(name, 0 /* Normal */);
1200
+ const isInline = type == 6 /* InlineModifier */;
1201
+ mod.delayContentExpansion = true;
1202
+ mod.prepareExpand = (node, cxt) => {
1203
+ const check = checkArgumentLength(node, argNames.length);
1204
+ if (check) return [check];
1205
+ node.state = { ok: true };
1206
+ return [];
1207
+ };
1208
+ mod.expand = (node, cxt) => {
1209
+ if (!node.state?.ok) return [];
1210
+ const contentClone = cloneNodes(content);
1211
+ return contentClone;
1212
+ };
1213
+ mod.beforeProcessExpansion = (node, cxt) => {
1214
+ if (!node.state?.ok) return [];
1215
+ const store = cxt.get(builtins);
1216
+ const args = new Map(
1217
+ node.arguments.map((x, i) => [argNames[i], cxt.evaluateArgument(x)])
1218
+ );
1219
+ const data = isInline ? store.inlineSlotData : store.blockSlotData;
1220
+ data.push([slotName, { mod, args, slotContent: node.content }]);
1221
+ debug.trace(
1222
+ `pushed ${type} slot data for`,
1223
+ name,
1224
+ slotName == "" ? "(unnamed)" : `= ${slotName}`
1225
+ );
1226
+ return [];
1227
+ };
1228
+ mod.afterProcessExpansion = (node, cxt) => {
1229
+ if (!node.state?.ok) return [];
1230
+ const store = cxt.get(builtins);
1231
+ const data = isInline ? store.inlineSlotData : store.blockSlotData;
1232
+ const pop = data.pop();
1233
+ assert(pop !== void 0 && pop[0] == slotName);
1234
+ debug.trace(
1235
+ `popped ${type} slot data for`,
1236
+ name,
1237
+ slotName == "" ? "(unnamed)" : `= ${slotName}`
1238
+ );
1239
+ return [];
1240
+ };
1241
+ return mod;
1242
+ }
1243
+
1244
+ // src/builtin/define-block.ts
1245
+ var DefineBlockMod = new SystemModifierDefinition("define-block", 0 /* Normal */, {
1246
+ // .define-block:name:args...[:(slot-id)]
1247
+ delayContentExpansion: true,
1248
+ alwaysTryExpand: true,
1249
+ beforeParseContent(node, cxt) {
1250
+ if (node.arguments.length == 0)
1251
+ return [new ArgumentsTooFewMessage(node.head.end - 1, 0)];
1252
+ const msgs = [];
1253
+ const name = node.arguments[0];
1254
+ const nameValue = cxt.evaluateArgument(name);
1255
+ if (cxt.config.blockModifiers.has(nameValue))
1256
+ msgs.push(new NameAlreadyDefinedMessage(
1257
+ node.start,
1258
+ name.end - name.start,
1259
+ nameValue
1260
+ ));
1261
+ let slotName = "";
1262
+ if (node.arguments.length > 1) {
1263
+ const last = cxt.evaluateArgument(node.arguments.at(-1));
1264
+ slotName = /^\(.+\)$/.test(last) ? last.substring(1, last.length - 1) : "";
1265
+ }
1266
+ const args = node.arguments.slice(1, slotName !== "" ? node.arguments.length - 1 : void 0).map((x) => cxt.evaluateArgument(x));
1267
+ node.state = { name: nameValue, slotName, args };
1268
+ const store = cxt.get(builtins);
1269
+ store.blockSlotDelayedStack.push(node.state.slotName);
1270
+ debug.trace("entering block definition:", node.state.name);
1271
+ return msgs;
1272
+ },
1273
+ afterParseContent(node, cxt) {
1274
+ if (!node.state) return [];
1275
+ const store = cxt.get(builtins);
1276
+ assert(store.blockSlotDelayedStack.pop() == node.state.slotName);
1277
+ debug.trace("leaving block definition", node.state.name);
1278
+ return [];
1279
+ },
1280
+ expand(node, cxt, immediate) {
1281
+ if (!immediate) return void 0;
1282
+ if (node.state) {
1283
+ if (cxt.config.blockModifiers.has(node.state.name))
1284
+ cxt.config.blockModifiers.remove(node.state.name);
1285
+ cxt.config.blockModifiers.add(
1286
+ customModifier(
1287
+ 7 /* BlockModifier */,
1288
+ node.state.name,
1289
+ node.state.args,
1290
+ node.state.slotName,
1291
+ node.content
1292
+ )
1293
+ );
1294
+ }
1295
+ return [];
1296
+ }
1297
+ });
1298
+
1299
+ // src/builtin/define-inline.ts
1300
+ var DefineInlineMod = new SystemModifierDefinition("define-inline", 0 /* Normal */, {
1301
+ // .define-inline name:args...[:(slot-id)]
1302
+ delayContentExpansion: true,
1303
+ alwaysTryExpand: true,
1304
+ beforeParseContent(node, cxt) {
1305
+ if (node.arguments.length == 0)
1306
+ return [new ArgumentsTooFewMessage(node.head.end - 1, 0)];
1307
+ const msgs = [];
1308
+ const name = node.arguments[0];
1309
+ const nameValue = cxt.evaluateArgument(name);
1310
+ if (cxt.config.inlineModifiers.has(nameValue))
1311
+ msgs.push(new NameAlreadyDefinedMessage(
1312
+ node.start,
1313
+ name.end - name.start,
1314
+ nameValue
1315
+ ));
1316
+ let slotName = "";
1317
+ if (node.arguments.length > 1) {
1318
+ const last = cxt.evaluateArgument(node.arguments.at(-1));
1319
+ slotName = /^\(.+\)$/.test(last) ? last.substring(1, last.length - 1) : "";
1320
+ }
1321
+ const args = node.arguments.slice(1, slotName !== "" ? node.arguments.length - 1 : void 0).map((x) => cxt.evaluateArgument(x));
1322
+ node.state = { name: nameValue, slotName, args };
1323
+ const store = cxt.get(builtins);
1324
+ store.inlineSlotDelayedStack.push(node.state.slotName);
1325
+ debug.trace("entering inline definition:", node.state.name);
1326
+ return msgs;
1327
+ },
1328
+ afterParseContent(node, cxt) {
1329
+ if (!node.state) return [];
1330
+ const store = cxt.get(builtins);
1331
+ assert(store.inlineSlotDelayedStack.pop() == node.state.slotName);
1332
+ debug.trace("leaving inline definition", node.state.name);
1333
+ return [];
1334
+ },
1335
+ prepareExpand(node, cxt) {
1336
+ if (!node.state) return [];
1337
+ const msgs = [];
1338
+ let lastIsParagraph = false;
1339
+ let concat = [];
1340
+ for (const n of node.content) {
1341
+ switch (n.type) {
1342
+ case 1 /* Paragraph */:
1343
+ if (!lastIsParagraph) {
1344
+ lastIsParagraph = true;
1345
+ concat.push(...n.content);
1346
+ continue;
1347
+ }
1348
+ case 2 /* Preformatted */:
1349
+ case 7 /* BlockModifier */:
1350
+ msgs.push(new InlineDefinitonInvalidEntityMessage(n.start, n.end - n.start));
1351
+ break;
1352
+ case 5 /* SystemModifier */:
1353
+ lastIsParagraph = false;
1354
+ concat.push(n);
1355
+ break;
1356
+ default:
1357
+ debug.never(n);
1358
+ }
1359
+ }
1360
+ node.state.definition = concat;
1361
+ return msgs;
1362
+ },
1363
+ expand(node, cxt, immediate) {
1364
+ if (!immediate) return void 0;
1365
+ if (node.state) {
1366
+ if (cxt.config.inlineModifiers.has(node.state.name))
1367
+ cxt.config.inlineModifiers.remove(node.state.name);
1368
+ cxt.config.inlineModifiers.add(
1369
+ customModifier(
1370
+ 6 /* InlineModifier */,
1371
+ node.state.name,
1372
+ node.state.args,
1373
+ node.state.slotName,
1374
+ node.state.definition
1375
+ )
1376
+ );
1377
+ }
1378
+ return [];
1379
+ }
1380
+ });
1381
+
1382
+ // src/builtin/slot.ts
1383
+ function slotModifier(type) {
1384
+ const mod = type == 7 /* BlockModifier */ ? new BlockModifierDefinition("slot", 2 /* Marker */) : new InlineModifierDefinition("slot", 2 /* Marker */);
1385
+ const isInline = type == 6 /* InlineModifier */;
1386
+ mod.alwaysTryExpand = true;
1387
+ mod.prepareExpand = (node, cxt, immediate) => {
1388
+ const store = cxt.get(builtins);
1389
+ const data = isInline ? store.inlineSlotData : store.blockSlotData;
1390
+ const id = node.arguments.length == 1 ? cxt.evaluateArgument(node.arguments[0]) : "";
1391
+ if (data.length == 0) {
1392
+ if (immediate) {
1393
+ node.state = { ok: false };
1394
+ return [new SlotUsedOutsideDefinitionMessage(node.start, node.head.end - node.start)];
1395
+ }
1396
+ return [];
1397
+ }
1398
+ if (node.arguments.length > 1) {
1399
+ if (immediate) {
1400
+ node.state = { ok: false };
1401
+ const start = node.arguments[1].start - 1;
1402
+ return [new ArgumentsTooManyMessage(start, node.head.end - start)];
1403
+ }
1404
+ return [];
1405
+ }
1406
+ const stack = isInline ? store.inlineSlotDelayedStack : store.blockSlotDelayedStack;
1407
+ if (stack.includes(id)) {
1408
+ debug.trace("delaying", id == "" ? "unnamed slot" : "slot: " + id);
1409
+ return [];
1410
+ }
1411
+ if (node.arguments.length == 0) {
1412
+ node.state = { ok: true, data: data.at(-1), index: data.length - 1 };
1413
+ return [];
1414
+ }
1415
+ for (let i = data.length - 1; i >= 0; i--) if (data[i][0] == id) {
1416
+ node.state = { ok: true, data: data[i], index: i };
1417
+ return [];
1418
+ }
1419
+ if (immediate) {
1420
+ node.state = { ok: false };
1421
+ const arg = node.arguments[0];
1422
+ return [new InvalidArgumentMessage(arg.start, arg.end - arg.start, id)];
1423
+ }
1424
+ return [];
1425
+ };
1426
+ mod.expand = (node, cxt) => {
1427
+ if (!node.state) return void 0;
1428
+ if (!node.state.ok) return [];
1429
+ return cloneNodes(node.state.data[1].slotContent);
1430
+ };
1431
+ mod.beforeProcessExpansion = (node, cxt) => {
1432
+ if (!node.state?.ok) return [];
1433
+ const store = cxt.get(builtins);
1434
+ debug.trace("temporarily removed slot data for", node.state.data[1].mod.name);
1435
+ const data = isInline ? store.inlineSlotData : store.blockSlotData;
1436
+ data.splice(node.state.index, 1);
1437
+ return [];
1438
+ };
1439
+ mod.afterProcessExpansion = (node, cxt) => {
1440
+ if (!node.state?.ok) return [];
1441
+ const store = cxt.get(builtins);
1442
+ debug.trace("reinstated slot data for", node.state.data[1].mod.name);
1443
+ const data = isInline ? store.inlineSlotData : store.blockSlotData;
1444
+ data.splice(node.state.index, 0, node.state.data);
1445
+ return [];
1446
+ };
1447
+ return mod;
1448
+ }
1449
+ var SlotBlockMod = slotModifier(7 /* BlockModifier */);
1450
+ var SlotInlineMod = slotModifier(6 /* InlineModifier */);
1451
+
1452
+ // src/builtin/var.ts
1453
+ function resolveId(id, cxt) {
1454
+ const store = cxt.get(builtins);
1455
+ let value = void 0;
1456
+ for (let i = store.inlineSlotData.length - 1; i >= 0; i--) {
1457
+ const [_, data] = store.inlineSlotData[i];
1458
+ if ((value = data.args.get(id)) !== void 0)
1459
+ break;
1460
+ }
1461
+ for (let i = store.blockSlotData.length - 1; i >= 0; i--) {
1462
+ const [_, data] = store.blockSlotData[i];
1463
+ if ((value = data.args.get(id)) !== void 0)
1464
+ break;
1465
+ }
1466
+ if (value === void 0)
1467
+ value = cxt.variables.get(id);
1468
+ return value;
1469
+ }
1470
+ var GetVarInlineMod = new InlineModifierDefinition("$", 2 /* Marker */, {
1471
+ // .$:id
1472
+ prepareExpand(node, cxt) {
1473
+ const check = checkArgumentLength(node, 1);
1474
+ if (check) return [check];
1475
+ const arg = node.arguments[0];
1476
+ const id = cxt.evaluateArgument(arg);
1477
+ if (id == "")
1478
+ return [new InvalidArgumentMessage(arg.start, arg.end - arg.start)];
1479
+ const value = resolveId(id, cxt);
1480
+ if (value === void 0)
1481
+ return [new UndefinedVariableMessage(arg.start, arg.end - arg.start, id)];
1482
+ node.state = { value };
1483
+ return [];
1484
+ },
1485
+ expand(node, cxt) {
1486
+ if (!node.state) return [];
1487
+ return [{ type: 3 /* Text */, content: node.state.value, start: -1, end: -1 }];
1488
+ }
1489
+ });
1490
+ var GetVarInterpolator = new ArgumentInterpolatorDefinition(
1491
+ "$(",
1492
+ ")",
1493
+ (content, cxt) => resolveId(content, cxt) ?? ""
1494
+ );
1495
+ var VarMod = new SystemModifierDefinition("var", 2 /* Marker */, {
1496
+ // .var id:value
1497
+ prepareExpand(node, cxt) {
1498
+ const check = checkArgumentLength(node, 2);
1499
+ if (check) return [check];
1500
+ const arg = node.arguments[0];
1501
+ const argValue = cxt.evaluateArgument(arg);
1502
+ if (argValue == "")
1503
+ return [new InvalidArgumentMessage(arg.start, arg.end - arg.start)];
1504
+ node.state = {
1505
+ id: argValue,
1506
+ value: cxt.evaluateArgument(node.arguments[1])
1507
+ };
1508
+ return [];
1509
+ },
1510
+ expand(node, cxt) {
1511
+ if (node.state) {
1512
+ cxt.variables.set(node.state.id, node.state.value);
1513
+ debug.trace("set variable", node.state.id, "=", node.state.value);
1514
+ }
1515
+ return [];
1516
+ }
1517
+ });
1518
+
1519
+ // src/builtin/builtin.ts
1520
+ var basic = new Configuration();
1521
+ basic.initializers = [initParseContext];
1522
+ basic.systemModifiers.add(DefineBlockMod, DefineInlineMod, VarMod);
1523
+ basic.blockModifiers.add(SlotBlockMod);
1524
+ basic.inlineModifiers.add(SlotInlineMod, GetVarInlineMod);
1525
+ basic.argumentInterpolators.add(GetVarInterpolator);
1526
+ var BuiltinConfiguration = Object.freeze(basic);
1527
+ // Annotate the CommonJS export names for ESM import in node:
1528
+ 0 && (module.exports = {
1529
+ ArgumentInterpolatorDefinition,
1530
+ ArgumentsTooFewMessage,
1531
+ ArgumentsTooManyMessage,
1532
+ BlockModifierDefinition,
1533
+ BuiltinConfiguration,
1534
+ Configuration,
1535
+ ContentShouldBeOnNewlineMessage,
1536
+ Document,
1537
+ ExpectedMessage,
1538
+ InlineDefinitonInvalidEntityMessage,
1539
+ InlineModifierDefinition,
1540
+ InvalidArgumentMessage,
1541
+ MessageSeverity,
1542
+ ModifierFlags,
1543
+ NameAlreadyDefinedMessage,
1544
+ NewBlockShouldBeOnNewlineMessage,
1545
+ NodeType,
1546
+ ParseContext,
1547
+ ReachedRecursionLimitMessage,
1548
+ ReferredMessage,
1549
+ SimpleScanner,
1550
+ SlotUsedOutsideDefinitionMessage,
1551
+ SystemModifierDefinition,
1552
+ UnclosedInlineModifierMessage,
1553
+ UndefinedVariableMessage,
1554
+ UnknownModifierMessage,
1555
+ UnnecessaryNewlineMessage,
1556
+ parse
1557
+ });
1558
+ //# sourceMappingURL=index.js.map