@givelotus/compiler 0.0.0-stage → 0.2.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/README.md +331 -2
- package/artifact-v2.schema.json +58 -0
- package/artifact.schema.json +19 -0
- package/dist/ast.d.ts +292 -0
- package/dist/ast.js +150 -0
- package/dist/bindings.d.ts +6 -0
- package/dist/bindings.js +134 -0
- package/dist/call-runtime.d.ts +84 -0
- package/dist/call-runtime.js +249 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +22 -0
- package/dist/compiler.d.ts +79 -0
- package/dist/compiler.js +125 -0
- package/dist/diagnostics.d.ts +163 -0
- package/dist/diagnostics.js +498 -0
- package/dist/ecash.d.ts +41 -0
- package/dist/ecash.js +190 -0
- package/dist/fees.d.ts +164 -0
- package/dist/fees.js +208 -0
- package/dist/fixture-cli.d.ts +2 -0
- package/dist/fixture-cli.js +41 -0
- package/dist/fixtures.d.ts +68 -0
- package/dist/fixtures.js +46 -0
- package/dist/forth-ir.d.ts +73 -0
- package/dist/forth-ir.js +147 -0
- package/dist/generic-cli.d.ts +2 -0
- package/dist/generic-cli.js +140 -0
- package/dist/generic.d.ts +48 -0
- package/dist/generic.js +2566 -0
- package/dist/lints.d.ts +8 -0
- package/dist/lints.js +204 -0
- package/dist/names.d.ts +1 -0
- package/dist/names.js +7 -0
- package/dist/opcodes.d.ts +154 -0
- package/dist/opcodes.js +162 -0
- package/dist/optimizer.d.ts +58 -0
- package/dist/optimizer.js +786 -0
- package/dist/package-fetch-cli.d.ts +2 -0
- package/dist/package-fetch-cli.js +17 -0
- package/dist/package-lock-cli.d.ts +2 -0
- package/dist/package-lock-cli.js +28 -0
- package/dist/package-sources.d.ts +82 -0
- package/dist/package-sources.js +785 -0
- package/dist/package-update-cli.d.ts +2 -0
- package/dist/package-update-cli.js +20 -0
- package/dist/packages.d.ts +231 -0
- package/dist/packages.js +1324 -0
- package/dist/parser.d.ts +32 -0
- package/dist/parser.js +575 -0
- package/dist/policy.d.ts +83 -0
- package/dist/policy.js +207 -0
- package/dist/runtime.d.ts +58 -0
- package/dist/runtime.js +126 -0
- package/dist/scheduler.d.ts +38 -0
- package/dist/scheduler.js +76 -0
- package/dist/semantic-ir.d.ts +76 -0
- package/dist/semantic-ir.js +231 -0
- package/dist/std.d.ts +27 -0
- package/dist/std.js +282 -0
- package/dist/target-compiler.d.ts +9 -0
- package/dist/target-compiler.js +139 -0
- package/dist/targets.d.ts +53 -0
- package/dist/targets.js +67 -0
- package/dist/token-cli.d.ts +2 -0
- package/dist/token-cli.js +82 -0
- package/dist/token-metadata.d.ts +43 -0
- package/dist/token-metadata.js +166 -0
- package/dist/toml-subset.d.ts +19 -0
- package/dist/toml-subset.js +81 -0
- package/dist/transaction-runtime.d.ts +182 -0
- package/dist/transaction-runtime.js +646 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +3 -0
- package/dist/vm-cost.d.ts +11 -0
- package/dist/vm-cost.js +541 -0
- package/package.json +74 -4
- package/policy-artifact.schema.json +20 -0
- package/std/custody/arbiter-escrow.lotus +20 -0
- package/std/custody/htlc.lotus +15 -0
- package/std/custody/multisig-2of3.lotus +13 -0
- package/std/custody/single-owner-wallet.lotus +9 -0
- package/std/custody/vault-with-recovery.lotus +14 -0
- package/std/defi/amm-pool-v2.lotus +97 -0
- package/std/defi/indexed-limit-order.lotus +37 -0
- package/std/nft/nft-collection.lotus +51 -0
- package/std/nft/royalty-transfer-rules.lotus +38 -0
- package/std/nft/unique-nft.lotus +30 -0
- package/std/tokens/capped-supply-token.lotus +76 -0
- package/std/tokens/fixed-supply-token.lotus +29 -0
- package/std/tokens/lrc20.lotus +26 -0
- package/std/tokens/standard-transfer-rules.lotus +15 -0
- package/std/tokens/stateful-token-merge.lotus +132 -0
- package/std/tokens/upgradable-token-rules.lotus +70 -0
- package/std/tokens/voucher-mint-token.lotus +31 -0
- package/std-pkg/lotus.toml +9 -0
- package/std-pkg/src/lrc20.lotus +38 -0
- package/std-pkg/src/stateful_token.lotus +131 -0
- package/std-pkg/src/upgradable.lotus +68 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/** Source target selection. eCash emits a direct script, never a Lotus policy. */
|
|
2
|
+
import { compileContract, parseModuleSource } from './generic.js';
|
|
3
|
+
import { DiagnosticBag, SourceManager } from './diagnostics.js';
|
|
4
|
+
import { resolveTarget, checkCapabilities } from './targets.js';
|
|
5
|
+
import { validateSemanticProgram } from './semantic-ir.js';
|
|
6
|
+
import { compileEcash } from './ecash.js';
|
|
7
|
+
export function compileTargetContract(source, options, file = '<source>') {
|
|
8
|
+
const sources = new SourceManager();
|
|
9
|
+
sources.add(file, source);
|
|
10
|
+
const bag = new DiagnosticBag(sources, file);
|
|
11
|
+
function fail(code, message, span) { return bag.raise(code, message, span); }
|
|
12
|
+
if (!options || typeof options.contract !== 'string' || !options.bindings || typeof options.bindings !== 'object' || Array.isArray(options.bindings))
|
|
13
|
+
fail('E0601', 'compile options require contract and bindings');
|
|
14
|
+
const target = (() => {
|
|
15
|
+
try {
|
|
16
|
+
return resolveTarget(options.target === undefined ? 'lotus-v2' : options.target);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
return fail('E1200', error.message);
|
|
20
|
+
}
|
|
21
|
+
})();
|
|
22
|
+
if (target.id === 'lotus-v2') {
|
|
23
|
+
if (options.method !== undefined)
|
|
24
|
+
fail('E1202', 'Lotus compilation commits the complete contract policy; method selection is available only for the eCash script target.');
|
|
25
|
+
return compileContract(source, { ...options, target: 'lotus-v2' }, file);
|
|
26
|
+
}
|
|
27
|
+
if (options.optimize === true || (options.optimizerVersion !== undefined && options.optimizerVersion !== 'none'))
|
|
28
|
+
fail('E1203', 'The eCash backend has no optimizer; omit optimize or set optimize:false. Lotus optimizations are not applied to eCash bytecode.');
|
|
29
|
+
const program = parseModuleSource(source, true, file, sources);
|
|
30
|
+
if (program.optimizerVersion !== undefined && program.optimizerVersion !== 'none') {
|
|
31
|
+
fail('E1203', `The eCash backend has no optimizer; source pragma optimizer "${program.optimizerVersion}" is unsupported on eCash.`);
|
|
32
|
+
}
|
|
33
|
+
if (program.imports.length)
|
|
34
|
+
fail('E1203', 'eCash source compilation does not yet link packages or imported helpers.', program.imports[0].span);
|
|
35
|
+
const contract = program.contracts.get(options.contract);
|
|
36
|
+
if (!contract)
|
|
37
|
+
fail('E0605', `unknown contract ${options.contract}`);
|
|
38
|
+
const diagnostic = (error) => fail(error.code.startsWith('semantic-ir-') ? 'E1204' : error.code, error.message, error.span);
|
|
39
|
+
const unsupported = (capability, span) => {
|
|
40
|
+
const [error] = checkCapabilities(target, [{ capability, span }]);
|
|
41
|
+
if (error)
|
|
42
|
+
diagnostic(error);
|
|
43
|
+
fail('E1203', `eCash source lowering for ${capability} is not implemented.`, span);
|
|
44
|
+
};
|
|
45
|
+
if (contract.kind === 'token')
|
|
46
|
+
unsupported('lotus-token', contract.span);
|
|
47
|
+
if (options.method !== undefined && typeof options.method !== 'string')
|
|
48
|
+
fail('E1202', 'selected method must be a string', contract.span);
|
|
49
|
+
if (options.method === undefined && contract.methods.length !== 1)
|
|
50
|
+
fail('E1202', 'eCash requires an explicit selected method when a contract has multiple methods; no dispatcher or combined policy is emitted.', contract.span);
|
|
51
|
+
const method = options.method === undefined ? contract.methods[0] : contract.methods.find(m => m.name === options.method);
|
|
52
|
+
if (!method)
|
|
53
|
+
fail('E1202', `unknown selected method ${contract.name}.${options.method}`, contract.span);
|
|
54
|
+
const type = (value, span) => {
|
|
55
|
+
if (value === 'Bool')
|
|
56
|
+
return { kind: 'bool' };
|
|
57
|
+
if (value === 'Bytes32')
|
|
58
|
+
return { kind: 'bytes', length: 32 };
|
|
59
|
+
const sized = /^Bytes\(([0-9]+)\)$/.exec(value);
|
|
60
|
+
if (sized)
|
|
61
|
+
return fail('E1203', `Source ${value} is a maximum byte bound; the current eCash IR requires exact lengths. Use Bytes32 for an exact 32-byte argument or wait for bounded-byte lowering.`, span);
|
|
62
|
+
if (value === 'Int' || value === 'Amount')
|
|
63
|
+
return unsupported('lotus-int128', span);
|
|
64
|
+
if (value === 'PublicKey' || value === 'Signature')
|
|
65
|
+
return unsupported('transaction-signature', span);
|
|
66
|
+
if (value === 'TokenId')
|
|
67
|
+
return unsupported('lotus-token', span);
|
|
68
|
+
return unsupported('transaction-reflection', span);
|
|
69
|
+
};
|
|
70
|
+
const constants = new Map();
|
|
71
|
+
const bound = options.bindings[contract.name] ?? {};
|
|
72
|
+
if (typeof bound !== 'object' || Array.isArray(bound))
|
|
73
|
+
fail('E0602', `constructor bindings for ${contract.name} must be an object`, contract.span);
|
|
74
|
+
for (const p of contract.params) {
|
|
75
|
+
if (!Object.hasOwn(bound, p.name))
|
|
76
|
+
fail('E0603', `missing constructor binding ${contract.name}.${p.name}`, p.span);
|
|
77
|
+
const t = type(p.type, p.span), value = bound[p.name];
|
|
78
|
+
if (t.kind === 'bool') {
|
|
79
|
+
if (typeof value !== 'boolean')
|
|
80
|
+
fail('E0604', `${contract.name}.${p.name} (Bool) requires a Boolean constructor binding`, p.span);
|
|
81
|
+
constants.set(p.name, { kind: 'bool', value, span: p.span });
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
if (typeof value !== 'string' || !/^(?:[0-9a-fA-F]{2})*$/.test(value) || value.length !== t.length * 2)
|
|
85
|
+
fail('E0604', `${contract.name}.${p.name} (${p.type}) requires exactly ${t.length} bytes of hexadecimal`, p.span);
|
|
86
|
+
constants.set(p.name, { kind: 'bytes', hex: value.toLowerCase(), span: p.span });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const extra = Object.keys(bound).find(key => !constants.has(key));
|
|
90
|
+
if (extra !== undefined)
|
|
91
|
+
fail('E0602', `unexpected constructor binding ${contract.name}.${extra}`, contract.span);
|
|
92
|
+
const args = method.params.map(p => {
|
|
93
|
+
if (constants.has(p.name))
|
|
94
|
+
fail('E0205', `method parameter shadows constructor parameter ${p.name}`, p.span);
|
|
95
|
+
return { name: p.name, type: type(p.type, p.span), span: p.span };
|
|
96
|
+
});
|
|
97
|
+
const expression = (expr) => {
|
|
98
|
+
const span = expr.span;
|
|
99
|
+
if (expr.kind === 'bool')
|
|
100
|
+
return { kind: 'bool', value: expr.value === 'true', span };
|
|
101
|
+
if (expr.kind === 'name') {
|
|
102
|
+
const constant = constants.get(expr.value);
|
|
103
|
+
return constant ? { ...constant, span } : { kind: 'arg', name: expr.value, span };
|
|
104
|
+
}
|
|
105
|
+
if (expr.kind === 'number')
|
|
106
|
+
return unsupported('lotus-int128', span);
|
|
107
|
+
if (expr.kind === 'binary' && expr.value === '==')
|
|
108
|
+
return { kind: 'equal', left: expression(expr.left), right: expression(expr.right), span };
|
|
109
|
+
if (expr.kind === 'call') {
|
|
110
|
+
if ((expr.value === 'sha256' || expr.value === 'hash256') && expr.args?.length === 1)
|
|
111
|
+
return { kind: expr.value, value: expression(expr.args[0]), span };
|
|
112
|
+
if (expr.value === 'checksig')
|
|
113
|
+
return unsupported('transaction-signature', span);
|
|
114
|
+
if (program.helpers.has(expr.value))
|
|
115
|
+
fail('E1203', `eCash source helper inlining is not implemented; selected call ${expr.value} must be expressed in the method body. Lotus helper compilation remains available.`, span);
|
|
116
|
+
if (/^(input|output|utxo|branch|leaf|contract|check_lock|check_sequence|merkle)/i.test(expr.value))
|
|
117
|
+
return unsupported('transaction-reflection', span);
|
|
118
|
+
fail('E1203', `function ${expr.value} is not implemented by the eCash byte/hash source slice`, span);
|
|
119
|
+
}
|
|
120
|
+
fail('E1203', `operator ${expr.value ?? expr.kind} is not implemented by the eCash byte/hash source slice; no Lotus instruction is substituted`, span);
|
|
121
|
+
};
|
|
122
|
+
const statements = (body) => body.map(stmt => {
|
|
123
|
+
if (stmt.kind === 'require')
|
|
124
|
+
return { kind: 'require', condition: expression(stmt.expr), span: stmt.span };
|
|
125
|
+
if (stmt.kind === 'if')
|
|
126
|
+
return { kind: 'if', condition: expression(stmt.expr), then: statements(stmt.then), otherwise: statements(stmt.otherwise), span: stmt.span };
|
|
127
|
+
if (stmt.kind === 'for')
|
|
128
|
+
return unsupported('lotus-loop', stmt.span);
|
|
129
|
+
fail('E1203', 'eCash source assignments are not implemented in the portable expression slice.', stmt.span);
|
|
130
|
+
});
|
|
131
|
+
const ir = { schema: 'lotus/semantic-ir/1', entrypoint: method.name, args, body: statements(method.body), span: method.span };
|
|
132
|
+
const checked = validateSemanticProgram(ir);
|
|
133
|
+
if (!checked.ok)
|
|
134
|
+
diagnostic(checked.diagnostics[0]);
|
|
135
|
+
const result = compileEcash(ir);
|
|
136
|
+
if (!result.ok)
|
|
137
|
+
return diagnostic(result.diagnostics[0]);
|
|
138
|
+
return result.artifact;
|
|
139
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Compiler target capabilities are implemented slices, not network support claims. */
|
|
2
|
+
export type TargetId = 'lotus-v2' | 'ecash';
|
|
3
|
+
export type SemanticCapability = 'bytes' | 'bool' | 'sha256' | 'hash256' | 'byte-equality' | 'require' | 'if' | 'lotus-int128' | 'transaction-signature' | 'transaction-reflection' | 'lotus-loop' | 'lotus-token';
|
|
4
|
+
export type SourceSpan = {
|
|
5
|
+
start: number;
|
|
6
|
+
end: number;
|
|
7
|
+
file?: string;
|
|
8
|
+
};
|
|
9
|
+
export type TargetDiagnostic = {
|
|
10
|
+
code: string;
|
|
11
|
+
message: string;
|
|
12
|
+
span?: SourceSpan;
|
|
13
|
+
capability?: string;
|
|
14
|
+
};
|
|
15
|
+
export type CapabilityRequirement = {
|
|
16
|
+
capability: SemanticCapability;
|
|
17
|
+
span?: SourceSpan;
|
|
18
|
+
};
|
|
19
|
+
export type TargetDescriptor = {
|
|
20
|
+
readonly id: TargetId;
|
|
21
|
+
readonly revision: string;
|
|
22
|
+
readonly profile: string;
|
|
23
|
+
readonly capabilities: readonly SemanticCapability[];
|
|
24
|
+
readonly limits: Readonly<{
|
|
25
|
+
maxScriptBytes: number;
|
|
26
|
+
maxElementBytes: number;
|
|
27
|
+
maxStackItems: number | null;
|
|
28
|
+
maxOps: number;
|
|
29
|
+
}>;
|
|
30
|
+
readonly capabilityScope: 'compiler-implemented';
|
|
31
|
+
/** null stack limit requires the caller's explicit invocation profile. */
|
|
32
|
+
readonly limitsScope: 'compiler' | 'vm-consensus';
|
|
33
|
+
readonly semantics: Readonly<{
|
|
34
|
+
booleanEncoding: 'canonical-int128-le' | 'minimal-scriptnum';
|
|
35
|
+
booleanConsumers: 'canonical-zero-or-one' | 'script-truthiness-with-minimalif';
|
|
36
|
+
integerModel: 'signed-int128' | 'not-supported-by-compiler';
|
|
37
|
+
signatureModel: 'lotus-p01' | 'not-supported-by-compiler';
|
|
38
|
+
entrypoint: 'merkle-branch-per-method' | 'single-method-script';
|
|
39
|
+
commitmentModel: 'lotus-branches-and-paths' | 'external-script-wrapper-required';
|
|
40
|
+
}>;
|
|
41
|
+
/** Exact pin's STANDARD_SCRIPT_VERIFY_FLAGS plus MINIMALIF; research profile, not network defaults. */
|
|
42
|
+
readonly evaluationFlags: readonly string[];
|
|
43
|
+
readonly maxMethods: number;
|
|
44
|
+
readonly evaluationFlagPolicy: 'caller-invocation-profile' | 'standard-plus-minimalif-research';
|
|
45
|
+
readonly sourceTree?: string;
|
|
46
|
+
};
|
|
47
|
+
export declare const ECASH_REVISION = "1fb7db17c176cdea8a2c60d887891589382ee4e3";
|
|
48
|
+
/** Exact identifiers only: aliases and inherited defaults are caller policy. */
|
|
49
|
+
export declare function resolveTarget(id: string): TargetDescriptor;
|
|
50
|
+
/** Reject semantic obligations before bytecode emission; preserve occurrence spans. */
|
|
51
|
+
export declare function checkCapabilities(target: TargetDescriptor, requirements: readonly CapabilityRequirement[]): TargetDiagnostic[];
|
|
52
|
+
/** eCash method dispatch must be designed explicitly, never inherited from Lotus. */
|
|
53
|
+
export declare function checkEntrypoint(target: TargetDescriptor, methodCount: number, span?: SourceSpan): TargetDiagnostic[];
|
package/dist/targets.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export const ECASH_REVISION = '1fb7db17c176cdea8a2c60d887891589382ee4e3';
|
|
2
|
+
const portable = ['bytes', 'bool', 'sha256', 'hash256', 'byte-equality', 'require', 'if'];
|
|
3
|
+
const lotusOnly = ['lotus-int128', 'transaction-signature', 'transaction-reflection', 'lotus-loop', 'lotus-token'];
|
|
4
|
+
const lotus = Object.freeze({
|
|
5
|
+
id: 'lotus-v2', revision: 'P01-P02-P03-candidate-2026-10-14', profile: 'P01-P02-P03-candidate-2026-10-14',
|
|
6
|
+
capabilities: Object.freeze([...portable, ...lotusOnly]), capabilityScope: 'compiler-implemented', limitsScope: 'compiler',
|
|
7
|
+
limits: Object.freeze({ maxScriptBytes: 8192, maxElementBytes: 8192, maxStackItems: null, maxOps: 4096 }),
|
|
8
|
+
semantics: Object.freeze({ booleanEncoding: 'canonical-int128-le', booleanConsumers: 'canonical-zero-or-one',
|
|
9
|
+
integerModel: 'signed-int128', signatureModel: 'lotus-p01', entrypoint: 'merkle-branch-per-method',
|
|
10
|
+
commitmentModel: 'lotus-branches-and-paths' }),
|
|
11
|
+
evaluationFlags: Object.freeze([]), maxMethods: 16, evaluationFlagPolicy: 'caller-invocation-profile',
|
|
12
|
+
});
|
|
13
|
+
const ecash = Object.freeze({
|
|
14
|
+
id: 'ecash', revision: ECASH_REVISION, profile: 'ecash-script-minimal-cleanstack-1fb7db17',
|
|
15
|
+
capabilities: Object.freeze([...portable]), capabilityScope: 'compiler-implemented', limitsScope: 'vm-consensus',
|
|
16
|
+
limits: Object.freeze({ maxScriptBytes: 10000, maxElementBytes: 520, maxStackItems: 1000, maxOps: 201 }),
|
|
17
|
+
semantics: Object.freeze({ booleanEncoding: 'minimal-scriptnum', booleanConsumers: 'script-truthiness-with-minimalif',
|
|
18
|
+
integerModel: 'not-supported-by-compiler', signatureModel: 'not-supported-by-compiler',
|
|
19
|
+
entrypoint: 'single-method-script', commitmentModel: 'external-script-wrapper-required' }),
|
|
20
|
+
maxMethods: 1, evaluationFlagPolicy: 'standard-plus-minimalif-research',
|
|
21
|
+
sourceTree: 'b2e4a0a9f57c593129028352d5dbb0c4ff294cdb',
|
|
22
|
+
evaluationFlags: Object.freeze(['P2SH', 'STRICTENC', 'SIGHASH_FORKID', 'LOW_S', 'NULLFAIL', 'MINIMALDATA',
|
|
23
|
+
'SCHNORR_MULTISIG', 'ENFORCE_SIGCHECKS', 'DERSIG', 'SIGPUSHONLY', 'DISCOURAGE_UPGRADABLE_NOPS',
|
|
24
|
+
'CLEANSTACK', 'CHECKLOCKTIMEVERIFY', 'CHECKSEQUENCEVERIFY', 'DISALLOW_SEGWIT_RECOVERY', 'INPUT_SIGCHECKS', 'MINIMALIF']),
|
|
25
|
+
});
|
|
26
|
+
/** Exact identifiers only: aliases and inherited defaults are caller policy. */
|
|
27
|
+
export function resolveTarget(id) {
|
|
28
|
+
if (id === 'lotus-v2')
|
|
29
|
+
return lotus;
|
|
30
|
+
if (id === 'ecash')
|
|
31
|
+
return ecash;
|
|
32
|
+
throw new Error(`Unknown compiler target ${JSON.stringify(id)}; expected lotus-v2 or ecash`);
|
|
33
|
+
}
|
|
34
|
+
const ecashReasons = Object.freeze({
|
|
35
|
+
'lotus-int128': 'Lotus Int requires exact sixteen-byte signed int128 arithmetic; the eCash compiler slice has no equivalent integer lowering.',
|
|
36
|
+
'transaction-signature': 'Lotus transaction-signature semantics require the P01 authenticated message and key/signature ABI; eCash uses a different transaction/signature ABI and its signing lowering is not implemented.',
|
|
37
|
+
'transaction-reflection': 'Lotus transaction reflection requires authenticated input/output and branch/path semantics; equivalent eCash compiler lowering is not implemented.',
|
|
38
|
+
'lotus-loop': 'Lotus input/output enumeration requires transaction-context iteration; the eCash compiler slice implements no equivalent loop lowering.',
|
|
39
|
+
'lotus-token': 'Lotus token mint/spend semantics and continuation commitments are not implemented by the eCash compiler slice.',
|
|
40
|
+
});
|
|
41
|
+
/** Reject semantic obligations before bytecode emission; preserve occurrence spans. */
|
|
42
|
+
export function checkCapabilities(target, requirements) {
|
|
43
|
+
return requirements.flatMap(requirement => {
|
|
44
|
+
if (target.capabilities.includes(requirement.capability))
|
|
45
|
+
return [];
|
|
46
|
+
const reason = target.id === 'ecash' && Object.hasOwn(ecashReasons, requirement.capability)
|
|
47
|
+
? ecashReasons[requirement.capability]
|
|
48
|
+
: `Capability ${JSON.stringify(requirement.capability)} is not implemented by target ${target.id}.`;
|
|
49
|
+
return [{ code: 'E1201', message: `${target.id} (${target.revision}): ${reason}`,
|
|
50
|
+
...(requirement.span ? { span: { ...requirement.span } } : {}), capability: requirement.capability }];
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/** eCash method dispatch must be designed explicitly, never inherited from Lotus. */
|
|
54
|
+
export function checkEntrypoint(target, methodCount, span) {
|
|
55
|
+
if (!Number.isSafeInteger(methodCount) || methodCount < 1)
|
|
56
|
+
return [{ code: 'E1202',
|
|
57
|
+
message: 'A target entrypoint requires a positive safe integer method count.', ...(span ? { span: { ...span } } : {}) }];
|
|
58
|
+
if (target.semantics.entrypoint === 'single-method-script' && methodCount !== 1)
|
|
59
|
+
return [{ code: 'E1202',
|
|
60
|
+
message: `${target.id} emits one method script; ${methodCount} methods require an explicit selector/dispatch ABI, which is not implemented. Lotus branch proofs cannot select eCash entrypoints.`,
|
|
61
|
+
...(span ? { span: { ...span } } : {}) }];
|
|
62
|
+
if (methodCount > target.maxMethods)
|
|
63
|
+
return [{ code: 'E1202',
|
|
64
|
+
message: `${target.id} compiler supports at most ${target.maxMethods} methods; received ${methodCount}.`,
|
|
65
|
+
...(span ? { span: { ...span } } : {}) }];
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `lotus-token` CLI: instantiate and verify LRC-20 token bundles with
|
|
4
|
+
* cryptographically committed `lotus/token-metadata/1` manifests.
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { createLrc20TokenBundle, verifyTokenMetadataBundle, } from './token-metadata.js';
|
|
8
|
+
function usage() {
|
|
9
|
+
console.error([
|
|
10
|
+
'Usage:',
|
|
11
|
+
' lotus-token init --name <name> --symbol <SYM> --decimals <0..18> --issuer <64-hex> [--rules <64-hex>] [--description <text>] [--website <https://...>] [--icon-uri <uri>] [--out <file.json>]',
|
|
12
|
+
' lotus-token verify <bundle.json>',
|
|
13
|
+
].join('\n'));
|
|
14
|
+
process.exit(1);
|
|
15
|
+
}
|
|
16
|
+
function flag(args, name) {
|
|
17
|
+
const idx = args.indexOf(name);
|
|
18
|
+
if (idx === -1)
|
|
19
|
+
return undefined;
|
|
20
|
+
const val = args[idx + 1];
|
|
21
|
+
if (val === undefined || val.startsWith('--'))
|
|
22
|
+
throw new Error(`missing value for ${name}`);
|
|
23
|
+
return val;
|
|
24
|
+
}
|
|
25
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
26
|
+
if (!cmd || cmd === '--help' || cmd === '-h')
|
|
27
|
+
usage();
|
|
28
|
+
try {
|
|
29
|
+
if (cmd === 'init') {
|
|
30
|
+
const name = flag(rest, '--name');
|
|
31
|
+
const symbol = flag(rest, '--symbol');
|
|
32
|
+
const decimalsRaw = flag(rest, '--decimals');
|
|
33
|
+
const issuer = flag(rest, '--issuer');
|
|
34
|
+
if (!name || !symbol || decimalsRaw === undefined || !issuer)
|
|
35
|
+
usage();
|
|
36
|
+
const decimals = Number(decimalsRaw);
|
|
37
|
+
const metadata = {
|
|
38
|
+
name,
|
|
39
|
+
symbol,
|
|
40
|
+
decimals,
|
|
41
|
+
...(flag(rest, '--description') ? { description: flag(rest, '--description') } : {}),
|
|
42
|
+
...(flag(rest, '--website') ? { website: flag(rest, '--website') } : {}),
|
|
43
|
+
...(flag(rest, '--icon-uri') ? { iconUri: flag(rest, '--icon-uri') } : {}),
|
|
44
|
+
...(flag(rest, '--icon-blake3') ? { iconBlake3: flag(rest, '--icon-blake3') } : {}),
|
|
45
|
+
};
|
|
46
|
+
const bundle = createLrc20TokenBundle({
|
|
47
|
+
metadata,
|
|
48
|
+
issuer,
|
|
49
|
+
transferRulesRoot: flag(rest, '--rules'),
|
|
50
|
+
});
|
|
51
|
+
const json = `${JSON.stringify(bundle, null, 2)}\n`;
|
|
52
|
+
const outPath = flag(rest, '--out');
|
|
53
|
+
if (outPath) {
|
|
54
|
+
writeFileSync(outPath, json, 'utf8');
|
|
55
|
+
console.log(`Wrote LRC-20 token bundle to ${outPath}`);
|
|
56
|
+
console.log(`token_id: ${bundle.tokenId}`);
|
|
57
|
+
console.log(`metadata_hash: ${bundle.metadataHash}`);
|
|
58
|
+
console.log(`rules_root: ${bundle.transferRulesRoot}`);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
process.stdout.write(json);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
else if (cmd === 'verify') {
|
|
65
|
+
const file = rest[0];
|
|
66
|
+
if (!file)
|
|
67
|
+
usage();
|
|
68
|
+
const raw = JSON.parse(readFileSync(file, 'utf8'));
|
|
69
|
+
const res = verifyTokenMetadataBundle(raw);
|
|
70
|
+
console.log(`OK ${res.metadata.symbol} (${res.metadata.name}, decimals=${res.metadata.decimals})`);
|
|
71
|
+
console.log(`token_id: ${res.tokenId}`);
|
|
72
|
+
console.log(`metadata_hash: ${res.metadataHash}`);
|
|
73
|
+
console.log(`rules_root: ${res.transferRulesRoot}`);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
usage();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
console.error(`lotus-token error: ${err.message}`);
|
|
81
|
+
process.exit(1);
|
|
82
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type ContractArtifact } from './generic.js';
|
|
2
|
+
export declare const TOKEN_METADATA_SCHEMA: "lotus/token-metadata/1";
|
|
3
|
+
export declare const TOKEN_BUNDLE_SCHEMA: "lotus/token-bundle/1";
|
|
4
|
+
export interface TokenMetadataInput {
|
|
5
|
+
readonly name: string;
|
|
6
|
+
readonly symbol: string;
|
|
7
|
+
readonly decimals: number;
|
|
8
|
+
readonly standard?: 'LRC-20' | 'LRC-721';
|
|
9
|
+
readonly description?: string;
|
|
10
|
+
readonly website?: string;
|
|
11
|
+
readonly iconUri?: string;
|
|
12
|
+
readonly iconBlake3?: string;
|
|
13
|
+
readonly authorityPubkey?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface TokenMetadata extends TokenMetadataInput {
|
|
16
|
+
readonly schema: typeof TOKEN_METADATA_SCHEMA;
|
|
17
|
+
readonly standard: 'LRC-20' | 'LRC-721';
|
|
18
|
+
}
|
|
19
|
+
export interface Lrc20TokenBundle {
|
|
20
|
+
readonly schema: typeof TOKEN_BUNDLE_SCHEMA;
|
|
21
|
+
readonly tokenId: string;
|
|
22
|
+
readonly metadataHash: string;
|
|
23
|
+
readonly transferRulesRoot: string;
|
|
24
|
+
readonly metadata: TokenMetadata;
|
|
25
|
+
readonly canonicalMetadataJson: string;
|
|
26
|
+
readonly mintArtifact: ContractArtifact;
|
|
27
|
+
}
|
|
28
|
+
export declare function validateTokenMetadata(input: TokenMetadataInput): TokenMetadata;
|
|
29
|
+
export declare function canonicalizeTokenMetadata(input: TokenMetadataInput): string;
|
|
30
|
+
export declare function hashTokenMetadata(input: TokenMetadataInput): string;
|
|
31
|
+
export interface CreateLrc20TokenOptions {
|
|
32
|
+
readonly metadata: TokenMetadataInput;
|
|
33
|
+
readonly issuer: string;
|
|
34
|
+
readonly transferRulesRoot?: string;
|
|
35
|
+
}
|
|
36
|
+
export declare function createLrc20TokenBundle(options: CreateLrc20TokenOptions): Lrc20TokenBundle;
|
|
37
|
+
export declare function verifyTokenMetadataBundle(bundle: Lrc20TokenBundle): {
|
|
38
|
+
readonly ok: true;
|
|
39
|
+
readonly tokenId: string;
|
|
40
|
+
readonly metadataHash: string;
|
|
41
|
+
readonly transferRulesRoot: string;
|
|
42
|
+
readonly metadata: TokenMetadata;
|
|
43
|
+
};
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical Lotus Token Metadata & Publishing Standard (`lotus/token-metadata/1`).
|
|
3
|
+
*
|
|
4
|
+
* Binds human-readable token metadata (name, symbol, decimals, icon, URI)
|
|
5
|
+
* cryptographically into the token's `token_id` via `BLAKE3(canonical_json)`
|
|
6
|
+
* committed in the mint contract's `metadata_hash` constructor parameter.
|
|
7
|
+
*/
|
|
8
|
+
import { blake3 } from '@noble/hashes/blake3';
|
|
9
|
+
import { hex } from './compiler.js';
|
|
10
|
+
import { assertContractArtifact } from './call-runtime.js';
|
|
11
|
+
import { verifyArtifactSource } from './generic.js';
|
|
12
|
+
import { compileStandardContract, UNIVERSAL_STANDARD_TRANSFER_RULES_ROOT, } from './std.js';
|
|
13
|
+
export const TOKEN_METADATA_SCHEMA = 'lotus/token-metadata/1';
|
|
14
|
+
export const TOKEN_BUNDLE_SCHEMA = 'lotus/token-bundle/1';
|
|
15
|
+
const HEX_32_RE = /^[0-9a-f]{64}$/;
|
|
16
|
+
const SYMBOL_RE = /^[A-Z0-9][A-Z0-9._-]{0,15}$/;
|
|
17
|
+
const CONTROL_CHAR_RE = /[\u0000-\u001f\u007f]/;
|
|
18
|
+
function assertCleanString(value, field, minLen, maxLen) {
|
|
19
|
+
if (typeof value !== 'string')
|
|
20
|
+
throw new Error(`${field} must be a string`);
|
|
21
|
+
if (value !== value.trim())
|
|
22
|
+
throw new Error(`${field} must not have leading or trailing whitespace`);
|
|
23
|
+
if (CONTROL_CHAR_RE.test(value))
|
|
24
|
+
throw new Error(`${field} must not contain control characters`);
|
|
25
|
+
const len = [...value].length;
|
|
26
|
+
if (len < minLen || len > maxLen)
|
|
27
|
+
throw new Error(`${field} length must be ${minLen}..${maxLen} characters`);
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
export function validateTokenMetadata(input) {
|
|
31
|
+
if (!input || typeof input !== 'object')
|
|
32
|
+
throw new Error('token metadata must be an object');
|
|
33
|
+
const name = assertCleanString(input.name, 'name', 1, 64);
|
|
34
|
+
const symbol = assertCleanString(input.symbol, 'symbol', 1, 16);
|
|
35
|
+
if (!SYMBOL_RE.test(symbol)) {
|
|
36
|
+
throw new Error('symbol must match /^[A-Z0-9][A-Z0-9._-]{0,15}$/');
|
|
37
|
+
}
|
|
38
|
+
if (!Number.isInteger(input.decimals) || input.decimals < 0 || input.decimals > 18) {
|
|
39
|
+
throw new Error('decimals must be an integer between 0 and 18');
|
|
40
|
+
}
|
|
41
|
+
const standard = input.standard ?? 'LRC-20';
|
|
42
|
+
if (standard !== 'LRC-20' && standard !== 'LRC-721') {
|
|
43
|
+
throw new Error('standard must be "LRC-20" or "LRC-721"');
|
|
44
|
+
}
|
|
45
|
+
if (standard === 'LRC-721' && input.decimals !== 0) {
|
|
46
|
+
throw new Error('LRC-721 metadata requires decimals === 0');
|
|
47
|
+
}
|
|
48
|
+
const out = {
|
|
49
|
+
schema: TOKEN_METADATA_SCHEMA,
|
|
50
|
+
standard,
|
|
51
|
+
name,
|
|
52
|
+
symbol,
|
|
53
|
+
decimals: input.decimals,
|
|
54
|
+
};
|
|
55
|
+
if (input.description !== undefined) {
|
|
56
|
+
out.description = assertCleanString(input.description, 'description', 1, 512);
|
|
57
|
+
}
|
|
58
|
+
if (input.website !== undefined) {
|
|
59
|
+
const uri = assertCleanString(input.website, 'website', 8, 256);
|
|
60
|
+
if (!uri.startsWith('https://'))
|
|
61
|
+
throw new Error('website must use https://');
|
|
62
|
+
out.website = uri;
|
|
63
|
+
}
|
|
64
|
+
if (input.iconUri !== undefined) {
|
|
65
|
+
const uri = assertCleanString(input.iconUri, 'iconUri', 7, 256);
|
|
66
|
+
if (!uri.startsWith('https://') && !uri.startsWith('ipfs://')) {
|
|
67
|
+
throw new Error('iconUri must use https:// or ipfs://');
|
|
68
|
+
}
|
|
69
|
+
out.iconUri = uri;
|
|
70
|
+
}
|
|
71
|
+
if (input.iconBlake3 !== undefined) {
|
|
72
|
+
if (typeof input.iconBlake3 !== 'string' || !HEX_32_RE.test(input.iconBlake3)) {
|
|
73
|
+
throw new Error('iconBlake3 must be 64 lowercase hex characters');
|
|
74
|
+
}
|
|
75
|
+
out.iconBlake3 = input.iconBlake3;
|
|
76
|
+
}
|
|
77
|
+
if (input.authorityPubkey !== undefined) {
|
|
78
|
+
if (typeof input.authorityPubkey !== 'string' || !HEX_32_RE.test(input.authorityPubkey)) {
|
|
79
|
+
throw new Error('authorityPubkey must be 64 lowercase hex characters (32-byte x-only pubkey)');
|
|
80
|
+
}
|
|
81
|
+
out.authorityPubkey = input.authorityPubkey;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
function canonicalJsonValue(value) {
|
|
86
|
+
if (value === null || typeof value !== 'object')
|
|
87
|
+
return JSON.stringify(value);
|
|
88
|
+
if (Array.isArray(value))
|
|
89
|
+
return `[${value.map(canonicalJsonValue).join(',')}]`;
|
|
90
|
+
const entries = Object.entries(value)
|
|
91
|
+
.filter(([, v]) => v !== undefined)
|
|
92
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
93
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJsonValue(v)}`).join(',')}}`;
|
|
94
|
+
}
|
|
95
|
+
export function canonicalizeTokenMetadata(input) {
|
|
96
|
+
const validated = validateTokenMetadata(input);
|
|
97
|
+
return canonicalJsonValue(validated);
|
|
98
|
+
}
|
|
99
|
+
export function hashTokenMetadata(input) {
|
|
100
|
+
const canonical = canonicalizeTokenMetadata(input);
|
|
101
|
+
return hex(blake3(new TextEncoder().encode(canonical)));
|
|
102
|
+
}
|
|
103
|
+
export function createLrc20TokenBundle(options) {
|
|
104
|
+
if (typeof options.issuer !== 'string' || !HEX_32_RE.test(options.issuer)) {
|
|
105
|
+
throw new Error('issuer must be 64 lowercase hex characters (32-byte x-only pubkey)');
|
|
106
|
+
}
|
|
107
|
+
const transferRulesRoot = (options.transferRulesRoot ?? UNIVERSAL_STANDARD_TRANSFER_RULES_ROOT).toLowerCase();
|
|
108
|
+
if (!HEX_32_RE.test(transferRulesRoot)) {
|
|
109
|
+
throw new Error('transferRulesRoot must be 64 lowercase hex characters');
|
|
110
|
+
}
|
|
111
|
+
const metadata = validateTokenMetadata({ ...options.metadata, standard: options.metadata.standard ?? 'LRC-20' });
|
|
112
|
+
const canonicalMetadataJson = canonicalizeTokenMetadata(metadata);
|
|
113
|
+
const metadataHash = hex(blake3(new TextEncoder().encode(canonicalMetadataJson)));
|
|
114
|
+
const { artifact: mintArtifact } = compileStandardContract('std/tokens/lrc20', {
|
|
115
|
+
issuer: options.issuer,
|
|
116
|
+
metadata_hash: metadataHash,
|
|
117
|
+
transfer_rules: transferRulesRoot,
|
|
118
|
+
});
|
|
119
|
+
const tokenId = mintArtifact.methods[0].root;
|
|
120
|
+
return {
|
|
121
|
+
schema: TOKEN_BUNDLE_SCHEMA,
|
|
122
|
+
tokenId,
|
|
123
|
+
metadataHash,
|
|
124
|
+
transferRulesRoot,
|
|
125
|
+
metadata,
|
|
126
|
+
canonicalMetadataJson,
|
|
127
|
+
mintArtifact,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
export function verifyTokenMetadataBundle(bundle) {
|
|
131
|
+
if (!bundle || typeof bundle !== 'object')
|
|
132
|
+
throw new Error('bundle must be an object');
|
|
133
|
+
if (bundle.schema !== TOKEN_BUNDLE_SCHEMA) {
|
|
134
|
+
throw new Error(`expected bundle schema ${TOKEN_BUNDLE_SCHEMA}, got ${String(bundle.schema)}`);
|
|
135
|
+
}
|
|
136
|
+
const metadata = validateTokenMetadata(bundle.metadata);
|
|
137
|
+
const canonical = canonicalizeTokenMetadata(metadata);
|
|
138
|
+
if (bundle.canonicalMetadataJson !== canonical) {
|
|
139
|
+
throw new Error('canonicalMetadataJson does not match canonicalized metadata');
|
|
140
|
+
}
|
|
141
|
+
const computedHash = hex(blake3(new TextEncoder().encode(canonical)));
|
|
142
|
+
if (bundle.metadataHash !== computedHash) {
|
|
143
|
+
throw new Error(`metadataHash mismatch: expected ${computedHash}, got ${bundle.metadataHash}`);
|
|
144
|
+
}
|
|
145
|
+
assertContractArtifact(bundle.mintArtifact);
|
|
146
|
+
verifyArtifactSource(bundle.mintArtifact);
|
|
147
|
+
const mintRoot = bundle.mintArtifact.methods[0]?.root;
|
|
148
|
+
if (!mintRoot || mintRoot !== bundle.tokenId) {
|
|
149
|
+
throw new Error(`tokenId mismatch: artifact root ${String(mintRoot)} !== ${bundle.tokenId}`);
|
|
150
|
+
}
|
|
151
|
+
const boundHash = bundle.mintArtifact.bindings.find((b) => b.name === 'metadata_hash')?.value;
|
|
152
|
+
if (boundHash !== computedHash) {
|
|
153
|
+
throw new Error(`mintArtifact metadata_hash binding (${String(boundHash)}) does not match computed metadataHash (${computedHash})`);
|
|
154
|
+
}
|
|
155
|
+
const boundRules = bundle.mintArtifact.bindings.find((b) => b.name === 'transfer_rules')?.value;
|
|
156
|
+
if (boundRules !== bundle.transferRulesRoot) {
|
|
157
|
+
throw new Error(`mintArtifact transfer_rules binding (${String(boundRules)}) does not match transferRulesRoot (${bundle.transferRulesRoot})`);
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
ok: true,
|
|
161
|
+
tokenId: bundle.tokenId,
|
|
162
|
+
metadataHash: computedHash,
|
|
163
|
+
transferRulesRoot: bundle.transferRulesRoot,
|
|
164
|
+
metadata,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strict parser for the tiny TOML subset used by `lotus.toml` (CABI-07).
|
|
3
|
+
*
|
|
4
|
+
* Accepted (every accepted file is also valid TOML 1.0):
|
|
5
|
+
* - UTF-8 text without BOM, LF or CRLF line endings, no tab characters or control bytes;
|
|
6
|
+
* - blank lines and full-line or trailing `#` comments;
|
|
7
|
+
* - `[table]` headers with a bare key (no dotted, array or inline tables);
|
|
8
|
+
* - `key = "string"` and `key = ["a", "b"]` (single line, optional trailing comma);
|
|
9
|
+
* - bare keys `[A-Za-z0-9_-]+` or quoted basic-string keys (no escapes);
|
|
10
|
+
* - basic strings without escapes, quotes or control characters.
|
|
11
|
+
*
|
|
12
|
+
* Everything else (integers, booleans, escapes, multi-line values, dotted keys,
|
|
13
|
+
* duplicate keys/tables, keys before the first table) is rejected rather than
|
|
14
|
+
* approximated, so two parsers cannot disagree about an accepted manifest.
|
|
15
|
+
* Quoted keys are basic strings, which TOML already allows.
|
|
16
|
+
*/
|
|
17
|
+
export type TomlValue = string | string[];
|
|
18
|
+
export type TomlDocument = Map<string, Map<string, TomlValue>>;
|
|
19
|
+
export declare function parseTomlSubset(text: string, file: string): TomlDocument;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const KEY = /^[A-Za-z0-9_-]+$/;
|
|
2
|
+
const STRING = /^"([^"\\\x00-\x1f\x7f]*)"/;
|
|
3
|
+
export function parseTomlSubset(text, file) {
|
|
4
|
+
if (text.startsWith('\uFEFF'))
|
|
5
|
+
throw new Error(`${file}: byte-order mark is not allowed`);
|
|
6
|
+
const doc = new Map();
|
|
7
|
+
let table;
|
|
8
|
+
const lines = text.split('\n');
|
|
9
|
+
lines.forEach((raw, index) => {
|
|
10
|
+
const lineNo = index + 1;
|
|
11
|
+
const fail = (message) => { throw new Error(`${file}:${lineNo}: ${message}`); };
|
|
12
|
+
const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
|
|
13
|
+
if (/[\x00-\x08\x0a-\x1f\x7f\t]/.test(line))
|
|
14
|
+
fail('control or tab character');
|
|
15
|
+
let rest = line.trim();
|
|
16
|
+
if (rest === '' || rest.startsWith('#'))
|
|
17
|
+
return;
|
|
18
|
+
const header = /^\[([A-Za-z0-9_-]+)\]\s*(#.*)?$/.exec(rest);
|
|
19
|
+
if (header) {
|
|
20
|
+
const name = header[1];
|
|
21
|
+
if (doc.has(name))
|
|
22
|
+
fail(`duplicate table [${name}]`);
|
|
23
|
+
table = new Map();
|
|
24
|
+
doc.set(name, table);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const eq = rest.indexOf('=');
|
|
28
|
+
if (eq < 0)
|
|
29
|
+
fail('expected key = value');
|
|
30
|
+
const rawKey = rest.slice(0, eq).trim();
|
|
31
|
+
let key;
|
|
32
|
+
if (rawKey.startsWith('"')) {
|
|
33
|
+
const quoted = STRING.exec(rawKey);
|
|
34
|
+
key = quoted?.[0].length === rawKey.length ? quoted[1] ?? '' : '';
|
|
35
|
+
if (!key)
|
|
36
|
+
fail('unsupported key (quoted keys are basic strings without escapes)');
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
if (!KEY.test(rawKey))
|
|
40
|
+
fail(`unsupported key ${JSON.stringify(rawKey)} (bare keys only)`);
|
|
41
|
+
key = rawKey;
|
|
42
|
+
}
|
|
43
|
+
if (!table)
|
|
44
|
+
fail('key outside of a table');
|
|
45
|
+
if (table.has(key))
|
|
46
|
+
fail(`duplicate key ${key}`);
|
|
47
|
+
rest = rest.slice(eq + 1).trim();
|
|
48
|
+
let value;
|
|
49
|
+
if (rest.startsWith('"')) {
|
|
50
|
+
const m = STRING.exec(rest);
|
|
51
|
+
if (!m)
|
|
52
|
+
fail('unsupported string (escapes, quotes and control characters are not allowed)');
|
|
53
|
+
value = m[1];
|
|
54
|
+
rest = rest.slice(m[0].length);
|
|
55
|
+
}
|
|
56
|
+
else if (rest.startsWith('[')) {
|
|
57
|
+
rest = rest.slice(1).trim();
|
|
58
|
+
const items = [];
|
|
59
|
+
while (!rest.startsWith(']')) {
|
|
60
|
+
const m = STRING.exec(rest);
|
|
61
|
+
if (!m)
|
|
62
|
+
fail('array items must be basic strings on one line');
|
|
63
|
+
items.push(m[1]);
|
|
64
|
+
rest = rest.slice(m[0].length).trim();
|
|
65
|
+
if (rest.startsWith(','))
|
|
66
|
+
rest = rest.slice(1).trim();
|
|
67
|
+
else if (!rest.startsWith(']'))
|
|
68
|
+
fail('expected , or ] in array');
|
|
69
|
+
}
|
|
70
|
+
value = items;
|
|
71
|
+
rest = rest.slice(1);
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
return fail('unsupported value (only strings and string arrays)');
|
|
75
|
+
rest = rest.trim();
|
|
76
|
+
if (rest !== '' && !rest.startsWith('#'))
|
|
77
|
+
fail('unexpected text after value');
|
|
78
|
+
table.set(key, value);
|
|
79
|
+
});
|
|
80
|
+
return doc;
|
|
81
|
+
}
|