yaml-dsl-spec 0.3.1 → 0.3.2

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 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,386 @@
1
+ 'use strict';
2
+
3
+ const { codeSpan } = require('./problem-wording');
4
+
5
+ const FORMAT_PART_LIMIT = 1000;
6
+ const EARLIEST_FORMAT_SECONDS = -62135596800;
7
+ const LATEST_FORMAT_SECONDS = 253402300800;
8
+ const SECONDS_PER_DAY = 86400;
9
+ const WHOLE_NUMBER_LIMIT = 2 ** 63;
10
+ const TEXT_KINDS = 'text';
11
+ const NUMBER_KINDS = 'a number';
12
+ const WHOLE_KINDS = 'a whole number';
13
+ const GREEK_UPPER_CASE_STARTS = [0x1f80, 0x1f90, 0x1fa0];
14
+ const UPPER_CASE_EXCEPTIONS = new Map([
15
+ ...GREEK_UPPER_CASE_STARTS.flatMap((start) => Array.from(
16
+ { length: 8 },
17
+ (_, step) => [start + step, start + step + 8],
18
+ )),
19
+ [0x1fb3, 0x1fbc],
20
+ [0x1fc3, 0x1fcc],
21
+ [0x1ff3, 0x1ffc],
22
+ ]);
23
+ const LOWER_CASE_EXCEPTIONS = new Map([[0x130, 0x69]]);
24
+ const QUOTED_ESCAPES = new Map([
25
+ ['"', '\\"'],
26
+ ['\\', '\\\\'],
27
+ ['\u0007', '\\a'],
28
+ ['\b', '\\b'],
29
+ ['\f', '\\f'],
30
+ ['\n', '\\n'],
31
+ ['\r', '\\r'],
32
+ ['\t', '\\t'],
33
+ ['\v', '\\v'],
34
+ ]);
35
+
36
+ const TEXT_VERB = {
37
+ acceptedKinds: TEXT_KINDS,
38
+ takesOperand: true,
39
+ kinds: ['text'],
40
+ readsWidth: true,
41
+ readsPrecision: true,
42
+ };
43
+ const HEXADECIMAL_VERB = {
44
+ acceptedKinds: 'a whole number or text',
45
+ takesOperand: true,
46
+ kinds: ['text', 'whole'],
47
+ readsWidth: true,
48
+ readsZeroPadding: true,
49
+ };
50
+ const FORMAT_VERB_RULES = new Map([
51
+ ['%', { kinds: [] }],
52
+ ['s', TEXT_VERB],
53
+ ['q', TEXT_VERB],
54
+ ['u', TEXT_VERB],
55
+ ['l', TEXT_VERB],
56
+ ['A', TEXT_VERB],
57
+ ['B', TEXT_VERB],
58
+ ['v', {
59
+ acceptedKinds: 'text, a whole number or a boolean',
60
+ takesOperand: true,
61
+ kinds: ['text', 'whole', 'boolean'],
62
+ readsWidth: true,
63
+ }],
64
+ ['d', {
65
+ acceptedKinds: WHOLE_KINDS,
66
+ takesOperand: true,
67
+ kinds: ['whole'],
68
+ readsWidth: true,
69
+ readsZeroPadding: true,
70
+ readsPlusSign: true,
71
+ }],
72
+ ['x', HEXADECIMAL_VERB],
73
+ ['X', HEXADECIMAL_VERB],
74
+ ['f', {
75
+ acceptedKinds: NUMBER_KINDS,
76
+ takesOperand: true,
77
+ kinds: ['whole', 'number'],
78
+ readsWidth: true,
79
+ readsPrecision: true,
80
+ readsZeroPadding: true,
81
+ readsPlusSign: true,
82
+ }],
83
+ ['C', {
84
+ acceptedKinds: NUMBER_KINDS,
85
+ takesOperand: true,
86
+ kinds: ['whole', 'number'],
87
+ readsWidth: true,
88
+ }],
89
+ ]);
90
+
91
+ /**
92
+ * The standard's format function: the layout with each verb written from the
93
+ * next operand; throws the problem that stops it.
94
+ */
95
+ function formatLayout(layout, operands) {
96
+ let writtenText = '';
97
+ let nextOperand = 0;
98
+ for (const layoutPart of parseLayout(layout)) {
99
+ if (layoutPart.verb === undefined) {
100
+ writtenText += layoutPart.text;
101
+ continue;
102
+ }
103
+ if (nextOperand >= operands.length) {
104
+ throw new Error(`layout ${codeSpan(layout)} has more verbs than operands`);
105
+ }
106
+ const verbRule = FORMAT_VERB_RULES.get(layoutPart.verb.letter);
107
+ const operand = formatOperandOf(operands[nextOperand]);
108
+ nextOperand += 1;
109
+ const verbText = formattedVerbText(layoutPart.verb, verbRule, operand, nextOperand);
110
+ writtenText += paddedVerbText(layoutPart.verb, verbRule, verbText);
111
+ }
112
+ if (nextOperand < operands.length) {
113
+ throw new Error(`layout ${codeSpan(layout)} has more operands than verbs`);
114
+ }
115
+ return writtenText;
116
+ }
117
+
118
+ /**
119
+ * The layout read into its parts, `{ text }` for literal text, `%%` read as
120
+ * text, and `{ verb }` for a verb: its `letter`, `leftAligned`, `plusSigned`,
121
+ * `zeroPadded`, and its `width` and `precision`, `null` where left out; throws
122
+ * the first problem in the layout.
123
+ */
124
+ function parseLayout(layout) {
125
+ const layoutCharacters = Array.from(layout);
126
+ const layoutParts = [];
127
+ let literalText = '';
128
+ for (let position = 0; position < layoutCharacters.length; position += 1) {
129
+ if (layoutCharacters[position] !== '%') {
130
+ literalText += layoutCharacters[position];
131
+ continue;
132
+ }
133
+ const directive = readFormatDirective(layoutCharacters, position);
134
+ if (directive === null) throw new Error(`layout ${codeSpan(layout)} ends inside a verb`);
135
+ position = directive.endPosition;
136
+ const verbRule = FORMAT_VERB_RULES.get(directive.verb.letter);
137
+ if (verbRule === undefined) {
138
+ throw new Error(`${codeSpan(directive.writtenText)} is not a verb \`format\` writes`);
139
+ }
140
+ const partProblem = directivePartProblem(directive, verbRule);
141
+ if (partProblem !== null) throw new Error(partProblem);
142
+ if (!verbRule.takesOperand) {
143
+ literalText += '%';
144
+ continue;
145
+ }
146
+ if (literalText !== '') layoutParts.push({ text: literalText });
147
+ literalText = '';
148
+ layoutParts.push({ verb: directive.verb });
149
+ }
150
+ if (literalText !== '') layoutParts.push({ text: literalText });
151
+ return layoutParts;
152
+ }
153
+
154
+ function readFormatDirective(layoutCharacters, startPosition) {
155
+ const verb = {
156
+ letter: null,
157
+ leftAligned: false,
158
+ plusSigned: false,
159
+ zeroPadded: false,
160
+ width: null,
161
+ precision: null,
162
+ };
163
+ const directive = { verb, overPartLimit: false };
164
+ let position = startPosition + 1;
165
+ while (position < layoutCharacters.length && '-+0'.includes(layoutCharacters[position])) {
166
+ if (layoutCharacters[position] === '-') verb.leftAligned = true;
167
+ else if (layoutCharacters[position] === '+') verb.plusSigned = true;
168
+ else verb.zeroPadded = true;
169
+ position += 1;
170
+ }
171
+ const width = readFormatNumber(layoutCharacters, position, directive);
172
+ verb.width = width.value;
173
+ position = width.endPosition;
174
+ if (layoutCharacters[position] === '.') {
175
+ const precision = readFormatNumber(layoutCharacters, position + 1, directive);
176
+ verb.precision = precision.value === null ? 0 : precision.value;
177
+ position = precision.endPosition;
178
+ }
179
+ if (position >= layoutCharacters.length) return null;
180
+ verb.letter = layoutCharacters[position];
181
+ directive.writtenText = layoutCharacters.slice(startPosition, position + 1).join('');
182
+ directive.endPosition = position;
183
+ return directive;
184
+ }
185
+
186
+ function readFormatNumber(layoutCharacters, startPosition, directive) {
187
+ let value = 0;
188
+ let position = startPosition;
189
+ while (position < layoutCharacters.length && /^[0-9]$/u.test(layoutCharacters[position])) {
190
+ if (value > FORMAT_PART_LIMIT) directive.overPartLimit = true;
191
+ else value = value * 10 + Number(layoutCharacters[position]);
192
+ position += 1;
193
+ }
194
+ if (value > FORMAT_PART_LIMIT) directive.overPartLimit = true;
195
+ return { value: position > startPosition ? value : null, endPosition: position };
196
+ }
197
+
198
+ function directivePartProblem({ verb, writtenText, overPartLimit }, verbRule) {
199
+ const fenced = codeSpan(writtenText);
200
+ if (overPartLimit) return `${fenced} has a width or a precision over ${FORMAT_PART_LIMIT}`;
201
+ if (verb.leftAligned && !verbRule.readsWidth) return `${fenced} takes no \`-\` flag`;
202
+ if (verb.plusSigned && !verbRule.readsPlusSign) return `${fenced} takes no \`+\` flag`;
203
+ if (verb.zeroPadded && !verbRule.readsZeroPadding) return `${fenced} takes no \`0\` flag`;
204
+ if (verb.width !== null && !verbRule.readsWidth) return `${fenced} takes no width`;
205
+ if (verb.precision !== null && !verbRule.readsPrecision) return `${fenced} takes no precision`;
206
+ if (verb.letter === 'B' && (verb.precision === null || verb.precision < 1)) {
207
+ return `${fenced} takes a precision of at least 1, such as \`%.64B\``;
208
+ }
209
+ return null;
210
+ }
211
+
212
+ function formatOperandOf(operandValue) {
213
+ if (typeof operandValue === 'string') {
214
+ return { kind: 'text', kindName: 'text', textValue: operandValue };
215
+ }
216
+ if (typeof operandValue === 'boolean') {
217
+ return { kind: 'boolean', kindName: 'a boolean', booleanValue: operandValue };
218
+ }
219
+ if (operandValue === null) return { kind: 'other', kindName: 'null' };
220
+ if (Array.isArray(operandValue)) return { kind: 'other', kindName: 'a list' };
221
+ if (typeof operandValue === 'object') return { kind: 'other', kindName: 'a map' };
222
+ if (typeof operandValue !== 'number') {
223
+ return { kind: 'other', kindName: `a JavaScript ${typeof operandValue}` };
224
+ }
225
+ if (!Number.isFinite(operandValue)) {
226
+ return { kind: 'other', kindName: 'a number that is not finite' };
227
+ }
228
+ const isWhole = Number.isInteger(operandValue)
229
+ && operandValue >= -WHOLE_NUMBER_LIMIT
230
+ && operandValue < WHOLE_NUMBER_LIMIT;
231
+ if (isWhole) return { kind: 'whole', kindName: WHOLE_KINDS, wholeValue: BigInt(operandValue) };
232
+ return { kind: 'number', kindName: NUMBER_KINDS, numberValue: operandValue };
233
+ }
234
+
235
+ function formattedVerbText(verb, verbRule, operand, operandNumber) {
236
+ if (!verbRule.kinds.includes(operand.kind)) {
237
+ throw new Error(
238
+ `${codeSpan(`%${verb.letter}`)} writes ${verbRule.acceptedKinds}, `
239
+ + `and operand ${operandNumber} is ${operand.kindName}`,
240
+ );
241
+ }
242
+ let readText = operand.textValue;
243
+ if (verb.precision !== null && operand.kind === 'text' && verb.letter !== 'B') {
244
+ readText = Array.from(readText).slice(0, verb.precision).join('');
245
+ }
246
+ const precision = verb.precision === null ? 6 : verb.precision;
247
+ switch (verb.letter) {
248
+ case 's': return readText;
249
+ case 'q': return goQuotedText(readText);
250
+ case 'u': return mappedCase(readText, UPPER_CASE_EXCEPTIONS, (text) => text.toUpperCase());
251
+ case 'l': return mappedCase(readText, LOWER_CASE_EXCEPTIONS, (text) => text.toLowerCase());
252
+ case 'A': return readText.replaceAll('/', '_');
253
+ case 'B': return tailBoundedText(readText, verb.precision);
254
+ case 'v': return valueVerbText(operand);
255
+ case 'd': return signedNumberText(operand.wholeValue.toString(), verb.plusSigned);
256
+ case 'x': return hexadecimalText(operand);
257
+ case 'X': return hexadecimalText(operand).toUpperCase();
258
+ case 'f': return signedNumberText(fixedPointText(operand, precision), verb.plusSigned);
259
+ default: return dateText(operand, operandNumber);
260
+ }
261
+ }
262
+
263
+ function valueVerbText(operand) {
264
+ if (operand.kind === 'text') return operand.textValue;
265
+ return String(operand.kind === 'whole' ? operand.wholeValue : operand.booleanValue);
266
+ }
267
+
268
+ function mappedCase(text, exceptions, fullMapping) {
269
+ return Array.from(text, (character) => {
270
+ const codePoint = character.codePointAt(0);
271
+ if (exceptions.has(codePoint)) return String.fromCodePoint(exceptions.get(codePoint));
272
+ const mapped = fullMapping(character);
273
+ return Array.from(mapped).length === 1 ? mapped : character;
274
+ }).join('');
275
+ }
276
+
277
+ function tailBoundedText(text, precision) {
278
+ const characters = Array.from(text);
279
+ if (characters.length <= precision) return text;
280
+ return `-${characters.slice(characters.length - (precision - 1)).join('')}`;
281
+ }
282
+
283
+ function signedNumberText(numberText, plusSigned) {
284
+ return plusSigned && !numberText.startsWith('-') ? `+${numberText}` : numberText;
285
+ }
286
+
287
+ function hexadecimalText(operand) {
288
+ if (operand.kind === 'text') return Buffer.from(operand.textValue, 'utf8').toString('hex');
289
+ if (operand.wholeValue < 0n) return `-${(-operand.wholeValue).toString(16)}`;
290
+ return operand.wholeValue.toString(16);
291
+ }
292
+
293
+ function fixedPointText(operand, precision) {
294
+ if (operand.kind === 'whole') {
295
+ if (precision === 0) return operand.wholeValue.toString();
296
+ return `${operand.wholeValue}.${'0'.repeat(precision)}`;
297
+ }
298
+ const { mantissa, binaryExponent } = exactBinaryParts(Math.abs(operand.numberValue));
299
+ const scale = 10n ** BigInt(precision);
300
+ let scaled;
301
+ if (binaryExponent >= 0) {
302
+ scaled = mantissa * scale * 2n ** BigInt(binaryExponent);
303
+ } else {
304
+ const numerator = mantissa * scale;
305
+ const denominator = 2n ** BigInt(-binaryExponent);
306
+ scaled = numerator / denominator;
307
+ const twiceRemainder = 2n * (numerator % denominator);
308
+ const roundsUp = twiceRemainder > denominator
309
+ || (twiceRemainder === denominator && scaled % 2n === 1n);
310
+ if (roundsUp) scaled += 1n;
311
+ }
312
+ const digits = scaled.toString().padStart(precision + 1, '0');
313
+ const signText = operand.numberValue < 0 ? '-' : '';
314
+ if (precision === 0) return `${signText}${digits}`;
315
+ return `${signText}${digits.slice(0, -precision)}.${digits.slice(-precision)}`;
316
+ }
317
+
318
+ function exactBinaryParts(positiveNumber) {
319
+ const view = new DataView(new ArrayBuffer(8));
320
+ view.setFloat64(0, positiveNumber);
321
+ const storedExponent = (view.getUint32(0) >>> 20) & 0x7ff;
322
+ const fraction = (BigInt(view.getUint32(0) & 0xfffff) << 32n) | BigInt(view.getUint32(4));
323
+ if (storedExponent === 0) return { mantissa: fraction, binaryExponent: -1074 };
324
+ return { mantissa: fraction | (1n << 52n), binaryExponent: storedExponent - 1075 };
325
+ }
326
+
327
+ function dateText(operand, operandNumber) {
328
+ const seconds = operand.kind === 'whole'
329
+ ? Number(operand.wholeValue)
330
+ : Math.floor(operand.numberValue);
331
+ if (seconds < EARLIEST_FORMAT_SECONDS || seconds >= LATEST_FORMAT_SECONDS) {
332
+ throw new Error(
333
+ `\`%C\` writes a time in the years 1 to 9999, and operand ${operandNumber} is outside them`,
334
+ );
335
+ }
336
+ const { year, month, day } = civilDateOfDays(Math.floor(seconds / SECONDS_PER_DAY));
337
+ const twoDigits = (value) => String(value).padStart(2, '0');
338
+ return `${String(year).padStart(4, '0')}-${twoDigits(month)}-${twoDigits(day)}`;
339
+ }
340
+
341
+ function civilDateOfDays(days) {
342
+ const shiftedDays = days + 719468;
343
+ const era = Math.floor(shiftedDays / 146097);
344
+ const dayOfEra = shiftedDays - era * 146097;
345
+ const yearOfEra = Math.floor((
346
+ dayOfEra
347
+ - Math.floor(dayOfEra / 1460)
348
+ + Math.floor(dayOfEra / 36524)
349
+ - Math.floor(dayOfEra / 146096)
350
+ ) / 365);
351
+ const dayOfYear = dayOfEra
352
+ - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
353
+ const shiftedMonth = Math.floor((5 * dayOfYear + 2) / 153);
354
+ const day = dayOfYear - Math.floor((153 * shiftedMonth + 2) / 5) + 1;
355
+ const month = shiftedMonth < 10 ? shiftedMonth + 3 : shiftedMonth - 9;
356
+ return { year: yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day };
357
+ }
358
+
359
+ function goQuotedText(text) {
360
+ const escaped = Array.from(text, (character) => {
361
+ if (QUOTED_ESCAPES.has(character)) return QUOTED_ESCAPES.get(character);
362
+ const codePoint = character.codePointAt(0);
363
+ if (codePoint < 0x20 || codePoint === 0x7f) {
364
+ return `\\x${codePoint.toString(16).padStart(2, '0')}`;
365
+ }
366
+ if (codePoint >= 0x80 && codePoint <= 0x9f) {
367
+ return `\\u${codePoint.toString(16).padStart(4, '0')}`;
368
+ }
369
+ return character;
370
+ });
371
+ return `"${escaped.join('')}"`;
372
+ }
373
+
374
+ function paddedVerbText(verb, verbRule, verbText) {
375
+ if (verb.width === null) return verbText;
376
+ const padding = verb.width - Array.from(verbText).length;
377
+ if (padding <= 0) return verbText;
378
+ if (verb.leftAligned) return verbText + ' '.repeat(padding);
379
+ if (verb.zeroPadded && verbRule.readsZeroPadding) {
380
+ const signText = verbText.startsWith('-') || verbText.startsWith('+') ? verbText[0] : '';
381
+ return signText + '0'.repeat(padding) + verbText.slice(signText.length);
382
+ }
383
+ return ' '.repeat(padding) + verbText;
384
+ }
385
+
386
+ module.exports = { formatLayout, parseLayout };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yaml-dsl-spec",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
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": {