@malloydata/malloy 0.0.70-dev230810160240 → 0.0.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tags.js CHANGED
@@ -21,8 +21,189 @@
21
21
  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
22
  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
23
  */
24
+ var __importDefault = (this && this.__importDefault) || function (mod) {
25
+ return (mod && mod.__esModule) ? mod : { "default": mod };
26
+ };
24
27
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.parseTagProperties = exports.Tags = void 0;
28
+ exports.parseTagProperties = exports.Tags = exports.Tag = void 0;
29
+ const tree_1 = require("antlr4ts/tree");
30
+ const MalloyTagLexer_1 = require("./lang/lib/Malloy/MalloyTagLexer");
31
+ const MalloyTagParser_1 = require("./lang/lib/Malloy/MalloyTagParser");
32
+ const antlr4ts_1 = require("antlr4ts");
33
+ const parse_utils_1 = require("./lang/parse-utils");
34
+ const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
35
+ /**
36
+ * Class for interacting with the parsed output of an annotation
37
+ * containing the Malloy tag language. Used by the parser to
38
+ * generate parsed data, and as an API to that data.
39
+ * ```
40
+ * tag.text(p?) => string value of tag.p or ''
41
+ * tag.array(p?) => Tag[] value of tag.p or []
42
+ * tag.numeric(p?) => numeric value of tag.p or NaN
43
+ * tag.dict => Record<string, Tag> of tag properties
44
+ * tag.tag(p) => Tag value of tag.p
45
+ * ```
46
+ */
47
+ class Tag {
48
+ constructor(from = {}) {
49
+ if (from.eq) {
50
+ this.eq = from.eq;
51
+ }
52
+ if (from.properties) {
53
+ this.properties = from.properties;
54
+ }
55
+ }
56
+ static tagFrom(from = {}) {
57
+ if (from instanceof Tag) {
58
+ return from;
59
+ }
60
+ return new Tag(from);
61
+ }
62
+ static id(t) {
63
+ let thisTagId = Tag.ids.get(t);
64
+ if (thisTagId === undefined) {
65
+ thisTagId = Tag.nextTagId;
66
+ Tag.ids.set(t, thisTagId);
67
+ Tag.nextTagId += 1;
68
+ }
69
+ return thisTagId;
70
+ }
71
+ peek() {
72
+ let str = `#${Tag.id(this)}`;
73
+ if (this.eq) {
74
+ if (typeof this.eq === 'string') {
75
+ str += `=${this.eq}`;
76
+ }
77
+ else {
78
+ str += '=[]';
79
+ }
80
+ }
81
+ if (this.properties) {
82
+ const propStr = Object.keys(this.properties)
83
+ .map(k => `${k}:`)
84
+ .join(', ');
85
+ str += `{${propStr}}`;
86
+ }
87
+ return str;
88
+ }
89
+ /**
90
+ * Parse a line of Malloy tag language into a Tag which can be queried
91
+ * @param source -- The source line to be parsed. If the string starts with #, then it skips
92
+ * all characters up to the first space.
93
+ * @param extending A tag which this line will be extending
94
+ * @param importing Outer "scopes" for $() references
95
+ * @returns Something shaped like { tag: Tag , log: ParseErrors[] }
96
+ */
97
+ static fromTagline(str, extending, ...importing) {
98
+ return parseTagline(str, extending, importing, __filename, 0, 0);
99
+ }
100
+ static annotationToTaglines(annote, prefix) {
101
+ annote || (annote = {});
102
+ const tagLines = annote.inherits
103
+ ? Tag.annotationToTaglines(annote.inherits, prefix)
104
+ : [];
105
+ function prefixed(na) {
106
+ const ret = [];
107
+ for (const n of na || []) {
108
+ if (prefix === undefined || n.text.match(prefix)) {
109
+ ret.push(n.text);
110
+ }
111
+ }
112
+ return ret;
113
+ }
114
+ return tagLines.concat(prefixed(annote.blockNotes), prefixed(annote.notes));
115
+ }
116
+ static annotationToTag(annote, spec = {}) {
117
+ let extending = spec.extending || new Tag();
118
+ const prefix = spec.prefix || /^##? /;
119
+ annote || (annote = {});
120
+ const allErrs = [];
121
+ if (annote.inherits) {
122
+ const inherits = Tag.annotationToTag(annote.inherits, spec);
123
+ allErrs.push(...inherits.log);
124
+ extending = inherits.tag;
125
+ }
126
+ const allNotes = [];
127
+ if (annote.blockNotes) {
128
+ allNotes.push(...annote.blockNotes);
129
+ }
130
+ if (annote.notes) {
131
+ allNotes.push(...annote.notes);
132
+ }
133
+ for (const note of allNotes) {
134
+ if (note.text.match(prefix)) {
135
+ const noteParse = parseTagline(note.text, extending, spec.scopes || [], note.at.url, note.at.range.start.line, note.at.range.start.character);
136
+ extending = noteParse.tag;
137
+ allErrs.push(...noteParse.log);
138
+ }
139
+ }
140
+ return { tag: extending, log: allErrs };
141
+ }
142
+ find(at) {
143
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
144
+ let findIn = this;
145
+ for (const seg of at) {
146
+ findIn = findIn.properties && Tag.tagFrom(findIn.properties[seg]);
147
+ if (!findIn) {
148
+ return undefined;
149
+ }
150
+ }
151
+ return findIn;
152
+ }
153
+ tag(...at) {
154
+ return this.find(at);
155
+ }
156
+ has(...at) {
157
+ return !!this.find(at);
158
+ }
159
+ text(...at) {
160
+ var _a;
161
+ const str = (_a = this.find(at)) === null || _a === void 0 ? void 0 : _a.eq;
162
+ if (typeof str === 'string') {
163
+ return str;
164
+ }
165
+ return '';
166
+ }
167
+ numeric(...at) {
168
+ var _a;
169
+ const str = (_a = this.find(at)) === null || _a === void 0 ? void 0 : _a.eq;
170
+ if (typeof str === 'string') {
171
+ return Number.parseFloat(str);
172
+ }
173
+ return NaN;
174
+ }
175
+ get dict() {
176
+ const newDict = {};
177
+ if (this.properties) {
178
+ for (const key in this.properties) {
179
+ newDict[key] = Tag.tagFrom(this.properties[key]);
180
+ }
181
+ }
182
+ return newDict;
183
+ }
184
+ array(...at) {
185
+ var _a;
186
+ const array = (_a = this.find(at)) === null || _a === void 0 ? void 0 : _a.eq;
187
+ if (array === undefined || typeof array === 'string') {
188
+ return [];
189
+ }
190
+ return array.map(el => typeof el === 'string' ? new Tag({ eq: el }) : Tag.tagFrom(el));
191
+ }
192
+ // Has the sometimes desireable side effect of initalizing properties
193
+ getProperties() {
194
+ if (this.properties === undefined) {
195
+ this.properties = {};
196
+ }
197
+ return this.properties;
198
+ }
199
+ clone() {
200
+ return new Tag((0, cloneDeep_1.default)(this));
201
+ }
202
+ }
203
+ exports.Tag = Tag;
204
+ // --- Just for debugging ---
205
+ Tag.ids = new Map();
206
+ Tag.nextTagId = 1000;
26
207
  function isDocTag(a) {
27
208
  return (a === null || a === void 0 ? void 0 : a.docString) !== undefined;
28
209
  }
