yaml-dsl-spec 0.3.2 → 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.
@@ -3,7 +3,8 @@
3
3
  const { codeSpan } = require('./problem-wording');
4
4
 
5
5
  const FORMAT_PART_LIMIT = 1000;
6
- const EARLIEST_FORMAT_SECONDS = -62135596800;
6
+ const MAXIMUM_TIME_DIGITS = 9;
7
+ const EARLIEST_FORMAT_SECONDS = -62167219200;
7
8
  const LATEST_FORMAT_SECONDS = 253402300800;
8
9
  const SECONDS_PER_DAY = 86400;
9
10
  const WHOLE_NUMBER_LIMIT = 2 ** 63;
@@ -85,8 +86,11 @@ const FORMAT_VERB_RULES = new Map([
85
86
  takesOperand: true,
86
87
  kinds: ['whole', 'number'],
87
88
  readsWidth: true,
89
+ readsPrecision: true,
90
+ readsDateFormat: true,
88
91
  }],
89
92
  ]);
93
+ const DATE_VERB_LETTERS = 'YymdHMSLz';
90
94
 
91
95
  /**
92
96
  * The standard's format function: the layout with each verb written from the
@@ -118,8 +122,10 @@ function formatLayout(layout, operands) {
118
122
  /**
119
123
  * The layout read into its parts, `{ text }` for literal text, `%%` read as
120
124
  * 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.
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.
123
129
  */
124
130
  function parseLayout(layout) {
125
131
  const layoutCharacters = Array.from(layout);
@@ -131,7 +137,8 @@ function parseLayout(layout) {
131
137
  continue;
132
138
  }
133
139
  const directive = readFormatDirective(layoutCharacters, position);
134
- if (directive === null) throw new Error(`layout ${codeSpan(layout)} ends inside a verb`);
140
+ if (directive.dateFormatProblem !== null) throw new Error(directive.dateFormatProblem);
141
+ if (!directive.isComplete) throw new Error(`layout ${codeSpan(layout)} ends inside a verb`);
135
142
  position = directive.endPosition;
136
143
  const verbRule = FORMAT_VERB_RULES.get(directive.verb.letter);
137
144
  if (verbRule === undefined) {
@@ -151,17 +158,44 @@ function parseLayout(layout) {
151
158
  return layoutParts;
152
159
  }
153
160
 
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,
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,
162
175
  };
163
- const directive = { verb, overPartLimit: false };
164
- let position = startPosition + 1;
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;
165
199
  while (position < layoutCharacters.length && '-+0'.includes(layoutCharacters[position])) {
166
200
  if (layoutCharacters[position] === '-') verb.leftAligned = true;
167
201
  else if (layoutCharacters[position] === '+') verb.plusSigned = true;
@@ -170,17 +204,108 @@ function readFormatDirective(layoutCharacters, startPosition) {
170
204
  }
171
205
  const width = readFormatNumber(layoutCharacters, position, directive);
172
206
  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;
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);
178
247
  }
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;
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 };
184
309
  }
185
310
 
186
311
  function readFormatNumber(layoutCharacters, startPosition, directive) {
@@ -203,9 +328,16 @@ function directivePartProblem({ verb, writtenText, overPartLimit }, verbRule) {
203
328
  if (verb.zeroPadded && !verbRule.readsZeroPadding) return `${fenced} takes no \`0\` flag`;
204
329
  if (verb.width !== null && !verbRule.readsWidth) return `${fenced} takes no width`;
205
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`;
206
332
  if (verb.letter === 'B' && (verb.precision === null || verb.precision < 1)) {
207
333
  return `${fenced} takes a precision of at least 1, such as \`%.64B\``;
208
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
+ }
209
341
  return null;
210
342
  }
211
343
 
@@ -256,7 +388,12 @@ function formattedVerbText(verb, verbRule, operand, operandNumber) {
256
388
  case 'x': return hexadecimalText(operand);
257
389
  case 'X': return hexadecimalText(operand).toUpperCase();
258
390
  case 'f': return signedNumberText(fixedPointText(operand, precision), verb.plusSigned);
259
- default: return dateText(operand, operandNumber);
391
+ default: return dateText(
392
+ operand,
393
+ verb.precision === null ? 0 : verb.precision,
394
+ verb.dateFormat,
395
+ operandNumber,
396
+ );
260
397
  }
261
398
  }
262
399
 
@@ -324,18 +461,57 @@ function exactBinaryParts(positiveNumber) {
324
461
  return { mantissa: fraction | (1n << 52n), binaryExponent: storedExponent - 1075 };
325
462
  }
326
463
 
327
- function dateText(operand, operandNumber) {
328
- const seconds = operand.kind === 'whole'
329
- ? Number(operand.wholeValue)
330
- : Math.floor(operand.numberValue);
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;
331
488
  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
- );
489
+ throw dateRangeProblem(operandNumber);
335
490
  }
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)}`;
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
+ );
339
515
  }
340
516
 
341
517
  function civilDateOfDays(days) {
@@ -372,15 +548,24 @@ function goQuotedText(text) {
372
548
  }
373
549
 
374
550
  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);
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);
382
567
  }
383
- return ' '.repeat(padding) + verbText;
568
+ return ' '.repeat(padding) + text;
384
569
  }
385
570
 
386
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.2",
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": {