@malloy-publisher/sdk 0.4.0 → 0.5.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 +19 -0
- package/dist/{DocumentStorageProvider-CyOJ0hqf.es.js → DocumentStorage-B04sZ5Ie.es.js} +2307 -2334
- package/dist/{DocumentStorageProvider-DGPQEd_l.cjs.js → DocumentStorage-B_MMJ0Ot.cjs.js} +20 -20
- package/dist/{RenderedResult-BnPzJ9Jf.es.js → RenderedResult-BB7eokcf.es.js} +100 -80
- package/dist/RenderedResult-DVuGhatg.cjs.js +135 -0
- package/dist/ServerProvider-D-jjzfE5.cjs.js +1 -0
- package/dist/{ServerProvider-BWOEKg0O.es.js → ServerProvider-Do-GBvpn.es.js} +492 -481
- package/dist/builder/index.cjs.js +57 -52
- package/dist/builder/index.es.js +4421 -3738
- package/dist/client/api.d.ts +14 -1
- package/dist/client/index.cjs.js +1 -1
- package/dist/client/index.es.js +1 -1
- package/dist/components/Dashboard/TileCard.d.ts +7 -3
- package/dist/components/Dashboard/telemetry.d.ts +20 -8
- package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +16 -4
- package/dist/components/DashboardBuilder/DashboardEditor.d.ts +31 -8
- package/dist/components/DashboardBuilder/controls.d.ts +8 -6
- package/dist/components/DashboardBuilder/document.d.ts +19 -5
- package/dist/components/DashboardBuilder/malloyText.d.ts +0 -30
- package/dist/components/DashboardBuilder/malloyTree.d.ts +232 -0
- package/dist/components/DashboardBuilder/preview.d.ts +17 -0
- package/dist/components/DashboardBuilder/readDocument.d.ts +23 -28
- package/dist/components/DashboardBuilder/spliceDocument.d.ts +12 -0
- package/dist/components/DocumentStorage/DocumentStorage.d.ts +69 -5
- package/dist/components/DocumentStorage/index.d.ts +1 -0
- package/dist/index.cjs.js +9 -9
- package/dist/index.es.js +508 -506
- package/dist/theme/resolveTheme.d.ts +1 -1
- package/dist/theme/types.d.ts +12 -2
- package/package.json +1 -1
- package/src/components/Dashboard/TileCard.tsx +8 -4
- package/src/components/Dashboard/telemetry.ts +20 -8
- package/src/components/DashboardBuilder/BuilderToolbar.tsx +4 -5
- package/src/components/DashboardBuilder/DashboardBuilder.tsx +21 -3
- package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +706 -0
- package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +356 -0
- package/src/components/DashboardBuilder/DashboardEditor.tsx +468 -103
- package/src/components/DashboardBuilder/FilterDialog.tsx +19 -6
- package/src/components/DashboardBuilder/TileFrame.tsx +11 -2
- package/src/components/DashboardBuilder/TileMenu.tsx +6 -0
- package/src/components/DashboardBuilder/__test__/inventory.ts +367 -0
- package/src/components/DashboardBuilder/controls.spec.ts +53 -3
- package/src/components/DashboardBuilder/controls.ts +9 -7
- package/src/components/DashboardBuilder/document.ts +17 -5
- package/src/components/DashboardBuilder/invariants.spec.ts +297 -0
- package/src/components/DashboardBuilder/malloyText.spec.ts +27 -66
- package/src/components/DashboardBuilder/malloyText.ts +4 -109
- package/src/components/DashboardBuilder/malloyTree.spec.ts +362 -0
- package/src/components/DashboardBuilder/malloyTree.ts +954 -0
- package/src/components/DashboardBuilder/preview.spec.ts +18 -0
- package/src/components/DashboardBuilder/preview.ts +24 -6
- package/src/components/DashboardBuilder/readDocument.spec.ts +312 -21
- package/src/components/DashboardBuilder/readDocument.ts +144 -165
- package/src/components/DashboardBuilder/scannerShapes.spec.ts +550 -0
- package/src/components/DashboardBuilder/spliceDocument.spec.ts +955 -21
- package/src/components/DashboardBuilder/spliceDocument.ts +509 -119
- package/src/components/DashboardBuilder/statementExtent.spec.ts +606 -0
- package/src/components/DocumentStorage/BrowserDocumentStorage.ts +7 -6
- package/src/components/DocumentStorage/DocumentStorage.ts +78 -5
- package/src/components/DocumentStorage/index.ts +1 -0
- package/src/components/Package/Package.tsx +12 -7
- package/src/components/RenderedResult/RenderedResult.tsx +21 -1
- package/src/components/given/GivensPanel.tsx +15 -3
- package/src/theme/buildTableCssVars.spec.ts +3 -0
- package/src/theme/buildTableCssVars.ts +6 -0
- package/src/theme/defaults.ts +16 -12
- package/src/theme/resolveTheme.spec.ts +14 -7
- package/src/theme/resolveTheme.ts +14 -8
- package/src/theme/types.ts +12 -2
- package/tsconfig.spec.json +5 -1
- package/dist/RenderedResult-Dp22kZsQ.cjs.js +0 -115
- package/dist/ServerProvider-Cc489A3f.cjs.js +0 -1
|
@@ -0,0 +1,954 @@
|
|
|
1
|
+
// Copyright (c) Credible Data Inc.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Where everything in a dashboard file IS, according to Malloy's own parser.
|
|
6
|
+
*
|
|
7
|
+
* The only module that touches the parse tree. The reader and the writer both
|
|
8
|
+
* locate through it, which is what makes a reader/writer disagreement about
|
|
9
|
+
* where a declaration starts or ends impossible rather than unlikely — the
|
|
10
|
+
* defect class that every hand-written scan here kept reintroducing.
|
|
11
|
+
*
|
|
12
|
+
* The rule the rest of the builder follows: LOCATORS come from this module,
|
|
13
|
+
* RECOGNIZERS may read text over a span this module bounded, and EMITTERS take
|
|
14
|
+
* positions only from a span or a token here. Nothing outside re-derives
|
|
15
|
+
* Malloy's grammar from raw text.
|
|
16
|
+
*
|
|
17
|
+
* Node identity is by ACCESSOR, never `constructor.name`: `@malloydata/malloy`
|
|
18
|
+
* is a peerDependency, so the host bundler minifies it and every class name
|
|
19
|
+
* becomes a single letter. Accessor and token names are properties, which
|
|
20
|
+
* minifiers leave alone.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** A half-open range of UTF-16 offsets into the source text. */
|
|
24
|
+
export interface Span {
|
|
25
|
+
start: number;
|
|
26
|
+
end: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Anything the writer has to find again: where it is, and on which line. */
|
|
30
|
+
export interface Positioned {
|
|
31
|
+
span: Span;
|
|
32
|
+
/** 0-based, to index the `lines` array the tag scan still works in. */
|
|
33
|
+
line: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A `field <op> $GIVEN` comparison: the only filter shape the builder owns. */
|
|
37
|
+
export interface TreeBinding {
|
|
38
|
+
field: string;
|
|
39
|
+
op: string;
|
|
40
|
+
given: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** One entry of a `where:` clause list, whether or not the builder owns it. */
|
|
44
|
+
export interface TreeClause extends Positioned {
|
|
45
|
+
binding?: TreeBinding;
|
|
46
|
+
/**
|
|
47
|
+
* Every `$GIVEN` this clause references, binding or not. A clause the
|
|
48
|
+
* builder does not own that names a given is what makes binding that given
|
|
49
|
+
* again a double filter, and the tree says so exactly — a scan for `$NAME`
|
|
50
|
+
* could be fooled by an apostrophe in a comment, and was.
|
|
51
|
+
*/
|
|
52
|
+
givens: string[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A `where:` statement, with its clauses located individually. */
|
|
56
|
+
export interface TreeWhere extends Positioned {
|
|
57
|
+
clauses: TreeClause[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A `{ … }` query-properties block: a view body, or a `+ { … }` refinement. */
|
|
61
|
+
export interface TreeStage {
|
|
62
|
+
/** The whole block, both braces included. */
|
|
63
|
+
span: Span;
|
|
64
|
+
/** Just after `{`, and at `}` — where a first or last statement goes. */
|
|
65
|
+
openEnd: number;
|
|
66
|
+
closeStart: number;
|
|
67
|
+
statements: Positioned[];
|
|
68
|
+
/** This block's OWN `where:`s. A nested `nest:`'s never appear here. */
|
|
69
|
+
wheres: TreeWhere[];
|
|
70
|
+
/** The indent a sibling statement sits at, for anything inserted. */
|
|
71
|
+
indent: string;
|
|
72
|
+
/** True when `{ … }` is written on one line, which changes how we insert. */
|
|
73
|
+
oneLine: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type TreeViewBody =
|
|
77
|
+
/** `view: v is base` or `view: v is base + { … }`. */
|
|
78
|
+
| { kind: "reference"; from: string; fromSpan: Span; refinement?: TreeStage }
|
|
79
|
+
/**
|
|
80
|
+
* `view: v is { … }`, or the first stage of `{ … } -> { … }`. Only the
|
|
81
|
+
* first stage is ever the tile's own, so `pipeline` says a later one
|
|
82
|
+
* follows and nothing may be appended to the end of the declaration.
|
|
83
|
+
*/
|
|
84
|
+
| { kind: "inline"; stage: TreeStage; pipeline?: boolean }
|
|
85
|
+
/** `view: v is a -> b`, and anything else: read, never rewritten. */
|
|
86
|
+
| { kind: "unsupported"; why: string };
|
|
87
|
+
|
|
88
|
+
export interface TreeView extends Positioned {
|
|
89
|
+
name: string;
|
|
90
|
+
/** `name is <expr>` — this entry alone, not the `view:` statement. */
|
|
91
|
+
span: Span;
|
|
92
|
+
/** The whole `view: …` statement, its `#` tag block included. */
|
|
93
|
+
statement: Span;
|
|
94
|
+
/** The `#` tag lines of that statement, in order. */
|
|
95
|
+
tags: Array<{ line: number; text: string }>;
|
|
96
|
+
/**
|
|
97
|
+
* How many views the one `view:` statement declares. Above 1 it is a
|
|
98
|
+
* comma-separated list, which the writer refuses to restructure.
|
|
99
|
+
*/
|
|
100
|
+
siblings: number;
|
|
101
|
+
body: TreeViewBody;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface TreeDimension extends Positioned {
|
|
105
|
+
name: string;
|
|
106
|
+
expression: string;
|
|
107
|
+
statement: Span;
|
|
108
|
+
tags: Array<{ line: number; text: string }>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface TreeSource extends Positioned {
|
|
112
|
+
name: string;
|
|
113
|
+
/** What it extends, as written — `orders`, or `` `odd name` ``. */
|
|
114
|
+
base: string;
|
|
115
|
+
/**
|
|
116
|
+
* The `source: …` statement, from the start of its line. Its `#` tag block
|
|
117
|
+
* is NOT included: the parser puts a source's annotations outside the rule's
|
|
118
|
+
* own range, and this type has no `tags` field to hold them either. A caller
|
|
119
|
+
* that wants them walks up from `line` with {@link ParsedMalloy.blockStart}.
|
|
120
|
+
*/
|
|
121
|
+
statement: Span;
|
|
122
|
+
/** The `extend { … }` block, when it has one. */
|
|
123
|
+
properties?: TreeStage;
|
|
124
|
+
views: TreeView[];
|
|
125
|
+
dimensions: TreeDimension[];
|
|
126
|
+
/** Source-level `where:`s, which are the source's own and not a tile's. */
|
|
127
|
+
wheres: TreeWhere[];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface TreeGiven extends Positioned {
|
|
131
|
+
name: string;
|
|
132
|
+
/** `NAME :: type is default`, as written. */
|
|
133
|
+
declaration: string;
|
|
134
|
+
statement: Span;
|
|
135
|
+
tags: Array<{ line: number; text: string }>;
|
|
136
|
+
/**
|
|
137
|
+
* The line of the `given:` keyword, when this is one entry of a block
|
|
138
|
+
* rather than a one-line declaration. Removing the last entry of a block
|
|
139
|
+
* has to take the header with it.
|
|
140
|
+
*/
|
|
141
|
+
blockHeader?: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface TreeImport extends Positioned {
|
|
145
|
+
/** The path, with its quotes stripped. */
|
|
146
|
+
from: string;
|
|
147
|
+
/** The `{ a, b }` selection, when there is one. */
|
|
148
|
+
names?: string[];
|
|
149
|
+
statement: Span;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface ParsedMalloy {
|
|
153
|
+
text: string;
|
|
154
|
+
/** 0-based line -> offset of its first character. */
|
|
155
|
+
lineStarts: number[];
|
|
156
|
+
imports: TreeImport[];
|
|
157
|
+
sources: TreeSource[];
|
|
158
|
+
givens: TreeGiven[];
|
|
159
|
+
/** The comment token on `line`, if the line ends with one. */
|
|
160
|
+
trailingComment(line: number): Span | undefined;
|
|
161
|
+
/**
|
|
162
|
+
* The first comment that starts inside `span`, of either token kind. A
|
|
163
|
+
* writer deleting a range wider than one node's own text asks this before
|
|
164
|
+
* it does, because a comment is trivia to the parser: it sits outside every
|
|
165
|
+
* span, so neither gate can see it go.
|
|
166
|
+
*/
|
|
167
|
+
commentIn(span: Span): Span | undefined;
|
|
168
|
+
/** Every comment in the file, in order, `//` and `--` and `/* … *\/`. */
|
|
169
|
+
comments: Span[];
|
|
170
|
+
/**
|
|
171
|
+
* Whether `line` is comment rather than code — including a line in the
|
|
172
|
+
* middle of a `/* … *\/`, whose text is prose however it begins.
|
|
173
|
+
*/
|
|
174
|
+
commentLine(line: number): boolean;
|
|
175
|
+
/**
|
|
176
|
+
* The `#`/comment block immediately above `line`, stopping at a blank line —
|
|
177
|
+
* the unit that travels with a declaration when it moves.
|
|
178
|
+
*/
|
|
179
|
+
blockStart(line: number): number;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface ParseRefusal {
|
|
183
|
+
ok: false;
|
|
184
|
+
reason: string;
|
|
185
|
+
line?: number;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export type ParseResult = { ok: true; parsed: ParsedMalloy } | ParseRefusal;
|
|
189
|
+
|
|
190
|
+
export const parseRefused = (r: ParseResult): r is ParseRefusal =>
|
|
191
|
+
r.ok === false;
|
|
192
|
+
|
|
193
|
+
/* ------------------------------------------------------------------ */
|
|
194
|
+
/* Node identity */
|
|
195
|
+
/* ------------------------------------------------------------------ */
|
|
196
|
+
|
|
197
|
+
interface TokenStream {
|
|
198
|
+
tokenSource?: {
|
|
199
|
+
vocabulary?: { getSymbolicName(type: number): string | undefined };
|
|
200
|
+
};
|
|
201
|
+
getTokens?(): Array<{ type: number; startIndex: number; stopIndex: number }>;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
type Ctx = Record<string, unknown> & {
|
|
205
|
+
ruleIndex?: number;
|
|
206
|
+
childCount?: number;
|
|
207
|
+
getChild(i: number): Ctx;
|
|
208
|
+
start?: { startIndex: number; line: number };
|
|
209
|
+
stop?: { stopIndex: number };
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const has = (c: unknown, ...accessors: string[]): boolean =>
|
|
213
|
+
accessors.every(
|
|
214
|
+
(a) => typeof (c as Record<string, unknown>)?.[a] === "function",
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
/** A rule context we can take a range from; terminals and empties are not. */
|
|
218
|
+
const isRule = (c: Ctx | undefined): boolean =>
|
|
219
|
+
c !== undefined && c.ruleIndex !== undefined && (c.childCount ?? 0) > 0;
|
|
220
|
+
|
|
221
|
+
const IS = {
|
|
222
|
+
sourceDefinition: (c: Ctx) =>
|
|
223
|
+
has(c, "sourceNameDef", "isDefine", "sqExplore"),
|
|
224
|
+
exploreQueryDef: (c: Ctx) =>
|
|
225
|
+
has(c, "exploreQueryNameDef", "isDefine", "vExpr"),
|
|
226
|
+
defExploreQuery: (c: Ctx) => has(c, "VIEW", "subQueryDefList"),
|
|
227
|
+
defDimension: (c: Ctx) => has(c, "defList", "DIMENSION"),
|
|
228
|
+
exploreProperties: (c: Ctx) =>
|
|
229
|
+
has(c, "exploreStatement", "OCURLY", "CCURLY"),
|
|
230
|
+
queryProperties: (c: Ctx) => has(c, "queryStatement", "OCURLY", "CCURLY"),
|
|
231
|
+
queryStatement: (c: Ctx) =>
|
|
232
|
+
has(c, "whereStatement", "aggregateStatement", "nestStatement"),
|
|
233
|
+
whereStatement: (c: Ctx) => has(c, "WHERE", "filterClauseList"),
|
|
234
|
+
givenDef: (c: Ctx) => has(c, "givenNameDef"),
|
|
235
|
+
givenStatement: (c: Ctx) => has(c, "GIVEN", "givenDefList"),
|
|
236
|
+
importStatement: (c: Ctx) => has(c, "IMPORT", "importURL"),
|
|
237
|
+
// A `vExpr` is either one stage or an `->` pipeline; a `segExpr` is a bare
|
|
238
|
+
// reference, a `{ … }` body, a `( … )`, or `lhs + rhs`.
|
|
239
|
+
vArrow: (c: Ctx) => has(c, "ARROW", "vExpr", "segExpr"),
|
|
240
|
+
segRefine: (c: Ctx) => has(c, "PLUS", "segExpr"),
|
|
241
|
+
segOps: (c: Ctx) => has(c, "queryProperties"),
|
|
242
|
+
segField: (c: Ctx) => has(c, "fieldPath") && !has(c, "segExpr"),
|
|
243
|
+
segParen: (c: Ctx) => has(c, "OPAREN", "CPAREN", "vExpr"),
|
|
244
|
+
/** `a ~ $A`: exactly a comparison, so `a ~ $A and c = 1` is not one. */
|
|
245
|
+
compare: (c: Ctx) => has(c, "fieldExpr", "compareOp"),
|
|
246
|
+
givenRef: (c: Ctx) => has(c, "GIVEN_REF"),
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
/* ------------------------------------------------------------------ */
|
|
250
|
+
/* Offsets */
|
|
251
|
+
/* ------------------------------------------------------------------ */
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Code-point index -> UTF-16 offset.
|
|
255
|
+
*
|
|
256
|
+
* ANTLR reads a `CodePointCharStream`, so every token index counts CODE
|
|
257
|
+
* POINTS while every JavaScript string index counts UTF-16 units. Measured on
|
|
258
|
+
* a line holding two emoji, a clause the parser puts at 24 is at 26 in JS, and
|
|
259
|
+
* slicing by the parser's number cuts a surrogate pair in half. One map per
|
|
260
|
+
* parse converts every offset once and the rest of the module is plain JS
|
|
261
|
+
* indices.
|
|
262
|
+
*/
|
|
263
|
+
function codePointMap(text: string): Int32Array {
|
|
264
|
+
const map = new Int32Array([...text].length + 1);
|
|
265
|
+
let cp = 0;
|
|
266
|
+
for (let i = 0; i < text.length; ) {
|
|
267
|
+
map[cp++] = i;
|
|
268
|
+
i += (text.codePointAt(i) as number) > 0xffff ? 2 : 1;
|
|
269
|
+
}
|
|
270
|
+
map[cp] = text.length;
|
|
271
|
+
return map;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function lineStartsOf(text: string): number[] {
|
|
275
|
+
const out = [0];
|
|
276
|
+
for (let i = 0; i < text.length; i++) if (text[i] === "\n") out.push(i + 1);
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/* ------------------------------------------------------------------ */
|
|
281
|
+
|
|
282
|
+
class Reader {
|
|
283
|
+
private readonly map: Int32Array;
|
|
284
|
+
readonly lineStarts: number[];
|
|
285
|
+
/**
|
|
286
|
+
* Lines that are comment rather than code, filled in from the lexer before
|
|
287
|
+
* anything is read. A block comment's own text is prose: a line inside one
|
|
288
|
+
* that happens to start with `#` is not an annotation, and reading it as one
|
|
289
|
+
* makes the writer rewrite a line inside a comment.
|
|
290
|
+
*/
|
|
291
|
+
commentLines: ReadonlySet<number> = new Set();
|
|
292
|
+
|
|
293
|
+
constructor(readonly text: string) {
|
|
294
|
+
this.map = codePointMap(text);
|
|
295
|
+
this.lineStarts = lineStartsOf(text);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The span a context covers, or `undefined` when it covers nothing we can
|
|
300
|
+
* trust. Empty rule contexts report inverted or whole-file ranges without
|
|
301
|
+
* throwing, so every span is checked rather than assumed.
|
|
302
|
+
*/
|
|
303
|
+
span(c: Ctx | undefined): Span | undefined {
|
|
304
|
+
if (!isRule(c)) return undefined;
|
|
305
|
+
const start = c!.start;
|
|
306
|
+
const stop = c!.stop;
|
|
307
|
+
if (!start || !stop) return undefined;
|
|
308
|
+
const s = this.map[start.startIndex];
|
|
309
|
+
const e = this.map[stop.stopIndex + 1];
|
|
310
|
+
if (s === undefined || e === undefined || e < s) return undefined;
|
|
311
|
+
return { start: s, end: e };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* The span of a TERMINAL node — a keyword or punctuation. A terminal has no
|
|
316
|
+
* rule range, only the token it stands for, and asking `span` for one
|
|
317
|
+
* silently yields nothing.
|
|
318
|
+
*/
|
|
319
|
+
terminal(node: unknown): Span | undefined {
|
|
320
|
+
const symbol = (
|
|
321
|
+
node as { symbol?: { startIndex: number; stopIndex: number } }
|
|
322
|
+
)?.symbol;
|
|
323
|
+
if (!symbol) return undefined;
|
|
324
|
+
const start = this.map[symbol.startIndex];
|
|
325
|
+
const end = this.map[symbol.stopIndex + 1];
|
|
326
|
+
if (start === undefined || end === undefined || end < start)
|
|
327
|
+
return undefined;
|
|
328
|
+
return { start, end };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** A parser code-point index as a JS string offset. */
|
|
332
|
+
utf16(codePoint: number): number | undefined {
|
|
333
|
+
return this.map[codePoint];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
text_(c: Ctx | undefined): string | undefined {
|
|
337
|
+
const s = this.span(c);
|
|
338
|
+
return s && this.text.slice(s.start, s.end);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
line(offset: number): number {
|
|
342
|
+
let lo = 0;
|
|
343
|
+
let hi = this.lineStarts.length - 1;
|
|
344
|
+
while (lo < hi) {
|
|
345
|
+
const mid = (lo + hi + 1) >> 1;
|
|
346
|
+
if (this.lineStarts[mid] <= offset) lo = mid;
|
|
347
|
+
else hi = mid - 1;
|
|
348
|
+
}
|
|
349
|
+
return lo;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
positioned(c: Ctx | undefined): Positioned | undefined {
|
|
353
|
+
const span = this.span(c);
|
|
354
|
+
return span && { span, line: this.line(span.start) };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** The whitespace a line begins with, which anything inserted matches. */
|
|
358
|
+
indentAt(offset: number): string {
|
|
359
|
+
const start = this.lineStarts[this.line(offset)];
|
|
360
|
+
return /^[ \t]*/.exec(this.text.slice(start))?.[0] ?? "";
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Every descendant that satisfies `pred`, outermost first. */
|
|
365
|
+
function collect(root: Ctx, pred: (c: Ctx) => boolean, out: Ctx[] = []): Ctx[] {
|
|
366
|
+
if (isRule(root) && pred(root)) out.push(root);
|
|
367
|
+
for (let i = 0; i < (root.childCount ?? 0); i++)
|
|
368
|
+
collect(root.getChild(i), pred, out);
|
|
369
|
+
return out;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** A `{ … }` block of any kind, which is where one scope ends and another begins. */
|
|
373
|
+
const opensScope = (c: Ctx) => has(c, "OCURLY", "CCURLY");
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Descendants that satisfy `pred`, not descending past one that does — nor
|
|
377
|
+
* past a nested `{ … }`, so a filtered measure's `where:` and a `nest:`'s
|
|
378
|
+
* never surface as the enclosing block's own. Depth is structure here, which
|
|
379
|
+
* is the point: no brace counting can be wrong about it.
|
|
380
|
+
*/
|
|
381
|
+
function collectShallow(root: Ctx, pred: (c: Ctx) => boolean): Ctx[] {
|
|
382
|
+
const out: Ctx[] = [];
|
|
383
|
+
const walk = (c: Ctx) => {
|
|
384
|
+
if (!isRule(c)) return;
|
|
385
|
+
if (pred(c)) {
|
|
386
|
+
out.push(c);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (opensScope(c)) return;
|
|
390
|
+
for (let i = 0; i < (c.childCount ?? 0); i++) walk(c.getChild(i));
|
|
391
|
+
};
|
|
392
|
+
for (let i = 0; i < (root.childCount ?? 0); i++) walk(root.getChild(i));
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const call = (c: Ctx, name: string): Ctx | undefined =>
|
|
397
|
+
(c[name] as (() => Ctx) | undefined)?.call(c);
|
|
398
|
+
|
|
399
|
+
const callAll = (c: Ctx, name: string): Ctx[] =>
|
|
400
|
+
((c[name] as (() => Ctx[]) | undefined)?.call(c) as Ctx[]) ?? [];
|
|
401
|
+
|
|
402
|
+
/* ------------------------------------------------------------------ */
|
|
403
|
+
/* Building the model */
|
|
404
|
+
/* ------------------------------------------------------------------ */
|
|
405
|
+
|
|
406
|
+
function readBinding(r: Reader, clause: Ctx): TreeBinding | undefined {
|
|
407
|
+
if (!IS.compare(clause) || (clause.childCount ?? 0) !== 3) return undefined;
|
|
408
|
+
const right = clause.getChild(2);
|
|
409
|
+
if (!IS.givenRef(right)) return undefined;
|
|
410
|
+
const field = r.text_(clause.getChild(0));
|
|
411
|
+
const op = r.text_(clause.getChild(1));
|
|
412
|
+
const given = r.text_(right) ?? "";
|
|
413
|
+
if (field === undefined || op === undefined) return undefined;
|
|
414
|
+
return { field, op: op.trim(), given: given.replace(/^\$/, "") };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function readWhere(r: Reader, ctx: Ctx): TreeWhere | undefined {
|
|
418
|
+
const at = r.positioned(ctx);
|
|
419
|
+
if (!at) return undefined;
|
|
420
|
+
const list = call(ctx, "filterClauseList");
|
|
421
|
+
const clauses: TreeClause[] = [];
|
|
422
|
+
for (const fe of list ? callAll(list, "fieldExpr") : []) {
|
|
423
|
+
const cat = r.positioned(fe);
|
|
424
|
+
if (!cat) continue;
|
|
425
|
+
const givens = collect(fe, IS.givenRef)
|
|
426
|
+
.map((g) => r.text_(g))
|
|
427
|
+
.filter((g): g is string => g !== undefined)
|
|
428
|
+
.map((g) => g.replace(/^\$/, ""));
|
|
429
|
+
clauses.push({ ...cat, givens, ...{ binding: readBinding(r, fe) } });
|
|
430
|
+
}
|
|
431
|
+
return { ...at, clauses };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* A `{ … }` block. `wheres` are the block's OWN `where:` statements: a
|
|
436
|
+
* `nest:`'s body is a `queryProperties` of its own, so its filters never
|
|
437
|
+
* surface here, which is what makes depth a matter of structure rather than
|
|
438
|
+
* of counting braces.
|
|
439
|
+
*/
|
|
440
|
+
function readStage(r: Reader, props: Ctx): TreeStage | undefined {
|
|
441
|
+
const span = r.span(props);
|
|
442
|
+
if (!span) return undefined;
|
|
443
|
+
const statements: Positioned[] = [];
|
|
444
|
+
const wheres: TreeWhere[] = [];
|
|
445
|
+
for (const st of collectShallow(props, IS.queryStatement)) {
|
|
446
|
+
const at = r.positioned(st);
|
|
447
|
+
if (at) statements.push(at);
|
|
448
|
+
const w = call(st, "whereStatement");
|
|
449
|
+
if (w && IS.whereStatement(w)) {
|
|
450
|
+
const read = readWhere(r, w);
|
|
451
|
+
if (read) wheres.push(read);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const openEnd = span.start + 1;
|
|
455
|
+
const closeStart = span.end - 1;
|
|
456
|
+
const oneLine = !r.text.slice(span.start, span.end).includes("\n");
|
|
457
|
+
const indent = statements.length
|
|
458
|
+
? r.indentAt(statements[0].span.start)
|
|
459
|
+
: r.indentAt(span.start) + " ";
|
|
460
|
+
return { span, openEnd, closeStart, statements, wheres, indent, oneLine };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** The `#` annotation lines of a statement's own tag block. */
|
|
464
|
+
function readTags(
|
|
465
|
+
r: Reader,
|
|
466
|
+
statement: Span,
|
|
467
|
+
declStart: number,
|
|
468
|
+
): Array<{ line: number; text: string }> {
|
|
469
|
+
const out: Array<{ line: number; text: string }> = [];
|
|
470
|
+
const first = r.line(statement.start);
|
|
471
|
+
const last = r.line(declStart);
|
|
472
|
+
for (let i = first; i < last; i++) {
|
|
473
|
+
if (r.commentLines.has(i)) continue;
|
|
474
|
+
const text: string = r.text
|
|
475
|
+
.slice(r.lineStarts[i], r.lineStarts[i + 1] ?? r.text.length)
|
|
476
|
+
.trim();
|
|
477
|
+
// `##` is a MODEL annotation and never belongs to a declaration.
|
|
478
|
+
if (text.startsWith("#") && !text.startsWith("##"))
|
|
479
|
+
out.push({ line: i, text });
|
|
480
|
+
}
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function readViewBody(r: Reader, vExpr: Ctx): TreeViewBody {
|
|
485
|
+
// A `->` pipeline: only its FIRST stage is the tile's own, so that is what
|
|
486
|
+
// is read and all that may ever be rewritten.
|
|
487
|
+
const seg = call(vExpr, "segExpr");
|
|
488
|
+
if (!seg) return { kind: "unsupported", why: "an unreadable expression" };
|
|
489
|
+
const pipeline = IS.vArrow(vExpr);
|
|
490
|
+
if (IS.segOps(seg)) {
|
|
491
|
+
const props = call(seg, "queryProperties");
|
|
492
|
+
const stage = props && readStage(r, props);
|
|
493
|
+
return stage
|
|
494
|
+
? { kind: "inline", stage, ...(pipeline ? { pipeline: true } : {}) }
|
|
495
|
+
: { kind: "unsupported", why: "an unreadable body" };
|
|
496
|
+
}
|
|
497
|
+
if (pipeline)
|
|
498
|
+
return { kind: "unsupported", why: "a `->` pipeline from a named view" };
|
|
499
|
+
if (IS.segField(seg)) {
|
|
500
|
+
const fromSpan = r.span(seg);
|
|
501
|
+
if (!fromSpan) return { kind: "unsupported", why: "an unreadable name" };
|
|
502
|
+
return {
|
|
503
|
+
kind: "reference",
|
|
504
|
+
from: r.text.slice(fromSpan.start, fromSpan.end),
|
|
505
|
+
fromSpan,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
if (IS.segRefine(seg)) {
|
|
509
|
+
// `vx + vy + { … }` nests left, so the refinement is the RIGHTMOST
|
|
510
|
+
// operand and the base is everything to its left, as written. Reading
|
|
511
|
+
// only the immediate left operand is what deleted `vy` at head.
|
|
512
|
+
const operands = callAll(seg, "segExpr");
|
|
513
|
+
const lhs = operands[0];
|
|
514
|
+
const rhs = operands[operands.length - 1];
|
|
515
|
+
// A `{ … }` anywhere in the BASE means a second refinement block --
|
|
516
|
+
// `{ … } + { … }`, or `vx + { … } + { … }`. There is then no one block a
|
|
517
|
+
// binding belongs in, and a given already filtered on in the other would
|
|
518
|
+
// be bound a second time, so the whole declaration is left alone.
|
|
519
|
+
let base = lhs;
|
|
520
|
+
while (IS.segRefine(base)) {
|
|
521
|
+
const inner = callAll(base, "segExpr");
|
|
522
|
+
if (inner.some((o) => IS.segOps(o) || IS.segParen(o)))
|
|
523
|
+
return { kind: "unsupported", why: "a chained refinement" };
|
|
524
|
+
base = inner[0];
|
|
525
|
+
}
|
|
526
|
+
if (!base || !IS.segField(base))
|
|
527
|
+
return {
|
|
528
|
+
kind: "unsupported",
|
|
529
|
+
why: "a `{ … } + { … }` compound refinement",
|
|
530
|
+
};
|
|
531
|
+
const fromSpan = r.span(lhs);
|
|
532
|
+
if (!fromSpan || !rhs)
|
|
533
|
+
return { kind: "unsupported", why: "an unreadable refinement" };
|
|
534
|
+
if (!IS.segOps(rhs)) {
|
|
535
|
+
// `vx + vy` with no `{ … }` at all: the base is the WHOLE expression,
|
|
536
|
+
// not its left operand, or a rewrite would drop everything after it.
|
|
537
|
+
const whole = r.span(seg);
|
|
538
|
+
return whole
|
|
539
|
+
? {
|
|
540
|
+
kind: "reference",
|
|
541
|
+
from: r.text.slice(whole.start, whole.end),
|
|
542
|
+
fromSpan: whole,
|
|
543
|
+
}
|
|
544
|
+
: { kind: "unsupported", why: "an unreadable refinement" };
|
|
545
|
+
}
|
|
546
|
+
const from = r.text.slice(fromSpan.start, fromSpan.end);
|
|
547
|
+
const props = call(rhs, "queryProperties");
|
|
548
|
+
const stage = props && readStage(r, props);
|
|
549
|
+
return stage
|
|
550
|
+
? { kind: "reference", from, fromSpan, refinement: stage }
|
|
551
|
+
: { kind: "reference", from, fromSpan };
|
|
552
|
+
}
|
|
553
|
+
return { kind: "unsupported", why: "a parenthesized expression" };
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function readViews(r: Reader, props: Ctx): TreeView[] {
|
|
557
|
+
const out: TreeView[] = [];
|
|
558
|
+
for (const stmt of collectShallow(props, IS.defExploreQuery)) {
|
|
559
|
+
const statement = r.span(stmt);
|
|
560
|
+
const list = call(stmt, "subQueryDefList");
|
|
561
|
+
if (!statement || !list) continue;
|
|
562
|
+
const defs = callAll(list, "exploreQueryDef").filter(IS.exploreQueryDef);
|
|
563
|
+
const keyword = r.terminal(call(stmt, "VIEW"));
|
|
564
|
+
for (const def of defs) {
|
|
565
|
+
const span = r.span(def);
|
|
566
|
+
const nameCtx = call(def, "exploreQueryNameDef");
|
|
567
|
+
const name = r.text_(nameCtx);
|
|
568
|
+
const vExpr = call(def, "vExpr");
|
|
569
|
+
if (!span || !name || !vExpr) continue;
|
|
570
|
+
out.push({
|
|
571
|
+
name,
|
|
572
|
+
span,
|
|
573
|
+
line: r.line(span.start),
|
|
574
|
+
statement,
|
|
575
|
+
tags: readTags(r, statement, keyword?.start ?? span.start),
|
|
576
|
+
siblings: defs.length,
|
|
577
|
+
body: readViewBody(r, vExpr),
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return out;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function readDimensions(r: Reader, props: Ctx): TreeDimension[] {
|
|
585
|
+
const out: TreeDimension[] = [];
|
|
586
|
+
for (const stmt of collectShallow(props, IS.defDimension)) {
|
|
587
|
+
const statement = r.span(stmt);
|
|
588
|
+
const list = call(stmt, "defList");
|
|
589
|
+
if (!statement || !list) continue;
|
|
590
|
+
const keyword = r.terminal(call(stmt, "DIMENSION"));
|
|
591
|
+
for (const def of callAll(list, "fieldDef")) {
|
|
592
|
+
const span = r.span(def);
|
|
593
|
+
// Both halves are nodes the tree hands over. Splitting the text on the
|
|
594
|
+
// word `is` cut `dimension: \`is\` is 1` in half inside its own name --
|
|
595
|
+
// the last place in this module that re-derived Malloy's grammar.
|
|
596
|
+
const name = r.text_(call(def, "fieldNameDef"))?.trim();
|
|
597
|
+
const expression = r.text_(call(def, "fieldExpr"))?.trim();
|
|
598
|
+
if (!span || !name || expression === undefined) continue;
|
|
599
|
+
out.push({
|
|
600
|
+
name,
|
|
601
|
+
expression,
|
|
602
|
+
span,
|
|
603
|
+
line: r.line(span.start),
|
|
604
|
+
statement,
|
|
605
|
+
tags: readTags(r, statement, keyword?.start ?? span.start),
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return out;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function readSources(r: Reader, root: Ctx): TreeSource[] {
|
|
613
|
+
const out: TreeSource[] = [];
|
|
614
|
+
for (const def of collect(root, IS.sourceDefinition)) {
|
|
615
|
+
const span = r.span(def);
|
|
616
|
+
const name = r.text_(call(def, "sourceNameDef"));
|
|
617
|
+
const explore = call(def, "sqExplore");
|
|
618
|
+
if (!span || !name || !explore) continue;
|
|
619
|
+
const exploreSpan = r.span(explore);
|
|
620
|
+
// The base is the leading name of what it extends, bounded by the tree.
|
|
621
|
+
const baseText = exploreSpan
|
|
622
|
+
? r.text.slice(exploreSpan.start, exploreSpan.end)
|
|
623
|
+
: "";
|
|
624
|
+
const base = (
|
|
625
|
+
/^\s*(`[^`]*`|[A-Za-z_][A-Za-z0-9_.]*)/.exec(baseText)?.[1] ?? ""
|
|
626
|
+
).trim();
|
|
627
|
+
const propsCtx = collectShallow(explore, IS.exploreProperties)[0];
|
|
628
|
+
const properties = propsCtx && readStage(r, propsCtx);
|
|
629
|
+
const statement: Span = {
|
|
630
|
+
start: r.lineStarts[r.line(span.start)],
|
|
631
|
+
end: span.end,
|
|
632
|
+
};
|
|
633
|
+
const wheres: TreeWhere[] = [];
|
|
634
|
+
if (propsCtx)
|
|
635
|
+
for (const st of collectShallow(propsCtx, IS.whereStatement)) {
|
|
636
|
+
const w = readWhere(r, st);
|
|
637
|
+
if (w) wheres.push(w);
|
|
638
|
+
}
|
|
639
|
+
out.push({
|
|
640
|
+
name,
|
|
641
|
+
base,
|
|
642
|
+
span,
|
|
643
|
+
line: r.line(span.start),
|
|
644
|
+
statement,
|
|
645
|
+
...(properties ? { properties } : {}),
|
|
646
|
+
views: propsCtx ? readViews(r, propsCtx) : [],
|
|
647
|
+
dimensions: propsCtx ? readDimensions(r, propsCtx) : [],
|
|
648
|
+
wheres,
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
return out;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function readGivens(r: Reader, root: Ctx): TreeGiven[] {
|
|
655
|
+
const out: TreeGiven[] = [];
|
|
656
|
+
for (const statement of collect(root, IS.givenStatement)) {
|
|
657
|
+
const keyword = r.terminal(call(statement, "GIVEN"));
|
|
658
|
+
const list = call(statement, "givenDefList");
|
|
659
|
+
const headerLine = keyword ? r.line(keyword.start) : undefined;
|
|
660
|
+
for (const def of list ? callAll(list, "givenDef") : []) {
|
|
661
|
+
const whole = r.span(def);
|
|
662
|
+
const nameSpan = r.span(call(def, "givenNameDef"));
|
|
663
|
+
const name = nameSpan && r.text.slice(nameSpan.start, nameSpan.end);
|
|
664
|
+
if (!whole || !nameSpan || !name) continue;
|
|
665
|
+
// The context takes in the `#` tag block above the name, which is the
|
|
666
|
+
// control contract rather than part of the declaration.
|
|
667
|
+
const span = { start: nameSpan.start, end: whole.end };
|
|
668
|
+
const line = r.line(span.start);
|
|
669
|
+
out.push({
|
|
670
|
+
name,
|
|
671
|
+
declaration: r.text.slice(span.start, span.end),
|
|
672
|
+
span,
|
|
673
|
+
line,
|
|
674
|
+
statement: { start: r.lineStarts[line], end: span.end },
|
|
675
|
+
tags: readTags(r, whole, span.start),
|
|
676
|
+
...(headerLine !== undefined && headerLine !== line
|
|
677
|
+
? { blockHeader: headerLine }
|
|
678
|
+
: {}),
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function readImports(r: Reader, root: Ctx): TreeImport[] {
|
|
686
|
+
const out: TreeImport[] = [];
|
|
687
|
+
for (const stmt of collect(root, IS.importStatement)) {
|
|
688
|
+
const span = r.span(stmt);
|
|
689
|
+
const url = r.text_(call(stmt, "importURL"));
|
|
690
|
+
if (!span || url === undefined) continue;
|
|
691
|
+
const select = call(stmt, "importSelect");
|
|
692
|
+
const names = select
|
|
693
|
+
? callAll(select, "importItem")
|
|
694
|
+
.map((i) => r.text_(i))
|
|
695
|
+
.filter((n): n is string => n !== undefined)
|
|
696
|
+
.map((n) => n.trim())
|
|
697
|
+
: undefined;
|
|
698
|
+
out.push({
|
|
699
|
+
from: url.replace(/^['"]|['"]$/g, ""),
|
|
700
|
+
...(names && names.length > 0 ? { names } : {}),
|
|
701
|
+
span,
|
|
702
|
+
line: r.line(span.start),
|
|
703
|
+
statement: span,
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
return out;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/* ------------------------------------------------------------------ */
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Parse `text`, or refuse.
|
|
713
|
+
*
|
|
714
|
+
* A file with ANY syntax error is refused rather than edited. ANTLR recovers
|
|
715
|
+
* from an error by inventing structure: measured on a file with one, the tree
|
|
716
|
+
* reports a view that is not there, a range that runs backwards, and drops
|
|
717
|
+
* every declaration after the error — all without raising anything a caller
|
|
718
|
+
* could notice. An edit located in that tree deletes real code, and neither
|
|
719
|
+
* the read-back gate nor the parse gate can see it. The server cannot compile
|
|
720
|
+
* such a file either, so the way out of one is the code editor, not this.
|
|
721
|
+
*/
|
|
722
|
+
export async function parseMalloy(text: string): Promise<ParseResult> {
|
|
723
|
+
let translation: Translation;
|
|
724
|
+
try {
|
|
725
|
+
translation = await translate(text, "file://dashboard-builder.malloy");
|
|
726
|
+
} catch (error) {
|
|
727
|
+
return { ok: false, reason: `Malloy could not read this file: ${error}` };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
const syntax = translation.problems.filter((p) => p.code === "syntax-error");
|
|
731
|
+
if (syntax.length > 0)
|
|
732
|
+
return {
|
|
733
|
+
ok: false,
|
|
734
|
+
reason: `This file has a Malloy syntax error, so it cannot be edited here: ${
|
|
735
|
+
syntax[0].message ?? "unknown"
|
|
736
|
+
}`,
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
const parse = translation.parse;
|
|
740
|
+
const root = parse?.root as Ctx | undefined;
|
|
741
|
+
if (!root || !isRule(root) || typeof root.getChild !== "function")
|
|
742
|
+
return {
|
|
743
|
+
ok: false,
|
|
744
|
+
reason:
|
|
745
|
+
"This build of Malloy does not expose a parse tree the builder can " +
|
|
746
|
+
`read (malloy ${parse?.malloyVersion ?? "unknown"}), so editing is off.`,
|
|
747
|
+
};
|
|
748
|
+
|
|
749
|
+
// The same shape assertion as above, for the TOKEN stream, which the tree
|
|
750
|
+
// check cannot speak for. `@malloydata/malloy` is a peer dependency, so a
|
|
751
|
+
// host may resolve a build whose token API differs -- and a comment index
|
|
752
|
+
// that silently comes back empty is worse than a refusal: every comment
|
|
753
|
+
// guard passes clean while comments are deleted, and a `#` line inside a
|
|
754
|
+
// `/* … */` starts reading as a real tag. Neither gate can see either.
|
|
755
|
+
const tokenStream = (parse?.tokenStream ?? {}) as TokenStream;
|
|
756
|
+
const tokens =
|
|
757
|
+
typeof tokenStream.getTokens === "function"
|
|
758
|
+
? tokenStream.getTokens()
|
|
759
|
+
: undefined;
|
|
760
|
+
if (
|
|
761
|
+
!tokens ||
|
|
762
|
+
typeof tokenStream.tokenSource?.vocabulary?.getSymbolicName !==
|
|
763
|
+
"function" ||
|
|
764
|
+
(tokens.length === 0 && text.trim() !== "")
|
|
765
|
+
)
|
|
766
|
+
return {
|
|
767
|
+
ok: false,
|
|
768
|
+
reason:
|
|
769
|
+
"This build of Malloy does not expose a token stream the builder " +
|
|
770
|
+
`can read (malloy ${parse?.malloyVersion ?? "unknown"}), so it ` +
|
|
771
|
+
"cannot tell a comment from code and editing is off.",
|
|
772
|
+
};
|
|
773
|
+
|
|
774
|
+
const r = new Reader(text);
|
|
775
|
+
// Before anything is read: `readTags` has to know which lines are comment,
|
|
776
|
+
// and a source is read through it.
|
|
777
|
+
const comments = commentIndex(r, tokenStream);
|
|
778
|
+
r.commentLines = comments.lines;
|
|
779
|
+
const sources = readSources(r, root);
|
|
780
|
+
|
|
781
|
+
// The shape assertion, on real content rather than on the API's presence:
|
|
782
|
+
// a file that declares a source and yields none means the tree is not what
|
|
783
|
+
// this module was written against, and locating an edit in it is guesswork.
|
|
784
|
+
if (sources.length === 0 && /^\s*source:/m.test(text))
|
|
785
|
+
return {
|
|
786
|
+
ok: false,
|
|
787
|
+
reason:
|
|
788
|
+
"The builder could not locate this file's sources in Malloy's parse " +
|
|
789
|
+
`tree (malloy ${parse?.malloyVersion ?? "unknown"}), so editing is off.`,
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
return {
|
|
793
|
+
ok: true,
|
|
794
|
+
parsed: {
|
|
795
|
+
text,
|
|
796
|
+
lineStarts: r.lineStarts,
|
|
797
|
+
imports: readImports(r, root),
|
|
798
|
+
sources,
|
|
799
|
+
givens: readGivens(r, root),
|
|
800
|
+
trailingComment: (line) => comments.trailing.get(line),
|
|
801
|
+
comments: comments.all,
|
|
802
|
+
commentLine: (line) => comments.lines.has(line),
|
|
803
|
+
commentIn: (span) =>
|
|
804
|
+
comments.all.find(
|
|
805
|
+
(at) => at.start >= span.start && at.start < span.end,
|
|
806
|
+
),
|
|
807
|
+
blockStart: (line) => blockStart(r, comments.lines, line),
|
|
808
|
+
},
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/** One of the translator's complaints. */
|
|
813
|
+
export interface MalloyProblem {
|
|
814
|
+
code?: string;
|
|
815
|
+
message?: string;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** One parse of one file, stopped at the parse step. */
|
|
819
|
+
export interface Translation {
|
|
820
|
+
problems: MalloyProblem[];
|
|
821
|
+
parse?: { root?: unknown; tokenStream?: unknown; malloyVersion?: string };
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* The ONE place the translator's shape is written down. `@malloydata/malloy` is
|
|
826
|
+
* a peer dependency, so nothing here can import its types and every caller has
|
|
827
|
+
* to hand-type a cast; a second copy is a second thing to miss when the shape
|
|
828
|
+
* upstream moves.
|
|
829
|
+
*
|
|
830
|
+
* The translation stops at the first step. A document with imports comes back
|
|
831
|
+
* asking for urls, by which point it has been parsed and nothing has been
|
|
832
|
+
* resolved -- so callers see every syntax error and none of the semantic ones.
|
|
833
|
+
*/
|
|
834
|
+
export async function translate(
|
|
835
|
+
text: string,
|
|
836
|
+
url: string,
|
|
837
|
+
): Promise<Translation> {
|
|
838
|
+
// Imported dynamically, never statically: `builder-entry.ts` installs the
|
|
839
|
+
// `process.env` shim the parser's dependencies read at module scope, and a
|
|
840
|
+
// static import would be evaluated before that shim runs.
|
|
841
|
+
const { MalloyTranslator } = await import("@malloydata/malloy");
|
|
842
|
+
const translator = new MalloyTranslator(url, null, {
|
|
843
|
+
urls: { [url]: text },
|
|
844
|
+
}) as unknown as {
|
|
845
|
+
translate(): { problems?: MalloyProblem[] };
|
|
846
|
+
parseStep?: { response?: { parse?: Translation["parse"] } };
|
|
847
|
+
};
|
|
848
|
+
return {
|
|
849
|
+
problems: translator.translate().problems ?? [],
|
|
850
|
+
parse: translator.parseStep?.response?.parse,
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* The comments, taken from the LEXER's own tokens rather than from a scan for
|
|
856
|
+
* `//`: a `//` inside a string literal is not a comment, and every scan here
|
|
857
|
+
* that had to know that got it wrong at least once.
|
|
858
|
+
*
|
|
859
|
+
* BOTH token kinds, because Malloy has two and spells a comment three ways:
|
|
860
|
+
* `//` and `--` lex as `COMMENT_TO_EOL`, `/* … *\/` as `BLOCK_COMMENT`. A
|
|
861
|
+
* filter on the first name alone left every block comment out of this index,
|
|
862
|
+
* so it was invisible to `commentIn` -- and a writer asking that before it
|
|
863
|
+
* deleted a range was told there was nothing there to lose.
|
|
864
|
+
*
|
|
865
|
+
* A comment alone on its line belongs to the block above a declaration; one
|
|
866
|
+
* that follows code is a trailing comment, and anything appended to that line
|
|
867
|
+
* has to go before it.
|
|
868
|
+
*/
|
|
869
|
+
function commentIndex(
|
|
870
|
+
r: Reader,
|
|
871
|
+
tokenStream: TokenStream,
|
|
872
|
+
): { trailing: Map<number, Span>; lines: Set<number>; all: Span[] } {
|
|
873
|
+
const trailing = new Map<number, Span>();
|
|
874
|
+
const lines = new Set<number>();
|
|
875
|
+
const all: Span[] = [];
|
|
876
|
+
const vocabulary = tokenStream.tokenSource?.vocabulary;
|
|
877
|
+
for (const token of tokenStream.getTokens?.() ?? []) {
|
|
878
|
+
const kind = vocabulary?.getSymbolicName(token.type);
|
|
879
|
+
if (kind !== "COMMENT_TO_EOL" && kind !== "BLOCK_COMMENT") continue;
|
|
880
|
+
const start = r.utf16(token.startIndex);
|
|
881
|
+
let end = r.utf16(token.stopIndex + 1);
|
|
882
|
+
if (start === undefined || end === undefined || end < start) continue;
|
|
883
|
+
// The token runs to the newline and takes it with it; the span must not,
|
|
884
|
+
// or anything inserted before the comment lands on the next line.
|
|
885
|
+
while (
|
|
886
|
+
end > start &&
|
|
887
|
+
(r.text[end - 1] === "\n" || r.text[end - 1] === "\r")
|
|
888
|
+
)
|
|
889
|
+
end--;
|
|
890
|
+
all.push({ start, end });
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// The file with every comment blanked out, newlines kept so the same offsets
|
|
894
|
+
// still address the same lines.
|
|
895
|
+
//
|
|
896
|
+
// Both questions below are about what ELSE is on a line, and asking only
|
|
897
|
+
// what precedes a comment cannot answer either: `/* tidy */ dimension: x is
|
|
898
|
+
// 1` is not a comment line, and `a ~ $A, /* c */ b ~ $B` has no trailing
|
|
899
|
+
// comment. Reading the first as a comment line made the walk above a
|
|
900
|
+
// declaration step over a line that declares something and collect the `#`
|
|
901
|
+
// tag belonging to it -- and report success.
|
|
902
|
+
const ordered = [...all].sort((a, b) => a.start - b.start);
|
|
903
|
+
let code = "";
|
|
904
|
+
let at = 0;
|
|
905
|
+
for (const span of ordered) {
|
|
906
|
+
code += r.text.slice(at, Math.max(at, span.start));
|
|
907
|
+
code += r.text
|
|
908
|
+
.slice(Math.max(at, span.start), Math.max(at, span.end))
|
|
909
|
+
.replace(/[^\n\r]/g, " ");
|
|
910
|
+
at = Math.max(at, span.end);
|
|
911
|
+
}
|
|
912
|
+
code += r.text.slice(at);
|
|
913
|
+
const codeOn = (line: number) =>
|
|
914
|
+
code.slice(r.lineStarts[line], r.lineStarts[line + 1] ?? code.length);
|
|
915
|
+
|
|
916
|
+
for (const span of all) {
|
|
917
|
+
const first = r.line(span.start);
|
|
918
|
+
const last = r.line(span.end - 1);
|
|
919
|
+
for (let l = first; l <= last; l++)
|
|
920
|
+
if (codeOn(l).trim() === "") lines.add(l);
|
|
921
|
+
// Trailing: code before it, and nothing but whitespace after it on the
|
|
922
|
+
// line it ends on. Anything appended at a statement's end goes before it.
|
|
923
|
+
const before = code.slice(r.lineStarts[first], span.start).trim();
|
|
924
|
+
const after = code
|
|
925
|
+
.slice(span.end, r.lineStarts[last + 1] ?? code.length)
|
|
926
|
+
.trim();
|
|
927
|
+
if (before !== "" && after === "") trailing.set(last, span);
|
|
928
|
+
}
|
|
929
|
+
return { trailing, lines, all };
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* The first line of the `#`/comment block above `line`, stopping at a blank line.
|
|
934
|
+
* A blank line is the author's own separator, which is why it is the boundary
|
|
935
|
+
* rather than a count or a guess about what a comment says.
|
|
936
|
+
*/
|
|
937
|
+
function blockStart(
|
|
938
|
+
r: Reader,
|
|
939
|
+
commentLines: Set<number>,
|
|
940
|
+
line: number,
|
|
941
|
+
): number {
|
|
942
|
+
let start = line;
|
|
943
|
+
for (let i = line - 1; i >= 0; i--) {
|
|
944
|
+
const text = r.text
|
|
945
|
+
.slice(r.lineStarts[i], r.lineStarts[i + 1] ?? r.text.length)
|
|
946
|
+
.trim();
|
|
947
|
+
// A blank line is the boundary -- unless it is inside a block comment,
|
|
948
|
+
// where it is the author's paragraph break rather than their separator.
|
|
949
|
+
if (text === "" && !commentLines.has(i)) break;
|
|
950
|
+
if (text.startsWith("#") || commentLines.has(i)) start = i;
|
|
951
|
+
else break;
|
|
952
|
+
}
|
|
953
|
+
return start;
|
|
954
|
+
}
|