@@ -52,11 +233,14 @@ function tagList(tagNode) {
52
233
  if (!tagNode) {
53
234
  return [];
54
235
  }
55
- return [
56
- ...(tagNode.inherits ? tagList(tagNode.inherits) : []),
57
- ...(tagNode.blockNotes || []),
58
- ...(tagNode.notes || []),
59
- ];
236
+ const justText = tagNode.inherits ? tagList(tagNode.inherits) : [];
237
+ if (tagNode.blockNotes) {
238
+ justText.push(...tagNode.blockNotes.map(bn => bn.text));
239
+ }
240
+ if (tagNode.notes) {
241
+ justText.push(...tagNode.notes.map(n => n.text));
242
+ }
243
+ return justText;
60
244
  }
61
245
  /**
62
246
  * Lines which start '#"' are doc strings
@@ -85,13 +269,6 @@ function parseTag(src, tagProp) {
85
269
  }
86
270
  }
87
271
  function parseTagProperties(src, tagProp) {
88
- /*
89
- * I went back and forth if the grammar for these annotations should be
90
- * in the parser or the lexer. Eventually the fact that the lexer ate
91
- * newlines meant I couldn't figure out how to do it in the parser.
92
- *
93
- * Seems wrong to be writing a parser though.
94
- */
95
272
  const tokens = tokenize(src);
96
273
  let tn = 0;
97
274
  const lastToken = tokens.length - 1;
@@ -161,4 +338,215 @@ function tokenize(src) {
161
338
  }
162
339
  return parts;
163
340
  }
