UNPKG

2.42 kBJavaScriptView Raw
1"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _linesandcolumns = require('lines-and-columns'); var _linesandcolumns2 = _interopRequireDefault(_linesandcolumns);
2
3
4var _types = require('../parser/tokenizer/types');
5
6 function formatTokens(code, tokens) {
7 if (tokens.length === 0) {
8 return "";
9 }
10
11 const tokenKeys = Object.keys(tokens[0]).filter(
12 (k) => k !== "type" && k !== "value" && k !== "start" && k !== "end" && k !== "loc",
13 );
14 const typeKeys = Object.keys(tokens[0].type).filter((k) => k !== "label" && k !== "keyword");
15
16 const headings = ["Location", "Label", "Raw", ...tokenKeys, ...typeKeys];
17
18 const lines = new (0, _linesandcolumns2.default)(code);
19 const rows = [headings, ...tokens.map(getTokenComponents)];
20 const padding = headings.map(() => 0);
21 for (const components of rows) {
22 for (let i = 0; i < components.length; i++) {
23 padding[i] = Math.max(padding[i], components[i].length);
24 }
25 }
26 return rows
27 .map((components) => components.map((component, i) => component.padEnd(padding[i])).join(" "))
28 .join("\n");
29
30 function getTokenComponents(token) {
31 const raw = code.slice(token.start, token.end);
32 return [
33 formatRange(token.start, token.end),
34 _types.formatTokenType.call(void 0, token.type),
35 truncate(String(raw), 14),
36 // @ts-ignore: Intentional dynamic access by key.
37 ...tokenKeys.map((key) => formatValue(token[key], key)),
38 // @ts-ignore: Intentional dynamic access by key.
39 ...typeKeys.map((key) => formatValue(token.type[key], key)),
40 ];
41 }
42
43 // eslint-disable-next-line @typescript-eslint/no-explicit-any
44 function formatValue(value, key) {
45 if (value === true) {
46 return key;
47 } else if (value === false || value === null) {
48 return "";
49 } else {
50 return String(value);
51 }
52 }
53
54 function formatRange(start, end) {
55 return `${formatPos(start)}-${formatPos(end)}`;
56 }
57
58 function formatPos(pos) {
59 const location = lines.locationForIndex(pos);
60 if (!location) {
61 return "Unknown";
62 } else {
63 return `${location.line + 1}:${location.column + 1}`;
64 }
65 }
66} exports.default = formatTokens;
67
68function truncate(s, length) {
69 if (s.length > length) {
70 return `${s.slice(0, length - 3)}...`;
71 } else {
72 return s;
73 }
74}