yaml-dsl-spec 0.3.1 → 0.3.3
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/index.js +3 -0
- package/lib/format-function.js +571 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -16,6 +16,7 @@ const { Diagnostic } = require('./lib/diagnostic-report');
|
|
|
16
16
|
const { Position } = require('./lib/source-position');
|
|
17
17
|
const { Node, numberJson } = require('./lib/yaml-node');
|
|
18
18
|
const { codeSpan } = require('./lib/problem-wording');
|
|
19
|
+
const { formatLayout, parseLayout } = require('./lib/format-function');
|
|
19
20
|
const functionTable = require('./lib/function-table');
|
|
20
21
|
const dslDefinition = require('./lib/dsl-definition');
|
|
21
22
|
const jsonPath = require('./lib/json-path');
|
|
@@ -40,6 +41,8 @@ module.exports = {
|
|
|
40
41
|
parseCallKey: functionTable.parseCallKey,
|
|
41
42
|
closestName: schemaValidation.closestName,
|
|
42
43
|
codeSpan,
|
|
44
|
+
formatLayout,
|
|
45
|
+
parseLayout,
|
|
43
46
|
yamlReader: { parseYaml: yamlReader.parseYaml },
|
|
44
47
|
dslDefinition: { dslDefinitionFromJson: dslDefinition.dslDefinitionFromJson },
|
|
45
48
|
jsonPath: { PathPattern: jsonPath.PathPattern, PathSet: jsonPath.PathSet },
|
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeSpan } = require('./problem-wording');
|
|
4
|
+
|
|
5
|
+
const FORMAT_PART_LIMIT = 1000;
|
|
6
|
+
const MAXIMUM_TIME_DIGITS = 9;
|
|
7
|
+
const EARLIEST_FORMAT_SECONDS = -62167219200;
|
|
8
|
+
const LATEST_FORMAT_SECONDS = 253402300800;
|
|
9
|
+
const SECONDS_PER_DAY = 86400;
|
|
10
|
+
const WHOLE_NUMBER_LIMIT = 2 ** 63;
|
|
11
|
+
const TEXT_KINDS = 'text';
|
|
12
|
+
const NUMBER_KINDS = 'a number';
|
|
13
|
+
const WHOLE_KINDS = 'a whole number';
|
|
14
|
+
const GREEK_UPPER_CASE_STARTS = [0x1f80, 0x1f90, 0x1fa0];
|
|
15
|
+
const UPPER_CASE_EXCEPTIONS = new Map([
|
|
16
|
+
...GREEK_UPPER_CASE_STARTS.flatMap((start) => Array.from(
|
|
17
|
+
{ length: 8 },
|
|
18
|
+
(_, step) => [start + step, start + step + 8],
|
|
19
|
+
)),
|
|
20
|
+
[0x1fb3, 0x1fbc],
|
|
21
|
+
[0x1fc3, 0x1fcc],
|
|
22
|
+
[0x1ff3, 0x1ffc],
|
|
23
|
+
]);
|
|
24
|
+
const LOWER_CASE_EXCEPTIONS = new Map([[0x130, 0x69]]);
|
|
25
|
+
const QUOTED_ESCAPES = new Map([
|
|
26
|
+
['"', '\\"'],
|
|
27
|
+
['\\', '\\\\'],
|
|
28
|
+
['\u0007', '\\a'],
|
|
29
|
+
['\b', '\\b'],
|
|
30
|
+
['\f', '\\f'],
|
|
31
|
+
['\n', '\\n'],
|
|
32
|
+
['\r', '\\r'],
|
|
33
|
+
['\t', '\\t'],
|
|
34
|
+
['\v', '\\v'],
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
const TEXT_VERB = {
|
|
38
|
+
acceptedKinds: TEXT_KINDS,
|
|
39
|
+
takesOperand: true,
|
|
40
|
+
kinds: ['text'],
|
|
41
|
+
readsWidth: true,
|
|
42
|
+
readsPrecision: true,
|
|
43
|
+
};
|
|
44
|
+
const HEXADECIMAL_VERB = {
|
|
45
|
+
acceptedKinds: 'a whole number or text',
|
|
46
|
+
takesOperand: true,
|
|
47
|
+
kinds: ['text', 'whole'],
|
|
48
|
+
readsWidth: true,
|
|
49
|
+
readsZeroPadding: true,
|
|
50
|
+
};
|
|
51
|
+
const FORMAT_VERB_RULES = new Map([
|
|
52
|
+
['%', { kinds: [] }],
|
|
53
|
+
['s', TEXT_VERB],
|
|
54
|
+
['q', TEXT_VERB],
|
|
55
|
+
['u', TEXT_VERB],
|
|
56
|
+
['l', TEXT_VERB],
|
|
57
|
+
['A', TEXT_VERB],
|
|
58
|
+
['B', TEXT_VERB],
|
|
59
|
+
['v', {
|
|
60
|
+
acceptedKinds: 'text, a whole number or a boolean',
|
|
61
|
+
takesOperand: true,
|
|
62
|
+
kinds: ['text', 'whole', 'boolean'],
|
|
63
|
+
readsWidth: true,
|
|
64
|
+
}],
|
|
65
|
+
['d', {
|
|
66
|
+
acceptedKinds: WHOLE_KINDS,
|
|
67
|
+
takesOperand: true,
|
|
68
|
+
kinds: ['whole'],
|
|
69
|
+
readsWidth: true,
|
|
70
|
+
readsZeroPadding: true,
|
|
71
|
+
readsPlusSign: true,
|
|
72
|
+
}],
|
|
73
|
+
['x', HEXADECIMAL_VERB],
|
|
74
|
+
['X', HEXADECIMAL_VERB],
|
|
75
|
+
['f', {
|
|
76
|
+
acceptedKinds: NUMBER_KINDS,
|
|
77
|
+
takesOperand: true,
|
|
78
|
+
kinds: ['whole', 'number'],
|
|
79
|
+
readsWidth: true,
|
|
80
|
+
readsPrecision: true,
|
|
81
|
+
readsZeroPadding: true,
|
|
82
|
+
readsPlusSign: true,
|
|
83
|
+
}],
|
|
84
|
+
['C', {
|
|
85
|
+
acceptedKinds: NUMBER_KINDS,
|
|
86
|
+
takesOperand: true,
|
|
87
|
+
kinds: ['whole', 'number'],
|
|
88
|
+
readsWidth: true,
|
|
89
|
+
readsPrecision: true,
|
|
90
|
+
readsDateFormat: true,
|
|
91
|
+
}],
|
|
92
|
+
]);
|
|
93
|
+
const DATE_VERB_LETTERS = 'YymdHMSLz';
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The standard's format function: the layout with each verb written from the
|
|
97
|
+
* next operand; throws the problem that stops it.
|
|
98
|
+
*/
|
|
99
|
+
function formatLayout(layout, operands) {
|
|
100
|
+
let writtenText = '';
|
|
101
|
+
let nextOperand = 0;
|
|
102
|
+
for (const layoutPart of parseLayout(layout)) {
|
|
103
|
+
if (layoutPart.verb === undefined) {
|
|
104
|
+
writtenText += layoutPart.text;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (nextOperand >= operands.length) {
|
|
108
|
+
throw new Error(`layout ${codeSpan(layout)} has more verbs than operands`);
|
|
109
|
+
}
|
|
110
|
+
const verbRule = FORMAT_VERB_RULES.get(layoutPart.verb.letter);
|
|
111
|
+
const operand = formatOperandOf(operands[nextOperand]);
|
|
112
|
+
nextOperand += 1;
|
|
113
|
+
const verbText = formattedVerbText(layoutPart.verb, verbRule, operand, nextOperand);
|
|
114
|
+
writtenText += paddedVerbText(layoutPart.verb, verbRule, verbText);
|
|
115
|
+
}
|
|
116
|
+
if (nextOperand < operands.length) {
|
|
117
|
+
throw new Error(`layout ${codeSpan(layout)} has more operands than verbs`);
|
|
118
|
+
}
|
|
119
|
+
return writtenText;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The layout read into its parts, `{ text }` for literal text, `%%` read as
|
|
124
|
+
* text, and `{ verb }` for a verb: its `letter`, `leftAligned`, `plusSigned`,
|
|
125
|
+
* `zeroPadded`, its `width` and `precision`, and its `dateFormat`, `null` where
|
|
126
|
+
* left out. A date format is its `parts`, `{ text }` with `%%` read as text and
|
|
127
|
+
* `{ dateVerb }` with its `leftAligned`, `zeroPadded` and `width`, and its
|
|
128
|
+
* `offset` as written; throws the first problem in the layout.
|
|
129
|
+
*/
|
|
130
|
+
function parseLayout(layout) {
|
|
131
|
+
const layoutCharacters = Array.from(layout);
|
|
132
|
+
const layoutParts = [];
|
|
133
|
+
let literalText = '';
|
|
134
|
+
for (let position = 0; position < layoutCharacters.length; position += 1) {
|
|
135
|
+
if (layoutCharacters[position] !== '%') {
|
|
136
|
+
literalText += layoutCharacters[position];
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const directive = readFormatDirective(layoutCharacters, position);
|
|
140
|
+
if (directive.dateFormatProblem !== null) throw new Error(directive.dateFormatProblem);
|
|
141
|
+
if (!directive.isComplete) throw new Error(`layout ${codeSpan(layout)} ends inside a verb`);
|
|
142
|
+
position = directive.endPosition;
|
|
143
|
+
const verbRule = FORMAT_VERB_RULES.get(directive.verb.letter);
|
|
144
|
+
if (verbRule === undefined) {
|
|
145
|
+
throw new Error(`${codeSpan(directive.writtenText)} is not a verb \`format\` writes`);
|
|
146
|
+
}
|
|
147
|
+
const partProblem = directivePartProblem(directive, verbRule);
|
|
148
|
+
if (partProblem !== null) throw new Error(partProblem);
|
|
149
|
+
if (!verbRule.takesOperand) {
|
|
150
|
+
literalText += '%';
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (literalText !== '') layoutParts.push({ text: literalText });
|
|
154
|
+
literalText = '';
|
|
155
|
+
layoutParts.push({ verb: directive.verb });
|
|
156
|
+
}
|
|
157
|
+
if (literalText !== '') layoutParts.push({ text: literalText });
|
|
158
|
+
return layoutParts;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function emptyFormatDirective() {
|
|
162
|
+
return {
|
|
163
|
+
verb: {
|
|
164
|
+
letter: null,
|
|
165
|
+
leftAligned: false,
|
|
166
|
+
plusSigned: false,
|
|
167
|
+
zeroPadded: false,
|
|
168
|
+
width: null,
|
|
169
|
+
precision: null,
|
|
170
|
+
dateFormat: null,
|
|
171
|
+
},
|
|
172
|
+
overPartLimit: false,
|
|
173
|
+
dateFormatProblem: null,
|
|
174
|
+
isComplete: false,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function readFormatDirective(layoutCharacters, startPosition) {
|
|
179
|
+
const directive = emptyFormatDirective();
|
|
180
|
+
let position = readFlagsAndWidth(layoutCharacters, startPosition + 1, directive);
|
|
181
|
+
if (layoutCharacters[position] === '{') {
|
|
182
|
+
const dateFormatEnd = readDateFormat(layoutCharacters, position + 1, directive);
|
|
183
|
+
if (!dateFormatEnd.isClosed) return directive;
|
|
184
|
+
position = dateFormatEnd.endPosition;
|
|
185
|
+
}
|
|
186
|
+
position = readPrecision(layoutCharacters, position, directive);
|
|
187
|
+
if (position >= layoutCharacters.length) return directive;
|
|
188
|
+
directive.verb.letter = layoutCharacters[position];
|
|
189
|
+
directive.writtenText = layoutCharacters.slice(startPosition, position + 1).join('');
|
|
190
|
+
directive.endPosition = position;
|
|
191
|
+
directive.isComplete = true;
|
|
192
|
+
return directive;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A verb's or a date verb's flags and width read onto the directive; answers where they end. */
|
|
196
|
+
function readFlagsAndWidth(layoutCharacters, startPosition, directive) {
|
|
197
|
+
const { verb } = directive;
|
|
198
|
+
let position = startPosition;
|
|
199
|
+
while (position < layoutCharacters.length && '-+0'.includes(layoutCharacters[position])) {
|
|
200
|
+
if (layoutCharacters[position] === '-') verb.leftAligned = true;
|
|
201
|
+
else if (layoutCharacters[position] === '+') verb.plusSigned = true;
|
|
202
|
+
else verb.zeroPadded = true;
|
|
203
|
+
position += 1;
|
|
204
|
+
}
|
|
205
|
+
const width = readFormatNumber(layoutCharacters, position, directive);
|
|
206
|
+
verb.width = width.value;
|
|
207
|
+
return width.endPosition;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A precision read onto the directive where one is written, `.` alone being 0; answers where it ends. */
|
|
211
|
+
function readPrecision(layoutCharacters, position, directive) {
|
|
212
|
+
if (layoutCharacters[position] !== '.') return position;
|
|
213
|
+
const precision = readFormatNumber(layoutCharacters, position + 1, directive);
|
|
214
|
+
directive.verb.precision = precision.value === null ? 0 : precision.value;
|
|
215
|
+
return precision.endPosition;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The date format from after its opening brace to its closing one, set on the directive where closed;
|
|
220
|
+
* answers where it ends and whether it is closed. Its first problem is kept on the directive.
|
|
221
|
+
*/
|
|
222
|
+
function readDateFormat(layoutCharacters, startPosition, directive) {
|
|
223
|
+
const dateFormat = { parts: [], offset: null };
|
|
224
|
+
const keepProblem = (problem) => {
|
|
225
|
+
if (directive.dateFormatProblem === null) directive.dateFormatProblem = problem;
|
|
226
|
+
};
|
|
227
|
+
let literalText = '';
|
|
228
|
+
let position = startPosition;
|
|
229
|
+
const endsDateParts = (character) => character === '}' || character === '|';
|
|
230
|
+
while (position < layoutCharacters.length && !endsDateParts(layoutCharacters[position])) {
|
|
231
|
+
if (layoutCharacters[position] !== '%') {
|
|
232
|
+
literalText += layoutCharacters[position];
|
|
233
|
+
position += 1;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (layoutCharacters[position + 1] === '%') {
|
|
237
|
+
literalText += '%';
|
|
238
|
+
position += 2;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const dateVerbRead = readDateVerb(layoutCharacters, position, keepProblem);
|
|
242
|
+
if (!dateVerbRead.isComplete) return { isClosed: false };
|
|
243
|
+
position = dateVerbRead.endPosition;
|
|
244
|
+
if (literalText !== '') dateFormat.parts.push({ text: literalText });
|
|
245
|
+
literalText = '';
|
|
246
|
+
dateFormat.parts.push(dateVerbRead.dateFormatPart);
|
|
247
|
+
}
|
|
248
|
+
if (literalText !== '') dateFormat.parts.push({ text: literalText });
|
|
249
|
+
if (layoutCharacters[position] === '|') {
|
|
250
|
+
const offsetStart = position + 1;
|
|
251
|
+
while (position < layoutCharacters.length && layoutCharacters[position] !== '}') position += 1;
|
|
252
|
+
const offsetText = layoutCharacters.slice(offsetStart, position).join('');
|
|
253
|
+
if (offsetText === '') {
|
|
254
|
+
keepProblem('a date format\'s `|` takes an offset, such as `+08:00`');
|
|
255
|
+
} else if (!offsetMinutesOf(offsetText).isOffset) {
|
|
256
|
+
keepProblem(`${codeSpan(offsetText)} is not an offset, such as \`Z\` or \`+08:00\``);
|
|
257
|
+
}
|
|
258
|
+
dateFormat.offset = offsetText;
|
|
259
|
+
}
|
|
260
|
+
if (position >= layoutCharacters.length) return { isClosed: false };
|
|
261
|
+
directive.verb.dateFormat = dateFormat;
|
|
262
|
+
return { isClosed: true, endPosition: position + 1 };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* A date verb from its `%` through its letter: its date format part, where it ends and whether the layout
|
|
267
|
+
* holds its letter; its first problem is kept.
|
|
268
|
+
*/
|
|
269
|
+
function readDateVerb(layoutCharacters, startPosition, keepProblem) {
|
|
270
|
+
const directive = emptyFormatDirective();
|
|
271
|
+
let position = readFlagsAndWidth(layoutCharacters, startPosition + 1, directive);
|
|
272
|
+
position = readPrecision(layoutCharacters, position, directive);
|
|
273
|
+
if (position >= layoutCharacters.length) return { isComplete: false };
|
|
274
|
+
const { verb } = directive;
|
|
275
|
+
const dateLetter = layoutCharacters[position];
|
|
276
|
+
const fencedDateVerb = codeSpan(layoutCharacters.slice(startPosition, position + 1).join(''));
|
|
277
|
+
if (!DATE_VERB_LETTERS.includes(dateLetter)) {
|
|
278
|
+
keepProblem(`${fencedDateVerb} is not a date verb \`format\` writes`);
|
|
279
|
+
} else if (directive.overPartLimit) {
|
|
280
|
+
keepProblem(`${fencedDateVerb} has a width or a precision over ${FORMAT_PART_LIMIT}`);
|
|
281
|
+
} else if (verb.plusSigned) {
|
|
282
|
+
keepProblem(`${fencedDateVerb} takes no \`+\` flag`);
|
|
283
|
+
} else if (verb.zeroPadded && dateLetter === 'z') {
|
|
284
|
+
keepProblem(`${fencedDateVerb} takes no \`0\` flag`);
|
|
285
|
+
} else if (verb.precision !== null) {
|
|
286
|
+
keepProblem(`${fencedDateVerb} takes no precision`);
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
isComplete: true,
|
|
290
|
+
endPosition: position + 1,
|
|
291
|
+
dateFormatPart: {
|
|
292
|
+
dateVerb: dateLetter,
|
|
293
|
+
leftAligned: verb.leftAligned,
|
|
294
|
+
zeroPadded: verb.zeroPadded,
|
|
295
|
+
width: verb.width,
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** A time offset read: `Z`, or a sign, hours `00` to `23`, `:` and minutes `00` to `59`. */
|
|
301
|
+
function offsetMinutesOf(offsetText) {
|
|
302
|
+
if (offsetText === 'Z') return { offsetMinutes: 0, isOffset: true };
|
|
303
|
+
const written = /^([+-])([0-9]{2}):([0-9]{2})$/u.exec(offsetText);
|
|
304
|
+
if (written === null) return { offsetMinutes: 0, isOffset: false };
|
|
305
|
+
const hours = Number(written[2]);
|
|
306
|
+
const minutes = Number(written[3]);
|
|
307
|
+
const offsetMinutes = (written[1] === '-' ? -1 : 1) * (hours * 60 + minutes);
|
|
308
|
+
return { offsetMinutes, isOffset: hours <= 23 && minutes <= 59 };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function readFormatNumber(layoutCharacters, startPosition, directive) {
|
|
312
|
+
let value = 0;
|
|
313
|
+
let position = startPosition;
|
|
314
|
+
while (position < layoutCharacters.length && /^[0-9]$/u.test(layoutCharacters[position])) {
|
|
315
|
+
if (value > FORMAT_PART_LIMIT) directive.overPartLimit = true;
|
|
316
|
+
else value = value * 10 + Number(layoutCharacters[position]);
|
|
317
|
+
position += 1;
|
|
318
|
+
}
|
|
319
|
+
if (value > FORMAT_PART_LIMIT) directive.overPartLimit = true;
|
|
320
|
+
return { value: position > startPosition ? value : null, endPosition: position };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function directivePartProblem({ verb, writtenText, overPartLimit }, verbRule) {
|
|
324
|
+
const fenced = codeSpan(writtenText);
|
|
325
|
+
if (overPartLimit) return `${fenced} has a width or a precision over ${FORMAT_PART_LIMIT}`;
|
|
326
|
+
if (verb.leftAligned && !verbRule.readsWidth) return `${fenced} takes no \`-\` flag`;
|
|
327
|
+
if (verb.plusSigned && !verbRule.readsPlusSign) return `${fenced} takes no \`+\` flag`;
|
|
328
|
+
if (verb.zeroPadded && !verbRule.readsZeroPadding) return `${fenced} takes no \`0\` flag`;
|
|
329
|
+
if (verb.width !== null && !verbRule.readsWidth) return `${fenced} takes no width`;
|
|
330
|
+
if (verb.precision !== null && !verbRule.readsPrecision) return `${fenced} takes no precision`;
|
|
331
|
+
if (verb.dateFormat !== null && !verbRule.readsDateFormat) return `${fenced} takes no date format`;
|
|
332
|
+
if (verb.letter === 'B' && (verb.precision === null || verb.precision < 1)) {
|
|
333
|
+
return `${fenced} takes a precision of at least 1, such as \`%.64B\``;
|
|
334
|
+
}
|
|
335
|
+
if (verb.letter === 'C' && verb.precision !== null && verb.precision > MAXIMUM_TIME_DIGITS) {
|
|
336
|
+
return `${fenced} takes a precision of at most ${MAXIMUM_TIME_DIGITS}, such as \`.3\` for milliseconds`;
|
|
337
|
+
}
|
|
338
|
+
if (verbRule.readsDateFormat && verb.dateFormat === null) {
|
|
339
|
+
return `${fenced} takes a date format, such as \`%{%Y-%m-%d}C\``;
|
|
340
|
+
}
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function formatOperandOf(operandValue) {
|
|
345
|
+
if (typeof operandValue === 'string') {
|
|
346
|
+
return { kind: 'text', kindName: 'text', textValue: operandValue };
|
|
347
|
+
}
|
|
348
|
+
if (typeof operandValue === 'boolean') {
|
|
349
|
+
return { kind: 'boolean', kindName: 'a boolean', booleanValue: operandValue };
|
|
350
|
+
}
|
|
351
|
+
if (operandValue === null) return { kind: 'other', kindName: 'null' };
|
|
352
|
+
if (Array.isArray(operandValue)) return { kind: 'other', kindName: 'a list' };
|
|
353
|
+
if (typeof operandValue === 'object') return { kind: 'other', kindName: 'a map' };
|
|
354
|
+
if (typeof operandValue !== 'number') {
|
|
355
|
+
return { kind: 'other', kindName: `a JavaScript ${typeof operandValue}` };
|
|
356
|
+
}
|
|
357
|
+
if (!Number.isFinite(operandValue)) {
|
|
358
|
+
return { kind: 'other', kindName: 'a number that is not finite' };
|
|
359
|
+
}
|
|
360
|
+
const isWhole = Number.isInteger(operandValue)
|
|
361
|
+
&& operandValue >= -WHOLE_NUMBER_LIMIT
|
|
362
|
+
&& operandValue < WHOLE_NUMBER_LIMIT;
|
|
363
|
+
if (isWhole) return { kind: 'whole', kindName: WHOLE_KINDS, wholeValue: BigInt(operandValue) };
|
|
364
|
+
return { kind: 'number', kindName: NUMBER_KINDS, numberValue: operandValue };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function formattedVerbText(verb, verbRule, operand, operandNumber) {
|
|
368
|
+
if (!verbRule.kinds.includes(operand.kind)) {
|
|
369
|
+
throw new Error(
|
|
370
|
+
`${codeSpan(`%${verb.letter}`)} writes ${verbRule.acceptedKinds}, `
|
|
371
|
+
+ `and operand ${operandNumber} is ${operand.kindName}`,
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
let readText = operand.textValue;
|
|
375
|
+
if (verb.precision !== null && operand.kind === 'text' && verb.letter !== 'B') {
|
|
376
|
+
readText = Array.from(readText).slice(0, verb.precision).join('');
|
|
377
|
+
}
|
|
378
|
+
const precision = verb.precision === null ? 6 : verb.precision;
|
|
379
|
+
switch (verb.letter) {
|
|
380
|
+
case 's': return readText;
|
|
381
|
+
case 'q': return goQuotedText(readText);
|
|
382
|
+
case 'u': return mappedCase(readText, UPPER_CASE_EXCEPTIONS, (text) => text.toUpperCase());
|
|
383
|
+
case 'l': return mappedCase(readText, LOWER_CASE_EXCEPTIONS, (text) => text.toLowerCase());
|
|
384
|
+
case 'A': return readText.replaceAll('/', '_');
|
|
385
|
+
case 'B': return tailBoundedText(readText, verb.precision);
|
|
386
|
+
case 'v': return valueVerbText(operand);
|
|
387
|
+
case 'd': return signedNumberText(operand.wholeValue.toString(), verb.plusSigned);
|
|
388
|
+
case 'x': return hexadecimalText(operand);
|
|
389
|
+
case 'X': return hexadecimalText(operand).toUpperCase();
|
|
390
|
+
case 'f': return signedNumberText(fixedPointText(operand, precision), verb.plusSigned);
|
|
391
|
+
default: return dateText(
|
|
392
|
+
operand,
|
|
393
|
+
verb.precision === null ? 0 : verb.precision,
|
|
394
|
+
verb.dateFormat,
|
|
395
|
+
operandNumber,
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function valueVerbText(operand) {
|
|
401
|
+
if (operand.kind === 'text') return operand.textValue;
|
|
402
|
+
return String(operand.kind === 'whole' ? operand.wholeValue : operand.booleanValue);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function mappedCase(text, exceptions, fullMapping) {
|
|
406
|
+
return Array.from(text, (character) => {
|
|
407
|
+
const codePoint = character.codePointAt(0);
|
|
408
|
+
if (exceptions.has(codePoint)) return String.fromCodePoint(exceptions.get(codePoint));
|
|
409
|
+
const mapped = fullMapping(character);
|
|
410
|
+
return Array.from(mapped).length === 1 ? mapped : character;
|
|
411
|
+
}).join('');
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function tailBoundedText(text, precision) {
|
|
415
|
+
const characters = Array.from(text);
|
|
416
|
+
if (characters.length <= precision) return text;
|
|
417
|
+
return `-${characters.slice(characters.length - (precision - 1)).join('')}`;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function signedNumberText(numberText, plusSigned) {
|
|
421
|
+
return plusSigned && !numberText.startsWith('-') ? `+${numberText}` : numberText;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function hexadecimalText(operand) {
|
|
425
|
+
if (operand.kind === 'text') return Buffer.from(operand.textValue, 'utf8').toString('hex');
|
|
426
|
+
if (operand.wholeValue < 0n) return `-${(-operand.wholeValue).toString(16)}`;
|
|
427
|
+
return operand.wholeValue.toString(16);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function fixedPointText(operand, precision) {
|
|
431
|
+
if (operand.kind === 'whole') {
|
|
432
|
+
if (precision === 0) return operand.wholeValue.toString();
|
|
433
|
+
return `${operand.wholeValue}.${'0'.repeat(precision)}`;
|
|
434
|
+
}
|
|
435
|
+
const { mantissa, binaryExponent } = exactBinaryParts(Math.abs(operand.numberValue));
|
|
436
|
+
const scale = 10n ** BigInt(precision);
|
|
437
|
+
let scaled;
|
|
438
|
+
if (binaryExponent >= 0) {
|
|
439
|
+
scaled = mantissa * scale * 2n ** BigInt(binaryExponent);
|
|
440
|
+
} else {
|
|
441
|
+
const numerator = mantissa * scale;
|
|
442
|
+
const denominator = 2n ** BigInt(-binaryExponent);
|
|
443
|
+
scaled = numerator / denominator;
|
|
444
|
+
const twiceRemainder = 2n * (numerator % denominator);
|
|
445
|
+
const roundsUp = twiceRemainder > denominator
|
|
446
|
+
|| (twiceRemainder === denominator && scaled % 2n === 1n);
|
|
447
|
+
if (roundsUp) scaled += 1n;
|
|
448
|
+
}
|
|
449
|
+
const digits = scaled.toString().padStart(precision + 1, '0');
|
|
450
|
+
const signText = operand.numberValue < 0 ? '-' : '';
|
|
451
|
+
if (precision === 0) return `${signText}${digits}`;
|
|
452
|
+
return `${signText}${digits.slice(0, -precision)}.${digits.slice(-precision)}`;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function exactBinaryParts(positiveNumber) {
|
|
456
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
457
|
+
view.setFloat64(0, positiveNumber);
|
|
458
|
+
const storedExponent = (view.getUint32(0) >>> 20) & 0x7ff;
|
|
459
|
+
const fraction = (BigInt(view.getUint32(0) & 0xfffff) << 32n) | BigInt(view.getUint32(4));
|
|
460
|
+
if (storedExponent === 0) return { mantissa: fraction, binaryExponent: -1074 };
|
|
461
|
+
return { mantissa: fraction | (1n << 52n), binaryExponent: storedExponent - 1075 };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function dateText(operand, timeDigits, dateFormat, operandNumber) {
|
|
465
|
+
const unitsPerSecond = 10n ** BigInt(timeDigits);
|
|
466
|
+
const isNearRange = (seconds) => seconds >= EARLIEST_FORMAT_SECONDS - SECONDS_PER_DAY
|
|
467
|
+
&& seconds < LATEST_FORMAT_SECONDS + SECONDS_PER_DAY;
|
|
468
|
+
let seconds;
|
|
469
|
+
let milliseconds;
|
|
470
|
+
if (operand.kind === 'whole') {
|
|
471
|
+
let wholeSeconds = operand.wholeValue / unitsPerSecond;
|
|
472
|
+
let remainder = operand.wholeValue % unitsPerSecond;
|
|
473
|
+
if (remainder < 0n) {
|
|
474
|
+
wholeSeconds -= 1n;
|
|
475
|
+
remainder += unitsPerSecond;
|
|
476
|
+
}
|
|
477
|
+
seconds = Number(wholeSeconds);
|
|
478
|
+
milliseconds = Number((remainder * 1000n) / unitsPerSecond);
|
|
479
|
+
} else {
|
|
480
|
+
const timeInSeconds = operand.numberValue / Number(unitsPerSecond);
|
|
481
|
+
seconds = Math.floor(timeInSeconds);
|
|
482
|
+
milliseconds = Math.floor((timeInSeconds - seconds) * 1000);
|
|
483
|
+
}
|
|
484
|
+
if (!isNearRange(seconds)) throw dateRangeProblem(operandNumber);
|
|
485
|
+
const { offset } = dateFormat;
|
|
486
|
+
const writtenOffset = offset === null || offset === '+00:00' ? 'Z' : offset;
|
|
487
|
+
seconds += offsetMinutesOf(writtenOffset).offsetMinutes * 60;
|
|
488
|
+
if (seconds < EARLIEST_FORMAT_SECONDS || seconds >= LATEST_FORMAT_SECONDS) {
|
|
489
|
+
throw dateRangeProblem(operandNumber);
|
|
490
|
+
}
|
|
491
|
+
const days = Math.floor(seconds / SECONDS_PER_DAY);
|
|
492
|
+
const secondOfDay = seconds - days * SECONDS_PER_DAY;
|
|
493
|
+
const { year, month, day } = civilDateOfDays(days);
|
|
494
|
+
const dateVerbValues = {
|
|
495
|
+
Y: year,
|
|
496
|
+
y: year % 100,
|
|
497
|
+
m: month,
|
|
498
|
+
d: day,
|
|
499
|
+
H: Math.floor(secondOfDay / 3600),
|
|
500
|
+
M: Math.floor((secondOfDay % 3600) / 60),
|
|
501
|
+
S: secondOfDay % 60,
|
|
502
|
+
L: milliseconds,
|
|
503
|
+
};
|
|
504
|
+
return dateFormat.parts.map((part) => {
|
|
505
|
+
if (part.dateVerb === undefined) return part.text;
|
|
506
|
+
if (part.dateVerb === 'z') return paddedText(writtenOffset, part.width, part.leftAligned, false);
|
|
507
|
+
return paddedText(String(dateVerbValues[part.dateVerb]), part.width, part.leftAligned, part.zeroPadded);
|
|
508
|
+
}).join('');
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function dateRangeProblem(operandNumber) {
|
|
512
|
+
return new Error(
|
|
513
|
+
`\`%C\` writes a time in the years 0000 to 9999, and operand ${operandNumber} is outside them`,
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function civilDateOfDays(days) {
|
|
518
|
+
const shiftedDays = days + 719468;
|
|
519
|
+
const era = Math.floor(shiftedDays / 146097);
|
|
520
|
+
const dayOfEra = shiftedDays - era * 146097;
|
|
521
|
+
const yearOfEra = Math.floor((
|
|
522
|
+
dayOfEra
|
|
523
|
+
- Math.floor(dayOfEra / 1460)
|
|
524
|
+
+ Math.floor(dayOfEra / 36524)
|
|
525
|
+
- Math.floor(dayOfEra / 146096)
|
|
526
|
+
) / 365);
|
|
527
|
+
const dayOfYear = dayOfEra
|
|
528
|
+
- (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
|
|
529
|
+
const shiftedMonth = Math.floor((5 * dayOfYear + 2) / 153);
|
|
530
|
+
const day = dayOfYear - Math.floor((153 * shiftedMonth + 2) / 5) + 1;
|
|
531
|
+
const month = shiftedMonth < 10 ? shiftedMonth + 3 : shiftedMonth - 9;
|
|
532
|
+
return { year: yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function goQuotedText(text) {
|
|
536
|
+
const escaped = Array.from(text, (character) => {
|
|
537
|
+
if (QUOTED_ESCAPES.has(character)) return QUOTED_ESCAPES.get(character);
|
|
538
|
+
const codePoint = character.codePointAt(0);
|
|
539
|
+
if (codePoint < 0x20 || codePoint === 0x7f) {
|
|
540
|
+
return `\\x${codePoint.toString(16).padStart(2, '0')}`;
|
|
541
|
+
}
|
|
542
|
+
if (codePoint >= 0x80 && codePoint <= 0x9f) {
|
|
543
|
+
return `\\u${codePoint.toString(16).padStart(4, '0')}`;
|
|
544
|
+
}
|
|
545
|
+
return character;
|
|
546
|
+
});
|
|
547
|
+
return `"${escaped.join('')}"`;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function paddedVerbText(verb, verbRule, verbText) {
|
|
551
|
+
const zeroPadded = verb.zeroPadded && verbRule.readsZeroPadding === true;
|
|
552
|
+
return paddedText(verbText, verb.width, verb.leftAligned, zeroPadded);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Text padded to a width: on the right where left-aligned, else with leading zeros after its sign where
|
|
557
|
+
* zero-padded, else with spaces on the left.
|
|
558
|
+
*/
|
|
559
|
+
function paddedText(text, width, leftAligned, zeroPadded) {
|
|
560
|
+
if (width === null) return text;
|
|
561
|
+
const padding = width - Array.from(text).length;
|
|
562
|
+
if (padding <= 0) return text;
|
|
563
|
+
if (leftAligned) return text + ' '.repeat(padding);
|
|
564
|
+
if (zeroPadded) {
|
|
565
|
+
const signText = text.startsWith('-') || text.startsWith('+') ? text[0] : '';
|
|
566
|
+
return signText + '0'.repeat(padding) + text.slice(signText.length);
|
|
567
|
+
}
|
|
568
|
+
return ' '.repeat(padding) + text;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
module.exports = { formatLayout, parseLayout };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "yaml-dsl-spec",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"description": "The YAML DSL standard: the JSON Schemas of yaml-dsl.yml and of a DSL's function table, and a reader returning a yaml-dsl.yml's DSL definitions validated.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|