forked from jeffpar/pcjs.v1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdio.js
656 lines (610 loc) · 24.7 KB
/
stdio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/**
* @fileoverview Class with stdio-like functions
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2020 Jeff Parsons
* @license MIT
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*/
"use strict";
/**
* Define the Formatter function type for addFormatType().
*
* @typedef {Function} Formatter
* @param {string} type
* @param {string} flags
* @param {number} width
* @param {number} precision
* @param {*} arg
* @returns {string}
*/
/**
* @class {StdIO}
* @unrestricted
* @property {Object.<string,(Formatter|null)>}>} formatters
*/
class StdIO extends NumIO {
/**
* StdIO()
*
* Summary of functions:
*
* addFormatType()
* flush()
* isDate()
* parseDate()
* print()
* printf()
* println()
* sprintf()
* toHex()
*
* This class is called "StdIO" rather than "stdio" because classes are global entities and I prefer global
* entities to begin with a capital letter and use camelCase. And its methods are primarily object functions
* rather than class functions, because the parent objects are typically Device objects which may wish to have
* unique "print" bindings. Mingling every object's print output in the same container may not be desired.
*
* The filename "stdio.js" is inspired by the C runtime library file "stdio.h", since it includes printf()
* and sprintf() functions that have many C-like features, but they also have many differences (both additions
* and omissions). And you will find other functions here that have no counterpart in "stdio.h", so don't take
* the name too seriously.
*
* @this {StdIO}
*/
constructor()
{
super();
/*
* We populate the sprintf() formatters table with null functions for all the predefined (built-in) types,
* so that type validation has only one look-up to perform.
*
* For reference purposes, the standard ANSI C set of format types is "dioxXucsfeEgGpn%", not all of which
* are supported. Some built-in types have been added, including Date types (see the upper-case types),
* a boolean type ('b'), and a JSON type ('j'); external format types include the Debugger Address type ('a'),
* and a default number type ('n') that selects the appropriate base type ('d', 'o', or 'x'), um, based on
* current Debugger preferences.
*/
this.formatters = {};
let predefinedTypes = "ACDFHIMNSTWYbdfjcsoXx%";
for (let i = 0; i < predefinedTypes.length; i++) {
this.formatters[predefinedTypes[i]] = null;
}
}
/**
* addFormatType(type, func)
*
* Whenever the specified type character is encountered in a sprintf() call, the specified
* function will be called with all the associated formatting parameters; the function must
* return a stringified copy of the arg.
*
* @this {StdIO}
* @param {string} type (the sprintf standard requires this be a single character)
* @param {Formatter} func
* @returns {boolean} (true if successful, false if type character has already been defined)
*/
addFormatType(type, func)
{
this.assert(!this.formatters[type]);
if (!this.formatters[type]) {
this.formatters[type] = func;
return true;
}
return false;
}
/**
* flush()
*
* @this {StdIO}
*/
flush()
{
let buffer = StdIO.PrintBuffer;
StdIO.PrintBuffer = "";
this.print(buffer);
}
/**
* getBaseName(sFileName, fStripExt)
*
* This is a poor-man's version of Node's path.basename(), which Node-only components should use instead.
*
* Note that if fStripExt is true, this strips ANY extension, whereas path.basename() strips the extension only
* if it matches the second parameter (eg, path.basename("/foo/bar/baz/asdf/quux.html", ".html") returns "quux").
*
* @this {StdIO}
* @param {string} sFileName
* @param {boolean} [fStripExt]
* @returns {string}
*/
getBaseName(sFileName, fStripExt)
{
let sBaseName = sFileName;
let i = sFileName.lastIndexOf('/');
if (i >= 0) sBaseName = sFileName.substr(i + 1);
/*
* This next bit is a kludge to clean up names that are part of a URL that includes unsightly query parameters.
*/
i = sBaseName.indexOf('&');
if (i > 0) sBaseName = sBaseName.substr(0, i);
if (fStripExt) {
i = sBaseName.lastIndexOf(".");
if (i > 0) {
sBaseName = sBaseName.substring(0, i);
}
}
return sBaseName;
}
/**
* isDate(date)
*
* @this {StdIO}
* @param {Date} date
* @returns {boolean}
*/
isDate(date)
{
return !isNaN(date.getTime());
}
/**
* parseDate(date)
* parseDate(date, time)
* parseDate(year, month, day, hour, minute, second)
*
* Produces a UTC date when ONLY a date (no time) is provided; otherwise, it combines the date and
* and time, producing a date that is either UTC or local, depending on the presence (or lack) of time
* zone information. Finally, if numeric inputs are provided, then Date.UTC() is called to generate
* a UTC time.
*
* In general, you should use this instead of new Date(), because the Date constructor implicitly calls
* Date.parse(s), which behaves inconsistently. For example, ISO date-only strings (e.g. "1970-01-01")
* generate a UTC time, but non-ISO date-only strings (eg, "10/1/1945" or "October 1, 1945") generate a
* local time.
*
* @this {StdIO}
* @param {...} args
* @returns {Date} (UTC unless a time string with a non-GMT timezone is explicitly provided)
*/
parseDate(...args)
{
let date;
if (args[0] === undefined) {
date = new Date(Date.now());
}
else if (typeof args[0] === "string") {
date = new Date(args[0] + ' ' + (args[1] || "00:00:00 GMT"));
}
else if (args[1] === undefined) {
date = new Date(args[0]);
} else {
date = new Date(Date.UTC(...args));
}
return date;
}
/**
* print(s, fBuffer)
*
* @this {StdIO}
* @param {string} s
* @param {boolean} [fBuffer] (true to always buffer; otherwise, only buffer the last partial line)
* @returns {number}
*/
print(s, fBuffer)
{
let i = s.lastIndexOf('\n');
if (!fBuffer) {
if (i >= 0) {
console.log(StdIO.PrintBuffer + s.substr(0, i));
StdIO.PrintBuffer = "";
s = s.substr(i + 1);
}
StdIO.PrintTime = null;
} else {
if (i >= 0) {
let now = Date.now();
if (!StdIO.PrintTime) StdIO.PrintTime = now;
s = ((now - StdIO.PrintTime) / 1000).toFixed(3) + ": " + s;
}
}
StdIO.PrintBuffer += s;
return s.length;
}
/**
* println(s, fBuffer)
*
* @this {StdIO}
* @param {string} s
* @param {boolean} [fBuffer] (true to always buffer; otherwise, only buffer the last partial line)
* @returns {number}
*/
println(s, fBuffer)
{
return this.print(s + '\n', fBuffer);
}
/**
* printf(format, ...args)
*
* @this {StdIO}
* @param {string} format
* @param {...} [args]
* @returns {number}
*/
printf(format, ...args)
{
return this.print(this.sprintf(format, ...args));
}
/**
* sprintf(format, ...args)
*
* Copied from the CCjs project (https://github.com/jeffpar/ccjs/blob/master/lib/stdio.js) and extended.
* Far from complete, let alone sprintf-compatible, but it's adequate for the handful of sprintf-style format
* specifiers that I use.
*
* In addition to supporting lots of handy Date formatting types (see below), it also supports custom format
* types; see addFormatType() for details.
*
* TODO: The %c and %s specifiers support a negative width for left-justified output, but the numeric specifiers
* (eg, %d and %x) do not; they support only positive widths and right-justified output. That's one of the more
* glaring omissions at the moment.
*
* @this {StdIO}
* @param {string} format
* @param {...} [args]
* @returns {string}
*/
sprintf(format, ...args)
{
/*
* This isn't just a nice optimization; it's also important if the caller is simply trying
* to printf() a string that may also contain '%' and doesn't want or expect any formatting.
*/
if (!args || !args.length) {
return format;
}
let buffer = "";
let aParts = format.split(/%([-+ 0#]*)([0-9]*|\*)(\.[0-9]+|)([hlL]?)([A-Za-z%])/);
let iArg = 0, iPart;
for (iPart = 0; iPart < aParts.length - 6; iPart += 6) {
buffer += aParts[iPart];
let arg, type = aParts[iPart+5];
/*
* Check for unrecognized types immediately, so we don't inadvertently pop any arguments.
*/
if (this.formatters[type] === undefined) {
buffer += '%' + aParts[iPart+1] + aParts[iPart+2] + aParts[iPart+3] + aParts[iPart+4] + type;
continue;
}
if (iArg < args.length) {
arg = args[iArg];
if (type != '%') iArg++;
} else {
arg = args[args.length-1];
}
let flags = aParts[iPart+1];
let hash = flags.indexOf('#') >= 0;
let zeroPad = flags.indexOf('0') >= 0;
let width = aParts[iPart+2];
if (width == '*') {
width = arg;
if (iArg < args.length) {
arg = args[iArg++];
} else {
arg = args[args.length-1];
}
} else {
width = +width || 0;
}
let precision = aParts[iPart+3];
precision = precision? +precision.substr(1) : -1;
// let length = aParts[iPart+4]; // eg, 'h', 'l' or 'L' (all currently ignored)
let ach = null, s, radix = 0, prefix = "";
/*
* The following non-standard sprintf() format types provide handy alternatives to the
* PHP date() format types that we previously used with the old datelib.formatDate() function:
*
* a: lowercase ante meridiem and post meridiem (am or pm) %A
* d: day of the month, 2 digits with leading zeros (01, 02, ..., 31) %02D
* D: 3-letter day of the week ("Sun", "Mon", ..., "Sat") %.3W
* F: month ("January", "February", ..., "December") %F
* g: hour in 12-hour format, without leading zeros (1, 2, ..., 12) %I
* h: hour in 24-hour format, without leading zeros (0, 1, ..., 23) %H
* H: hour in 24-hour format, with leading zeros (00, 01, ..., 23) %02H
* i: minutes, with leading zeros (00, 01, ..., 59) %02N
* j: day of the month, without leading zeros (1, 2, ..., 31) %D
* l: day of the week ("Sunday", "Monday", ..., "Saturday") %W
* m: month, with leading zeros (01, 02, ..., 12) %02M
* M: 3-letter month ("Jan", "Feb", ..., "Dec") %.3F
* n: month, without leading zeros (1, 2, ..., 12) %M
* s: seconds, with leading zeros (00, 01, ..., 59) %02S
* y: 2-digit year (eg, 14) %0.2Y
* Y: 4-digit year (eg, 2014) %Y
*
* We also support a few custom format types:
*
* %C: calendar output (equivalent to: %W, %F %D, %Y)
* %T: timestamp output (equivalent to: %Y-%02M-%02D %02H:%02N:%02S)
*
* Use the optional '#' flag with any of the above '%' format types to produce UTC results
* (eg, '%#I' instead of '%I').
*
* The %A, %F, and %W types act as strings (which support the '-' left justification flag, as well as
* the width and precision options), and the rest act as integers (which support the '0' padding flag
* and the width option). Also, while %Y does act as an integer, it also supports truncation using the
* precision option (normally, integers do not); this enables a variable number of digits for the year.
*
* So old code like this:
*
* printf("%s\n", formatDate("l, F j, Y", date));
*
* can now be written like this:
*
* printf("%W, %F %D, %Y\n", date, date, date, date);
*
* or even more succinctly, as:
*
* printf("%C\n", date);
*
* In fact, even the previous example can be written more succinctly as:
*
* printf("%W, %F %D, %Y\n", date);
*
* because unlike the C runtime, we reuse the final parameter once the format string has exhausted all parameters.
*/
let ch, date = /** @type {Date} */ ("ACDFHIMNSTWY".indexOf(type) >= 0 && typeof arg != "object"? this.parseDate(arg) : arg), dateUndefined;
switch(type) {
case 'C':
ch = hash? '#' : '';
buffer += (this.isDate(date)? this.sprintf(this.sprintf("%%%sW, %%%sF %%%sD, %%%sY", ch), date) : dateUndefined);
continue;
case 'D':
arg = hash? date.getUTCDate() : date.getDate();
type = 'd';
break;
case 'A':
case 'H':
case 'I':
arg = hash? date.getUTCHours() : date.getHours();
if (type == 'A') {
arg = (arg < 12 ? "am" : "pm");
type = 's';
}
else {
if (type == 'I') {
arg = (!arg? 12 : (arg > 12 ? arg - 12 : arg));
}
type = 'd';
}
break;
case 'F':
case 'M':
arg = hash? date.getUTCMonth() : date.getMonth();
if (type == 'F') {
arg = StdIO.NamesOfMonths[arg];
type = 's';
} else {
arg++;
type = 'd';
}
break;
case 'N':
arg = hash? date.getUTCMinutes() : date.getMinutes();
type = 'd';
break;
case 'S':
arg = hash? date.getUTCSeconds() : date.getSeconds();
type = 'd'
break;
case 'T':
ch = hash? '#' : '';
buffer += (this.isDate(date)? this.sprintf(this.sprintf("%%%sY-%%%s02M-%%%s02D %%%s02H:%%%s02N:%%%s02S", ch), date) : dateUndefined);
continue;
case 'W':
arg = StdIO.NamesOfDays[hash? date.getUTCDay() : date.getDay()];
type = 's';
break;
case 'Y':
arg = hash? date.getUTCFullYear() : date.getFullYear();
if (precision > 0) {
arg = arg % (Math.pow(10, precision));
precision = -1;
}
type = 'd';
break;
}
switch(type) {
case 'b':
/*
* "%b" for boolean-like values is a non-standard format specifier that seems handy.
*/
buffer += (arg? "true" : "false");
break;
case 'd':
/*
* I could use "arg |= 0", but there may be some value to supporting integers > 32 bits,
* so I use Math.trunc() instead. Bit-wise operators also mask a lot of evils, by converting
* complete nonsense into zero, so while I'm ordinarily a fan, that's not desirable here.
*
* Other (hidden) advantages of Math.trunc(): it automatically converts strings, it honors
* numeric prefixes (the traditional "0x" for hex and the newer "0o" for octal), and it returns
* NaN if the ENTIRE string cannot be converted.
*
* parseInt(), which would seem to be the more logical choice here, doesn't understand "0o",
* doesn't return NaN if non-digits are embedded in the string, and doesn't behave consistently
* across all browsers when parsing older octal values with a leading "0"; Math.trunc() doesn't
* recognize those octal values either, but I'm OK with that, as long as it CONSISTENTLY doesn't
* recognize them.
*
* That last problem is why some recommend you ALWAYS pass a radix to parseInt(), but that
* forces you to parse the string first and determine the proper radix; otherwise, you end up
* with NEW inconsistencies. For example, if radix is 10 and the string is "0x10", the result
* is zero, since parseInt() happily stops parsing when it reaches the first non-radix 10 digit.
*/
arg = Math.trunc(arg);
/*
* Before falling into the decimal floating-point code, we take this opportunity to convert
* the precision value, if any, to the minimum number of digits to print. Which basically means
* setting zeroPad to true, width to precision, and then unsetting precision.
*
* TODO: This isn't quite accurate. For example, printf("%6.3d", 3) should print " 003", not
* "000003". But once again, this isn't a common enough case to worry about.
*/
if (precision >= 0) {
zeroPad = true;
if (width < precision) width = precision;
precision = -1;
}
/* falls through */
case 'f':
arg = +arg;
s = arg + "";
if (precision >= 0) {
s = arg.toFixed(precision);
}
if (s.length < width) {
if (zeroPad) {
if (arg < 0) {
width--;
s = s.substr(1);
}
s = ("0000000000" + s).slice(-width);
if (arg < 0) s = '-' + s;
} else {
s = (" " + s).slice(-width);
}
}
buffer += s;
break;
case 'j':
/*
* 'j' is one of our non-standard extensions to the sprintf() interface; it signals that
* the caller is providing an Object that should be rendered as JSON. If a width is included
* (eg, "%2j"), it's used as an indentation value; otherwise, no whitespace is added.
*/
buffer += JSON.stringify(arg, null, width || undefined);
break;
case 'c':
arg = typeof arg == "string"? arg[0] : String.fromCharCode(arg);
/* falls through */
case 's':
/*
* 's' includes some non-standard benefits, such as coercing non-strings to strings first;
* we know undefined and null values don't have a toString() method, but hopefully everything
* else does.
*/
if (arg != undefined) {
if (typeof arg != "string") {
arg = arg.toString();
}
if (precision >= 0) {
arg = arg.substr(0, precision);
}
while (arg.length < width) {
if (flags.indexOf('-') >= 0) {
arg += ' ';
} else {
arg = ' ' + arg;
}
}
}
buffer += arg;
break;
case 'o':
radix = 8;
if (hash) prefix = "0";
/* falls through */
case 'X':
ach = StdIO.HexUpperCase;
// if (hash) prefix = "0X"; // I don't like that %#X uppercases BOTH the prefix and the value
/* falls through */
case 'x':
s = "";
if (!radix) radix = 16;
if (!prefix && hash) prefix = "0x";
if (!ach) ach = StdIO.HexLowerCase;
/*
* For all the same reasons articulated above (for type 'd'), we pass the arg through Math.trunc(),
* and we honor precision, if any, as the minimum number of digits to print.
*/
arg = Math.trunc(arg);
if (precision >= 0) {
zeroPad = true;
if (width < precision) width = precision;
precision = -1;
}
if (zeroPad && !width) {
/*
* When zero padding is specified without a width (eg, "%0x"), we select a width based on the value.
*/
let v = Math.abs(arg);
if (v <= 0xff) {
width = 2;
} else if (v <= 0xffff) {
width = 4;
} else if (v <= 0xffffffff) {
width = 8;
} else {
width = 9;
}
width += prefix.length;
}
width -= prefix.length;
do {
let d = arg & (radix - 1);
arg >>>= (radix == 16? 4 : 3);
if (zeroPad || !s || d || arg) {
s = ach[d] + s;
} else {
if (prefix) {
s = prefix + s;
prefix = "";
}
if (width > 0) s = ' ' + s;
}
} while (--width > 0 || arg);
buffer += prefix + s;
break;
case '%':
buffer += '%';
break;
default:
this.assert(this.formatters[type]);
if (this.formatters[type]) {
buffer += this.formatters[type](type, flags, width, precision, arg);
break;
}
buffer += "(unimplemented sprintf type: %" + type + ")";
break;
}
}
buffer += aParts[iPart];
return buffer;
}
/**
* toHex(n)
*
* This is a helper function mainly intended for use in a debugging console, allowing you to display numbers
* as hex by evaluating the expression "this.toHex(n)".
*
* In a C runtime, you might use "itoa(n, buffer, 16)", which would be in "stdlib" instead of "stdio", and
* it would not display a "0x" prefix; however, since we're relying on sprintf() to perform all our number
* to string conversions, and sprintf() is a "stdio" function, we're keeping all these related functions here.
*
* @this {StdIO}
* @param {number} n
*/
toHex(n)
{
return this.sprintf("%#x", n);
}
}
/*
* Global variables
*/
StdIO.PrintBuffer = "";
StdIO.PrintTime = null;
/*
* Global constants
*/
StdIO.HexLowerCase = "0123456789abcdef";
StdIO.HexUpperCase = "0123456789ABCDEF";
StdIO.NamesOfDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
StdIO.NamesOfMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
Defs.CLASSES["StdIO"] = StdIO;