341
+ class TagErrorListener {
342
+ constructor(sourceURL, atLine, fromChar) {
343
+ this.sourceURL = sourceURL;
344
+ this.atLine = atLine;
345
+ this.fromChar = fromChar;
346
+ this.log = [];
347
+ }
348
+ syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, _e) {
349
+ const errAt = {
350
+ line: this.atLine,
351
+ character: this.fromChar + charPositionInLine,
352
+ };
353
+ const range = { start: errAt, end: errAt };
354
+ const logMsg = {
355
+ message: msg,
356
+ at: { url: this.sourceURL, range },
357
+ severity: 'error',
358
+ };
359
+ this.log.push(logMsg);
360
+ }
361
+ }
362
+ function getBuildOn(ctx) {
363
+ const buildOn = ctx['buildOn'];
364
+ if (buildOn instanceof Tag) {
365
+ return buildOn;
366
+ }
367
+ return new Tag();
368
+ }
369
+ function parsePath(buildOn, path) {
370
+ let writeInto = buildOn.getProperties();
371
+ for (const p of path.slice(0, path.length - 1)) {
372
+ let next;
373
+ if (writeInto[p] === undefined) {
374
+ next = new Tag({});
375
+ writeInto[p] = next;
376
+ }
377
+ else {
378
+ next = Tag.tagFrom(writeInto[p]);
379
+ }
380
+ writeInto = next.getProperties();
381
+ }
382
+ return [path[path.length - 1], writeInto];
383
+ }
384
+ function getString(ctx) {
385
+ return ctx.BARE_STRING() ? ctx.text : (0, parse_utils_1.parseString)(ctx.text, ctx.text[0]);
386
+ }
387
+ function parseTagline(source, extending, outerScope, sourceURL, onLine, atChar) {
388
+ if (source[0] === '#') {
389
+ const skipTo = source.indexOf(' ');
390
+ if (skipTo > 0) {
391
+ source = source.slice(skipTo);
392
+ }
393
+ else {
394
+ source = '';
395
+ }
396
+ }
397
+ const inputStream = antlr4ts_1.CharStreams.fromString(source);
398
+ const lexer = new MalloyTagLexer_1.MalloyTagLexer(inputStream);
399
+ const tokenStream = new antlr4ts_1.CommonTokenStream(lexer);
400
+ const taglineParser = new MalloyTagParser_1.MalloyTagParser(tokenStream);
401
+ taglineParser.removeErrorListeners();
402
+ const pLog = new TagErrorListener(sourceURL, onLine, atChar);
403
+ taglineParser.addErrorListener(pLog);
404
+ const tagTree = taglineParser.tagLine();
405
+ const treeWalker = new TaglineParser(outerScope);
406
+ const tag = treeWalker.tagLineToTag(tagTree, extending);
407
+ return { tag, log: pLog.log };
408
+ }
409
+ class TaglineParser extends tree_1.AbstractParseTreeVisitor {
410
+ constructor(outerScopes = []) {
411
+ super();
412
+ this.scopes = [];
413
+ this.scopes.unshift(...outerScopes);
414
+ }
415
+ defaultResult() {
416
+ return new Tag();
417
+ }
418
+ visitString(ctx) {
419
+ return new Tag({ eq: getString(ctx) });
420
+ }
421
+ getPropName(ctx) {
422
+ return ctx.string().map(cx => getString(cx));
423
+ }
424
+ getTags(tags, tagLine) {
425
+ for (const tagSpec of tags) {
426
+ // Stash the current state of this tag in the context and then visit it
427
+ // visit functions should alter the tagLine
428
+ tagSpec['buildOn'] = tagLine;
429
+ this.visit(tagSpec);
430
+ }
431
+ return tagLine;
432
+ }
433
+ tagLineToTag(ctx, extending) {
434
+ extending = (extending === null || extending === void 0 ? void 0 : extending.clone()) || new Tag({});
435
+ this.scopes.unshift(extending);
436
+ this.getTags(ctx.tagSpec(), extending);
437
+ return extending;
438
+ }
439
+ visitTagLine(_ctx) {
440
+ throw new Error('INTERNAL: ERROR: Call tagLineToTag, not vistTagLine');
441
+ return this.defaultResult();
442
+ }
443
+ visitProperties(ctx) {
444
+ return this.getTags(ctx.tagSpec(), getBuildOn(ctx));
445
+ }
446
+ visitArrayValue(ctx) {
447
+ return new Tag({ eq: this.getArray(ctx) });
448
+ }
449
+ getArray(ctx) {
450
+ return ctx.arrayElement().map(v => this.visit(v));
451
+ }
452
+ visitArrayElement(ctx) {
453
+ const propCx = ctx.properties();
454
+ const properties = propCx ? this.visitProperties(propCx) : undefined;
455
+ const strCx = ctx.string();
456
+ let value = strCx ? getString(strCx) : undefined;
457
+ const arrayCx = ctx.arrayValue();
458
+ if (arrayCx) {
459
+ value = this.getArray(arrayCx);
460
+ }
461
+ if (properties) {
462
+ if (value) {
463
+ properties.eq = value;
464
+ }
465
+ return properties;
466
+ }
467
+ const refCx = ctx.reference();
468
+ if (refCx) {
469
+ return this.visitReference(refCx);
470
+ }
471
+ return new Tag({ eq: value });
472
+ }
473
+ visitReference(ctx) {
474
+ const path = this.getPropName(ctx.propName());
475
+ for (const scope of this.scopes) {
476
+ // first scope which has the first component gets to resolve the whole path
477
+ if (scope.has(path[0])) {
478
+ const refTo = scope.tag(...path);
479
+ if (refTo) {
480
+ return refTo.clone();
481
+ }
482
+ break;
483
+ }
484
+ }
485
+ // MTOY TODO SYNTAX ERROR NOT FOUND
486
+ return this.defaultResult();
487
+ }
488
+ visitTagEq(ctx) {
489
+ const buildOn = getBuildOn(ctx);
490
+ const name = this.getPropName(ctx.propName());
491
+ const [writeKey, writeInto] = parsePath(buildOn, name);
492
+ const eq = this.visit(ctx.eqValue());
493
+ const propCx = ctx.properties();
494
+ if (propCx) {
495
+ // a.b.c { -y } means i want to do -y on
496
+ if (propCx.DOTTY() === undefined) {
497
+ const properties = this.visitProperties(propCx).dict;
498
+ // Add new properties old value
499
+ writeInto[writeKey] = { ...eq, properties };
500
+ }
501
+ else {
502
+ // preserve old properties, add new value
503
+ writeInto[writeKey] = { ...writeInto[writeKey], ...eq };
504
+ }
505
+ }
506
+ else {
507
+ writeInto[writeKey] = eq;
508
+ }
509
+ return buildOn;
510
+ }
511
+ visitTagReplaceProperties(ctx) {
512
+ const buildOn = getBuildOn(ctx);
513
+ const name = this.getPropName(ctx.propName());
514
+ const [writeKey, writeInto] = parsePath(buildOn, name);
515
+ const propCx = ctx.properties();
516
+ const props = this.visitProperties(propCx);
517
+ if (ctx.DOTTY() === undefined) {
518
+ // No dots, thropw away the value
519
+ writeInto[writeKey] = { properties: props.dict };
520
+ }
521
+ else {
522
+ /// DOTS, just update the properties
523
+ writeInto[writeKey].properties = props.dict;
524
+ }
525
+ return buildOn;
526
+ }
527
+ visitTagUpdateProperties(ctx) {
528
+ const buildOn = getBuildOn(ctx);
529
+ const name = this.getPropName(ctx.propName());
530
+ const [writeKey, writeInto] = parsePath(buildOn, name);
531
+ const propCx = ctx.properties();
532
+ propCx['buildOn'] = Tag.tagFrom(writeInto[writeKey]);
533
+ const props = this.visitProperties(propCx);
534
+ const thisObj = writeInto[writeKey] || {};
535
+ const properties = { ...thisObj.properties, ...props.dict };
536
+ writeInto[writeKey] = { ...thisObj, properties };
537
+ return buildOn;
538
+ }
539
+ visitTagDef(ctx) {
540
+ const buildOn = getBuildOn(ctx);
541
+ const path = this.getPropName(ctx.propName());
542
+ const [writeKey, writeInto] = parsePath(buildOn, path);
543
+ if (ctx.MINUS()) {
544
+ delete writeInto[writeKey];
545
+ }
546
+ else {
547
+ writeInto[writeKey] = {};
548
+ }
549
+ return buildOn;
550
+ }
551
+ }
164
552
  //# sourceMappingURL=tags.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/malloy",
3
- "version": "0.0.70-dev230810160240",
3
+ "version": "0.0.70",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -24,6 +24,7 @@
24
24
  "dependencies": {
25
25
  "antlr4ts": "^0.5.0-alpha.4",
26
26
  "assert": "^2.0.0",
27
+ "jest-diff": "^29.6.2",
27
28
  "lodash": "^4.17.20",
28
29
  "luxon": "^1.26.0",
29
30
  "uuid": "^8.3.2"