@latex-kit/template 0.0.0-stage → 0.3.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/LICENSE +23 -0
- package/README.md +137 -2
- package/analyze.d.ts +38 -0
- package/analyze.js +144 -0
- package/clause.d.ts +23 -0
- package/clause.js +26 -0
- package/codemod.d.ts +25 -0
- package/codemod.js +67 -0
- package/compile.d.ts +74 -0
- package/compile.js +258 -0
- package/condition.d.ts +38 -0
- package/condition.js +201 -0
- package/diagnostics.d.ts +29 -0
- package/diagnostics.js +48 -0
- package/document.d.ts +15 -0
- package/document.js +25 -0
- package/esm/analyze.d.ts +38 -0
- package/esm/analyze.js +141 -0
- package/esm/clause.d.ts +23 -0
- package/esm/clause.js +21 -0
- package/esm/codemod.d.ts +25 -0
- package/esm/codemod.js +62 -0
- package/esm/compile.d.ts +74 -0
- package/esm/compile.js +253 -0
- package/esm/condition.d.ts +38 -0
- package/esm/condition.js +193 -0
- package/esm/diagnostics.d.ts +29 -0
- package/esm/diagnostics.js +40 -0
- package/esm/document.d.ts +15 -0
- package/esm/document.js +22 -0
- package/esm/evaluate.d.ts +40 -0
- package/esm/evaluate.js +235 -0
- package/esm/filters.d.ts +39 -0
- package/esm/filters.js +221 -0
- package/esm/index.d.ts +12 -0
- package/esm/index.js +12 -0
- package/esm/jsonschema.d.ts +24 -0
- package/esm/jsonschema.js +94 -0
- package/esm/path.d.ts +7 -0
- package/esm/path.js +16 -0
- package/esm/sty.d.ts +6 -0
- package/esm/sty.js +67 -0
- package/evaluate.d.ts +40 -0
- package/evaluate.js +239 -0
- package/filters.d.ts +39 -0
- package/filters.js +229 -0
- package/index.d.ts +12 -0
- package/index.js +28 -0
- package/jsonschema.d.ts +24 -0
- package/jsonschema.js +99 -0
- package/package.json +44 -4
- package/path.d.ts +7 -0
- package/path.js +22 -0
- package/sty.d.ts +6 -0
- package/sty.js +70 -0
package/esm/analyze.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { conditionPaths } from './condition';
|
|
2
|
+
import { diag } from './diagnostics';
|
|
3
|
+
import { ANY, itemSchema, schemaAt } from './jsonschema';
|
|
4
|
+
import { GLOBAL_SPECIALS, LOOP_SPECIALS, splitPath } from './path';
|
|
5
|
+
/**
|
|
6
|
+
* Static checks for a template: every path exists in the schema, \each walks
|
|
7
|
+
* a list, \raw is flagged, snippets resolve. Lists every field it reads.
|
|
8
|
+
*/
|
|
9
|
+
export function analyzeTemplate(template, options = {}) {
|
|
10
|
+
const root = options.schema;
|
|
11
|
+
const diagnostics = [...template.diagnostics];
|
|
12
|
+
const fields = [];
|
|
13
|
+
const snippets = [];
|
|
14
|
+
const clauses = [];
|
|
15
|
+
const refs = [];
|
|
16
|
+
const stack = [template.file];
|
|
17
|
+
const resolve = (path, scopes, loc) => {
|
|
18
|
+
const [head, ...rest] = splitPath(path);
|
|
19
|
+
if (head.startsWith('$')) {
|
|
20
|
+
if (LOOP_SPECIALS.includes(head)) {
|
|
21
|
+
if (scopes.length === 0)
|
|
22
|
+
diagnostics.push(diag('error', `${head} only works inside \\each`, loc));
|
|
23
|
+
}
|
|
24
|
+
else if (!GLOBAL_SPECIALS.includes(head)) {
|
|
25
|
+
diagnostics.push(diag('error', `unknown special value ${head} (known: ${[...GLOBAL_SPECIALS, ...LOOP_SPECIALS].join(', ')})`, loc));
|
|
26
|
+
}
|
|
27
|
+
if (rest.length)
|
|
28
|
+
diagnostics.push(diag('error', `${head} has no fields`, loc));
|
|
29
|
+
return { absolute: path, schema: ANY };
|
|
30
|
+
}
|
|
31
|
+
const scope = [...scopes].reverse().find((s) => s.name === head);
|
|
32
|
+
const absolute = scope ? [scope.absolute, ...rest].join('.') : path;
|
|
33
|
+
if (!root)
|
|
34
|
+
return { absolute, schema: ANY };
|
|
35
|
+
const base = scope ? scope.schema : root;
|
|
36
|
+
const segs = scope ? rest : [head, ...rest];
|
|
37
|
+
const found = base === undefined ? undefined : schemaAt(base, segs, root);
|
|
38
|
+
if (found === undefined && base !== undefined) {
|
|
39
|
+
diagnostics.push(diag('error', `unknown field ${absolute} (not in the template's schema)`, loc));
|
|
40
|
+
}
|
|
41
|
+
return { absolute, schema: found };
|
|
42
|
+
};
|
|
43
|
+
const walk = (nodes, scopes) => {
|
|
44
|
+
for (const node of nodes) {
|
|
45
|
+
switch (node.kind) {
|
|
46
|
+
case 'text':
|
|
47
|
+
case 'docid':
|
|
48
|
+
break;
|
|
49
|
+
case 'field': {
|
|
50
|
+
const { absolute } = resolve(node.spec.path, scopes, node.loc);
|
|
51
|
+
fields.push({
|
|
52
|
+
kind: node.raw ? 'raw' : 'field',
|
|
53
|
+
path: node.spec.path,
|
|
54
|
+
absolute,
|
|
55
|
+
filters: node.spec.filters.map((f) => (f.arg === undefined ? f.name : `${f.name}:${f.arg}`)),
|
|
56
|
+
...node.loc,
|
|
57
|
+
});
|
|
58
|
+
if (node.raw) {
|
|
59
|
+
diagnostics.push(diag('warning', `\\raw{${node.spec.path}} inserts LaTeX unescaped; only use it for trusted values`, node.loc));
|
|
60
|
+
}
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
case 'when':
|
|
64
|
+
for (const p of conditionPaths(node.cond)) {
|
|
65
|
+
const { absolute } = resolve(p, scopes, node.loc);
|
|
66
|
+
fields.push({ kind: 'when', path: p, absolute, filters: [], ...node.loc });
|
|
67
|
+
}
|
|
68
|
+
walk(node.then, scopes);
|
|
69
|
+
if (node.else)
|
|
70
|
+
walk(node.else, scopes);
|
|
71
|
+
break;
|
|
72
|
+
case 'each': {
|
|
73
|
+
const { absolute, schema } = resolve(node.path, scopes, node.loc);
|
|
74
|
+
fields.push({ kind: 'each', path: node.path, absolute, filters: [], ...node.loc });
|
|
75
|
+
let item = ANY;
|
|
76
|
+
if (root && schema !== undefined) {
|
|
77
|
+
item = itemSchema(schema, root);
|
|
78
|
+
if (item === undefined)
|
|
79
|
+
diagnostics.push(diag('error', `\\each{${node.path}}: ${absolute} is not a list in the schema`, node.loc));
|
|
80
|
+
}
|
|
81
|
+
walk(node.body, [...scopes, { name: node.name, absolute: `${absolute}[]`, schema: item }]);
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
case 'sep':
|
|
85
|
+
walk(node.body, scopes);
|
|
86
|
+
break;
|
|
87
|
+
case 'snippet': {
|
|
88
|
+
const from = stack[stack.length - 1];
|
|
89
|
+
const snippet = options.loadSnippet?.(node.name, from) ?? null;
|
|
90
|
+
if (!snippet) {
|
|
91
|
+
diagnostics.push(diag('error', `snippet not found: ${node.name}`, node.loc));
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
if (stack.includes(snippet.file)) {
|
|
95
|
+
diagnostics.push(diag('error', `snippet ${node.name} includes itself`, node.loc));
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
if (!snippets.includes(snippet.file)) {
|
|
99
|
+
snippets.push(snippet.file);
|
|
100
|
+
diagnostics.push(...snippet.diagnostics);
|
|
101
|
+
}
|
|
102
|
+
stack.push(snippet.file);
|
|
103
|
+
walk(snippet.nodes, scopes);
|
|
104
|
+
stack.pop();
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
case 'clause': {
|
|
108
|
+
const clause = options.loadClause?.(node.id) ?? null;
|
|
109
|
+
if (!clause) {
|
|
110
|
+
diagnostics.push(diag('error', `clause not found: ${node.id}`, node.loc));
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
if (stack.includes(clause.template.file)) {
|
|
114
|
+
diagnostics.push(diag('error', `clause ${node.id} includes itself`, node.loc));
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
if (!clauses.some((c) => c.id === node.id)) {
|
|
118
|
+
clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
|
|
119
|
+
diagnostics.push(...clause.template.diagnostics);
|
|
120
|
+
if (!clause.title)
|
|
121
|
+
diagnostics.push(diag('warning', `clause ${node.id} has no "% title:" line, so it prints as a bare number`, { file: clause.template.file, line: 1, column: 1 }));
|
|
122
|
+
}
|
|
123
|
+
stack.push(clause.template.file);
|
|
124
|
+
walk(clause.template.nodes, scopes);
|
|
125
|
+
stack.pop();
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case 'clauseref':
|
|
129
|
+
refs.push({ id: node.id, loc: node.loc });
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
walk(template.nodes, []);
|
|
135
|
+
for (const r of refs) {
|
|
136
|
+
if (!clauses.some((c) => c.id === r.id)) {
|
|
137
|
+
diagnostics.push(diag('error', `\\clauseref{${r.id}}: the template never places \\clause{${r.id}}`, r.loc));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { fields, snippets, clauses, diagnostics };
|
|
141
|
+
}
|
package/esm/clause.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CompiledTemplate } from './compile';
|
|
2
|
+
export interface ClauseMeta {
|
|
3
|
+
title?: string;
|
|
4
|
+
version?: string;
|
|
5
|
+
}
|
|
6
|
+
/** A clause from the library, compiled, with its header. */
|
|
7
|
+
export interface LoadedClause extends ClauseMeta {
|
|
8
|
+
id: string;
|
|
9
|
+
template: CompiledTemplate;
|
|
10
|
+
}
|
|
11
|
+
export interface ClauseUse {
|
|
12
|
+
id: string;
|
|
13
|
+
version?: string;
|
|
14
|
+
file: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Read a clause file's header: the leading `%` comment lines.
|
|
18
|
+
*
|
|
19
|
+
* % title: Confidentiality
|
|
20
|
+
* % version: 3
|
|
21
|
+
*/
|
|
22
|
+
export declare function parseClauseHeader(text: string): ClauseMeta;
|
|
23
|
+
export declare const clauseLabel: (id: string) => string;
|
package/esm/clause.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read a clause file's header: the leading `%` comment lines.
|
|
3
|
+
*
|
|
4
|
+
* % title: Confidentiality
|
|
5
|
+
* % version: 3
|
|
6
|
+
*/
|
|
7
|
+
export function parseClauseHeader(text) {
|
|
8
|
+
const meta = {};
|
|
9
|
+
for (const line of text.split('\n')) {
|
|
10
|
+
const t = line.trim();
|
|
11
|
+
if (t === '')
|
|
12
|
+
continue;
|
|
13
|
+
if (!t.startsWith('%'))
|
|
14
|
+
break;
|
|
15
|
+
const m = /^%\s*(title|version)\s*:\s*(.*?)\s*$/i.exec(t);
|
|
16
|
+
if (m)
|
|
17
|
+
meta[m[1].toLowerCase()] = m[2];
|
|
18
|
+
}
|
|
19
|
+
return meta;
|
|
20
|
+
}
|
|
21
|
+
export const clauseLabel = (id) => `clause:${id}`;
|
package/esm/codemod.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface Converted {
|
|
2
|
+
/** The token as it appeared, e.g. `@COMPANY@LEGAL_NAME@` or `{{ party.name }}`. */
|
|
3
|
+
from: string;
|
|
4
|
+
/** What it became, e.g. `\field{company.legalName}`. */
|
|
5
|
+
to: string;
|
|
6
|
+
line: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ConvertResult {
|
|
9
|
+
tex: string;
|
|
10
|
+
converted: Converted[];
|
|
11
|
+
/** Tokens that looked like placeholders but could not become a valid path. */
|
|
12
|
+
skipped: Converted[];
|
|
13
|
+
}
|
|
14
|
+
/** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
|
|
15
|
+
export declare function camelSegment(seg: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* Turn placeholder tokens from older templates or Word documents into
|
|
18
|
+
* `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
|
|
19
|
+
* `{{ path }}` (common in Word/Markdown templates, also after pandoc
|
|
20
|
+
* escaped it). Anything that cannot become a valid path is left alone and
|
|
21
|
+
* reported.
|
|
22
|
+
*/
|
|
23
|
+
export declare function convertPlaceholders(tex: string): ConvertResult;
|
|
24
|
+
/** Make sure a document loads latex-kit.sty, right before \begin{document}. */
|
|
25
|
+
export declare function ensureLatexKitPackage(tex: string): string;
|
package/esm/codemod.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { isPath } from './path';
|
|
2
|
+
/** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
|
|
3
|
+
export function camelSegment(seg) {
|
|
4
|
+
const s = seg.replace(/\\_/g, '_');
|
|
5
|
+
if (!s.includes('_') && s !== s.toUpperCase())
|
|
6
|
+
return s;
|
|
7
|
+
const parts = s.toLowerCase().split('_').filter(Boolean);
|
|
8
|
+
return parts.map((p, i) => (i === 0 ? p : p[0].toUpperCase() + p.slice(1))).join('');
|
|
9
|
+
}
|
|
10
|
+
// @GROUP@FIELD@ with letters, digits and underscores (possibly escaped as \_ by pandoc)
|
|
11
|
+
const LEGACY = /@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@/g;
|
|
12
|
+
// {{ path }} as typed, or \{\{ path \}\} as pandoc escapes it
|
|
13
|
+
const MUSTACHE = /(?:\{\{|\\\{\\\{)\s*([^{}\\]*(?:\\_[^{}\\]*)*?)\s*(?:\}\}|\\\}\\\})/g;
|
|
14
|
+
function lineAt(text, offset) {
|
|
15
|
+
let n = 1;
|
|
16
|
+
for (let i = 0; i < offset; i++)
|
|
17
|
+
if (text.charCodeAt(i) === 10)
|
|
18
|
+
n++;
|
|
19
|
+
return n;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Turn placeholder tokens from older templates or Word documents into
|
|
23
|
+
* `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
|
|
24
|
+
* `{{ path }}` (common in Word/Markdown templates, also after pandoc
|
|
25
|
+
* escaped it). Anything that cannot become a valid path is left alone and
|
|
26
|
+
* reported.
|
|
27
|
+
*/
|
|
28
|
+
export function convertPlaceholders(tex) {
|
|
29
|
+
const converted = [];
|
|
30
|
+
const skipped = [];
|
|
31
|
+
let out = tex.replace(LEGACY, (whole, group, field, offset) => {
|
|
32
|
+
const path = `${camelSegment(group)}.${camelSegment(field)}`;
|
|
33
|
+
const item = { from: whole, to: `\\field{${path}}`, line: lineAt(tex, offset) };
|
|
34
|
+
if (!isPath(path)) {
|
|
35
|
+
skipped.push(item);
|
|
36
|
+
return whole;
|
|
37
|
+
}
|
|
38
|
+
converted.push(item);
|
|
39
|
+
return item.to;
|
|
40
|
+
});
|
|
41
|
+
const before = out;
|
|
42
|
+
out = out.replace(MUSTACHE, (whole, inner, offset) => {
|
|
43
|
+
const path = inner.replace(/\\_/g, '_').trim();
|
|
44
|
+
const item = { from: whole, to: `\\field{${path}}`, line: lineAt(before, offset) };
|
|
45
|
+
if (!isPath(path)) {
|
|
46
|
+
skipped.push(item);
|
|
47
|
+
return whole;
|
|
48
|
+
}
|
|
49
|
+
converted.push(item);
|
|
50
|
+
return item.to;
|
|
51
|
+
});
|
|
52
|
+
return { tex: out, converted, skipped };
|
|
53
|
+
}
|
|
54
|
+
/** Make sure a document loads latex-kit.sty, right before \begin{document}. */
|
|
55
|
+
export function ensureLatexKitPackage(tex) {
|
|
56
|
+
if (/\\usepackage\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/.test(tex))
|
|
57
|
+
return tex;
|
|
58
|
+
const at = tex.indexOf('\\begin{document}');
|
|
59
|
+
if (at === -1)
|
|
60
|
+
return tex;
|
|
61
|
+
return `${tex.slice(0, at)}\\usepackage{latex-kit}\n${tex.slice(at)}`;
|
|
62
|
+
}
|
package/esm/compile.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { Expr } from './condition';
|
|
2
|
+
import { Diagnostic, Location } from './diagnostics';
|
|
3
|
+
import { FieldSpec } from './filters';
|
|
4
|
+
/**
|
|
5
|
+
* The template language's macros and how many {…} arguments each takes.
|
|
6
|
+
* Bare names keep templates readable; \snippet (not \partial, which is the
|
|
7
|
+
* math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
|
|
8
|
+
* inserts a numbered clause from the clause library; \clauseref prints its number.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MACROS: {
|
|
11
|
+
readonly field: 1;
|
|
12
|
+
readonly raw: 1;
|
|
13
|
+
readonly when: 2;
|
|
14
|
+
readonly otherwise: 1;
|
|
15
|
+
readonly each: 3;
|
|
16
|
+
readonly sep: 1;
|
|
17
|
+
readonly snippet: 1;
|
|
18
|
+
readonly docid: 0;
|
|
19
|
+
readonly clause: 1;
|
|
20
|
+
readonly clauseref: 1;
|
|
21
|
+
};
|
|
22
|
+
export type MacroName = keyof typeof MACROS;
|
|
23
|
+
export type Node = {
|
|
24
|
+
kind: 'text';
|
|
25
|
+
text: string;
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'field';
|
|
28
|
+
spec: FieldSpec;
|
|
29
|
+
raw: boolean;
|
|
30
|
+
source: string;
|
|
31
|
+
loc: Location;
|
|
32
|
+
} | {
|
|
33
|
+
kind: 'when';
|
|
34
|
+
cond: Expr;
|
|
35
|
+
source: string;
|
|
36
|
+
then: Node[];
|
|
37
|
+
else?: Node[];
|
|
38
|
+
loc: Location;
|
|
39
|
+
} | {
|
|
40
|
+
kind: 'each';
|
|
41
|
+
path: string;
|
|
42
|
+
name: string;
|
|
43
|
+
body: Node[];
|
|
44
|
+
loc: Location;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'sep';
|
|
47
|
+
body: Node[];
|
|
48
|
+
loc: Location;
|
|
49
|
+
} | {
|
|
50
|
+
kind: 'snippet';
|
|
51
|
+
name: string;
|
|
52
|
+
loc: Location;
|
|
53
|
+
} | {
|
|
54
|
+
kind: 'docid';
|
|
55
|
+
loc: Location;
|
|
56
|
+
} | {
|
|
57
|
+
kind: 'clause';
|
|
58
|
+
id: string;
|
|
59
|
+
loc: Location;
|
|
60
|
+
} | {
|
|
61
|
+
kind: 'clauseref';
|
|
62
|
+
id: string;
|
|
63
|
+
loc: Location;
|
|
64
|
+
};
|
|
65
|
+
export interface CompiledTemplate {
|
|
66
|
+
file: string;
|
|
67
|
+
text: string;
|
|
68
|
+
nodes: Node[];
|
|
69
|
+
/** Syntax problems found while compiling. */
|
|
70
|
+
diagnostics: Diagnostic[];
|
|
71
|
+
}
|
|
72
|
+
/** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
|
|
73
|
+
export declare function isRelativeName(name: string): boolean;
|
|
74
|
+
export declare function compileTemplate(text: string, file: string): CompiledTemplate;
|
package/esm/compile.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { getParser } from '@unified-latex/unified-latex-util-parse';
|
|
2
|
+
import { ConditionError, parseCondition } from './condition';
|
|
3
|
+
import { diag, LineIndex } from './diagnostics';
|
|
4
|
+
import { FilterError, parseFieldSpec } from './filters';
|
|
5
|
+
import { isName, isPath } from './path';
|
|
6
|
+
/**
|
|
7
|
+
* The template language's macros and how many {…} arguments each takes.
|
|
8
|
+
* Bare names keep templates readable; \snippet (not \partial, which is the
|
|
9
|
+
* math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
|
|
10
|
+
* inserts a numbered clause from the clause library; \clauseref prints its number.
|
|
11
|
+
*/
|
|
12
|
+
export const MACROS = {
|
|
13
|
+
field: 1,
|
|
14
|
+
raw: 1,
|
|
15
|
+
when: 2,
|
|
16
|
+
otherwise: 1,
|
|
17
|
+
each: 3,
|
|
18
|
+
sep: 1,
|
|
19
|
+
snippet: 1,
|
|
20
|
+
docid: 0,
|
|
21
|
+
clause: 1,
|
|
22
|
+
clauseref: 1,
|
|
23
|
+
};
|
|
24
|
+
const parser = getParser({
|
|
25
|
+
macros: Object.fromEntries(Object.entries(MACROS).map(([name, n]) => [name, { signature: Array(n).fill('m').join(' ') }])),
|
|
26
|
+
});
|
|
27
|
+
/** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
|
|
28
|
+
export function isRelativeName(name) {
|
|
29
|
+
return /^[A-Za-z0-9_./-]+$/.test(name) && !name.split('/').some((s) => s === '..' || s === '' || s === '.');
|
|
30
|
+
}
|
|
31
|
+
/** Find our macros with unified-latex, so comments, verbatim and \verb are skipped. */
|
|
32
|
+
function findMacros(text) {
|
|
33
|
+
const out = [];
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
const walk = (node) => {
|
|
36
|
+
if (Array.isArray(node)) {
|
|
37
|
+
node.forEach(walk);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (!node || typeof node !== 'object')
|
|
41
|
+
return;
|
|
42
|
+
const n = node;
|
|
43
|
+
if (n.type === 'macro' && typeof n.content === 'string' && n.content in MACROS && n.position) {
|
|
44
|
+
const start = n.position.start.offset;
|
|
45
|
+
if (!seen.has(start)) {
|
|
46
|
+
seen.add(start);
|
|
47
|
+
out.push({ name: n.content, start });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (n.content && typeof n.content !== 'string')
|
|
51
|
+
walk(n.content);
|
|
52
|
+
if (n.args)
|
|
53
|
+
walk(n.args);
|
|
54
|
+
};
|
|
55
|
+
walk(parser.parse(text));
|
|
56
|
+
return out.sort((a, b) => a.start - b.start);
|
|
57
|
+
}
|
|
58
|
+
class SyntaxError extends Error {
|
|
59
|
+
offset;
|
|
60
|
+
constructor(message, offset) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.offset = offset;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Skip spaces and at most one line break, as TeX does between arguments. */
|
|
66
|
+
function skipSpace(text, pos) {
|
|
67
|
+
let newlines = 0;
|
|
68
|
+
while (pos < text.length) {
|
|
69
|
+
const ch = text[pos];
|
|
70
|
+
if (ch === ' ' || ch === '\t' || ch === '\r')
|
|
71
|
+
pos++;
|
|
72
|
+
else if (ch === '\n' && newlines === 0) {
|
|
73
|
+
newlines++;
|
|
74
|
+
pos++;
|
|
75
|
+
}
|
|
76
|
+
else
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
return pos;
|
|
80
|
+
}
|
|
81
|
+
/** Read `count` brace groups starting at `pos`. Returns the content ranges and the end. */
|
|
82
|
+
function readArgs(text, pos, count, macro) {
|
|
83
|
+
const args = [];
|
|
84
|
+
for (let i = 0; i < count; i++) {
|
|
85
|
+
const open = skipSpace(text, pos);
|
|
86
|
+
if (text[open] !== '{') {
|
|
87
|
+
throw new SyntaxError(`\\${macro} needs ${count} {…} argument${count > 1 ? 's' : ''}`, open);
|
|
88
|
+
}
|
|
89
|
+
let depth = 0;
|
|
90
|
+
let j = open;
|
|
91
|
+
for (; j < text.length; j++) {
|
|
92
|
+
const ch = text[j];
|
|
93
|
+
if (ch === '\\') {
|
|
94
|
+
j++;
|
|
95
|
+
}
|
|
96
|
+
else if (ch === '%') {
|
|
97
|
+
while (j < text.length && text[j] !== '\n')
|
|
98
|
+
j++;
|
|
99
|
+
}
|
|
100
|
+
else if (ch === '{') {
|
|
101
|
+
depth++;
|
|
102
|
+
}
|
|
103
|
+
else if (ch === '}') {
|
|
104
|
+
depth--;
|
|
105
|
+
if (depth === 0)
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (depth !== 0)
|
|
110
|
+
throw new SyntaxError(`unbalanced braces in \\${macro}`, open);
|
|
111
|
+
args.push({ start: open + 1, end: j });
|
|
112
|
+
pos = j + 1;
|
|
113
|
+
}
|
|
114
|
+
return { args, end: pos };
|
|
115
|
+
}
|
|
116
|
+
export function compileTemplate(text, file) {
|
|
117
|
+
const diagnostics = [];
|
|
118
|
+
const lines = new LineIndex(text);
|
|
119
|
+
const at = (offset) => ({ file, ...lines.locate(offset) });
|
|
120
|
+
let occurrences;
|
|
121
|
+
try {
|
|
122
|
+
occurrences = findMacros(text);
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
diagnostics.push(diag('error', `could not parse: ${e.message}`, at(0)));
|
|
126
|
+
return { file, text, nodes: [{ kind: 'text', text }], diagnostics };
|
|
127
|
+
}
|
|
128
|
+
let next = 0; // index into occurrences
|
|
129
|
+
const compileRange = (start, end, inEach) => {
|
|
130
|
+
const nodes = [];
|
|
131
|
+
let pos = start;
|
|
132
|
+
const pushText = (to) => {
|
|
133
|
+
if (to > pos)
|
|
134
|
+
nodes.push({ kind: 'text', text: text.slice(pos, to) });
|
|
135
|
+
};
|
|
136
|
+
while (next < occurrences.length && occurrences[next].start < end) {
|
|
137
|
+
const occ = occurrences[next++];
|
|
138
|
+
if (occ.start < pos)
|
|
139
|
+
continue; // inside an argument already consumed
|
|
140
|
+
pushText(occ.start);
|
|
141
|
+
const loc = at(occ.start);
|
|
142
|
+
const nameEnd = occ.start + 1 + occ.name.length;
|
|
143
|
+
pos = nameEnd;
|
|
144
|
+
try {
|
|
145
|
+
const { args, end: macroEnd } = readArgs(text, nameEnd, MACROS[occ.name], occ.name);
|
|
146
|
+
const argText = (i) => text.slice(args[i].start, args[i].end).trim();
|
|
147
|
+
switch (occ.name) {
|
|
148
|
+
case 'field':
|
|
149
|
+
case 'raw': {
|
|
150
|
+
try {
|
|
151
|
+
nodes.push({ kind: 'field', spec: parseFieldSpec(argText(0)), raw: occ.name === 'raw', source: argText(0), loc });
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
if (!(e instanceof FilterError))
|
|
155
|
+
throw e;
|
|
156
|
+
diagnostics.push(diag('error', `\\${occ.name}{${argText(0)}}: ${e.message}`, loc));
|
|
157
|
+
}
|
|
158
|
+
pos = macroEnd;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
case 'when': {
|
|
162
|
+
let cond = null;
|
|
163
|
+
try {
|
|
164
|
+
cond = parseCondition(argText(0));
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
if (!(e instanceof ConditionError))
|
|
168
|
+
throw e;
|
|
169
|
+
diagnostics.push(diag('error', `\\when{${argText(0)}}: ${e.message}`, loc));
|
|
170
|
+
}
|
|
171
|
+
const thenNodes = compileRange(args[1].start, args[1].end, inEach);
|
|
172
|
+
pos = macroEnd;
|
|
173
|
+
let elseNodes;
|
|
174
|
+
const after = skipSpace(text, macroEnd);
|
|
175
|
+
const nextOcc = occurrences[next];
|
|
176
|
+
if (nextOcc && nextOcc.name === 'otherwise' && nextOcc.start === after) {
|
|
177
|
+
next++;
|
|
178
|
+
const o = readArgs(text, after + '\\otherwise'.length, 1, 'otherwise');
|
|
179
|
+
elseNodes = compileRange(o.args[0].start, o.args[0].end, inEach);
|
|
180
|
+
pos = o.end;
|
|
181
|
+
}
|
|
182
|
+
if (cond)
|
|
183
|
+
nodes.push({ kind: 'when', cond, source: argText(0), then: thenNodes, else: elseNodes, loc });
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
case 'otherwise':
|
|
187
|
+
diagnostics.push(diag('error', '\\otherwise must come right after \\when{…}{…}', loc));
|
|
188
|
+
pos = macroEnd;
|
|
189
|
+
break;
|
|
190
|
+
case 'each': {
|
|
191
|
+
const path = argText(0);
|
|
192
|
+
const name = argText(1);
|
|
193
|
+
if (!isPath(path))
|
|
194
|
+
diagnostics.push(diag('error', `\\each: invalid list path "${path}"`, loc));
|
|
195
|
+
if (!isName(name))
|
|
196
|
+
diagnostics.push(diag('error', `\\each: invalid item name "${name}" (use a simple name like item)`, loc));
|
|
197
|
+
const body = compileRange(args[2].start, args[2].end, true);
|
|
198
|
+
nodes.push({ kind: 'each', path, name, body, loc });
|
|
199
|
+
pos = macroEnd;
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
case 'sep': {
|
|
203
|
+
if (!inEach)
|
|
204
|
+
diagnostics.push(diag('error', '\\sep only works inside \\each', loc));
|
|
205
|
+
nodes.push({ kind: 'sep', body: compileRange(args[0].start, args[0].end, inEach), loc });
|
|
206
|
+
pos = macroEnd;
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
case 'snippet':
|
|
210
|
+
case 'clause': {
|
|
211
|
+
const name = argText(0);
|
|
212
|
+
if (!isRelativeName(name)) {
|
|
213
|
+
diagnostics.push(diag('error', `\\${occ.name}{${name}}: use a relative name like ${occ.name === 'clause' ? 'nda/confidentiality' : 'parts/header'}`, loc));
|
|
214
|
+
}
|
|
215
|
+
else if (occ.name === 'snippet') {
|
|
216
|
+
nodes.push({ kind: 'snippet', name, loc });
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
nodes.push({ kind: 'clause', id: name, loc });
|
|
220
|
+
}
|
|
221
|
+
pos = macroEnd;
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
case 'docid': {
|
|
225
|
+
nodes.push({ kind: 'docid', loc });
|
|
226
|
+
// allow \docid{} as in plain LaTeX usage
|
|
227
|
+
pos = text.startsWith('{}', macroEnd) ? macroEnd + 2 : macroEnd;
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
case 'clauseref': {
|
|
231
|
+
const id = argText(0);
|
|
232
|
+
if (!isRelativeName(id))
|
|
233
|
+
diagnostics.push(diag('error', `\\clauseref{${id}}: use the clause's name, like nda/confidentiality`, loc));
|
|
234
|
+
else
|
|
235
|
+
nodes.push({ kind: 'clauseref', id, loc });
|
|
236
|
+
pos = macroEnd;
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch (e) {
|
|
242
|
+
if (!(e instanceof SyntaxError))
|
|
243
|
+
throw e;
|
|
244
|
+
diagnostics.push(diag('error', e.message, at(e.offset)));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
pushText(end);
|
|
248
|
+
pos = end;
|
|
249
|
+
return nodes;
|
|
250
|
+
};
|
|
251
|
+
const nodes = compileRange(0, text.length, false);
|
|
252
|
+
return { file, text, nodes, diagnostics };
|
|
253
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The condition language for \when{…}: a small, safe expression grammar.
|
|
3
|
+
* Never evaluated with eval.
|
|
4
|
+
*
|
|
5
|
+
* expr := or
|
|
6
|
+
* or := and ('||' and)*
|
|
7
|
+
* and := not ('&&' not)*
|
|
8
|
+
* not := '!' not | compare
|
|
9
|
+
* compare := primary (('==' | '!=' | '<' | '<=' | '>' | '>=') primary)?
|
|
10
|
+
* primary := path | number | "string" | true | false | null | '(' expr ')'
|
|
11
|
+
*/
|
|
12
|
+
export type Expr = {
|
|
13
|
+
type: 'path';
|
|
14
|
+
path: string;
|
|
15
|
+
} | {
|
|
16
|
+
type: 'literal';
|
|
17
|
+
value: string | number | boolean | null;
|
|
18
|
+
} | {
|
|
19
|
+
type: 'not';
|
|
20
|
+
expr: Expr;
|
|
21
|
+
} | {
|
|
22
|
+
type: 'and' | 'or';
|
|
23
|
+
left: Expr;
|
|
24
|
+
right: Expr;
|
|
25
|
+
} | {
|
|
26
|
+
type: 'compare';
|
|
27
|
+
op: CompareOp;
|
|
28
|
+
left: Expr;
|
|
29
|
+
right: Expr;
|
|
30
|
+
};
|
|
31
|
+
export type CompareOp = '==' | '!=' | '<' | '<=' | '>' | '>=';
|
|
32
|
+
export declare class ConditionError extends Error {
|
|
33
|
+
name: string;
|
|
34
|
+
}
|
|
35
|
+
export declare function parseCondition(src: string): Expr;
|
|
36
|
+
export declare function truthy(v: unknown): boolean;
|
|
37
|
+
export declare function evaluateCondition(expr: Expr, lookup: (path: string) => unknown): boolean;
|
|
38
|
+
export declare function conditionPaths(expr: Expr, out?: string[]): string[];
|