Repository navigation
Expand file tree
/
Copy pathexceptions.ts
More file actions
811 lines (730 loc) Β· 21.6 KB
/
Copy pathexceptions.ts
File metadata and controls
811 lines (730 loc) Β· 21.6 KB
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import { ExitCode, ExitCoded } from './exit';
import { errorType, ErrorCode } from './errors';
import { Formattable, Formatter, formatter } from './format';
import { Traceable, Traceback } from './traceback';
import type { Value } from './value';
import { Source } from './ast/source';
/**
* The base class for all Exceptions, including fatal exceptions.
*/
@errorType('BaseException')
export class BaseException extends Error implements Traceable, Formattable {
/**
* @param message The message for the exception.
* @param traceback The traceback for the exception.
*/
constructor(
public message: any,
public traceback: Traceback | null = null,
) {
const msg =
typeof message === 'string' ? message : formatter.format(message);
super(msg);
Object.setPrototypeOf(this, new.target.prototype);
// TODO: Exceptions in Python store all args the constructor is called
// with, not just a message.
// TODO: Implement notes a la Python?
// See: https://docs.python.org/3/tutorial/errors.html#enriching-exceptions-with-notes
}
format(formatter: Formatter): string {
return formatter.formatBaseException(this);
}
}
/**
* The base class for all built-in, non-fatal exceptions. User
* exceptions should be derived from this class.
*/
@errorType('Exception')
export class Exception extends BaseException {}
//
// Non-fatal errors.
//
/**
* An exception raised by an assertion.
*/
@errorType('AssertionError')
export class AssertionError extends Exception {
format(formatter: Formatter): string {
return formatter.formatAssertionError(this);
}
}
/**
* An exception raised on errors in the runtime.
*/
@errorType('RuntimeError')
export class RuntimeError extends Exception {}
/**
* An exception raised when casting is not supported.
*/
@errorType('TypeError')
export class TypeError extends RuntimeError {
public from: string;
public to: string;
/**
* @param message The message for the exception.
* @param value The value attempted to cast
* @param from_ The type attempted to cast from
* @param to_ The type attempted to cast to
* @param traceback The traceback for the exception.
*/
constructor(
public readonly message: any,
public readonly value: Value,
from_: string,
to_: string,
public traceback: Traceback | null = null,
) {
super(message, traceback);
this.from = from_;
this.to = to_;
}
format(formatter: Formatter): string {
return formatter.formatTypeError(this);
}
}
/**
* An exception raised for unexpected values. Extends RuntimeError.
*/
@errorType('ValueError')
export class ValueError extends RuntimeError {}
/**
* An exception raised when a variable or property can't be found. Extends
* RuntimeError.
*/
@errorType('NameError')
export class NameError extends RuntimeError {}
/**
* An exception raised when an unexpected parameter is encountered. Extends
* RuntimeError.
*/
@errorType('ParamError')
export class ParamError extends RuntimeError {}
/**
* An exception raised for various arithmetic errors. Extends RuntimeError.
*/
@errorType('ArithmeticError')
export class ArithmeticError extends RuntimeError {}
/**
* An exception raised when attempting to divide by zero. Extends
* ArithmeticError.
*/
@errorType('ZeroDivisionError')
export class ZeroDivisionError extends ArithmeticError {
constructor(
public readonly a: Value,
public readonly typeA: string,
public readonly b: Value,
public readonly typeB: string,
public traceback: Traceback | null = null,
) {
const message = 'Cannot divide by zero';
super(message, traceback);
Object.setPrototypeOf(this, new.target.prototype);
}
format(formatter: Formatter): string {
return formatter.formatZeroDivisionError(this);
}
}
/**
* An exception raised when functionality is not implemented. Extends
* RuntimeError.
*/
@errorType('NotImplementedError')
export class NotImplementedError extends RuntimeError {}
//
// Warnings.
//
/**
* The base class for all warnings. Warnings are non-fatal and can not be
* caught.
*/
@errorType('BaseWarning')
export class BaseWarning extends BaseException {
format(formatter: Formatter): string {
return formatter.formatBaseWarning(this);
}
}
/**
* The base class for all user warnings.
*/
@errorType('Warning')
export class Warning extends BaseWarning {}
/**
* A warning for deprecated functionality.
*/
@errorType('DeprecationWarning')
export class DeprecationWarning extends Warning {}
//
// OS and file IO errors.
//
/**
* An operating system level error.
*/
@errorType('OsError')
export class OsError extends Exception implements ExitCoded {
public readonly exitCode: ExitCode;
/**
* @param message The message for the exception.
* @param code The Node.JS system error code.
* @param exitCode The exit code for the exception. If null, a default exit
* code will be set based on the error code.
* @param traceback The traceback for the exception.
*/
constructor(
public readonly message: any,
public readonly code: ErrorCode | string,
exitCode: ExitCode | null,
public readonly traceback: Traceback | null,
) {
super(message, traceback);
Object.setPrototypeOf(this, new.target.prototype);
if (exitCode) {
this.exitCode = exitCode;
} else {
switch (code) {
// NOTE: For FileErrors, ErrorCode.Access maps to ExitCode.NoInput
// for read operations and ExitCode.CantCreate for write operations.
case ErrorCode.Access:
this.exitCode = ExitCode.OsError;
break;
case ErrorCode.AddressInUse:
// There are arguments for this being Unavailable, OsError or
// Software.
this.exitCode = ExitCode.Protocol;
break;
case ErrorCode.ConnectionRefused:
case ErrorCode.ConnectionReset:
this.exitCode = ExitCode.Unavailable;
break;
case ErrorCode.Exists:
this.exitCode = ExitCode.CantCreate;
break;
case ErrorCode.IsDirectory:
this.exitCode = ExitCode.IoError;
break;
case ErrorCode.MaxFileDescriptors:
this.exitCode = ExitCode.OsError;
break;
case ErrorCode.NoEntity:
this.exitCode = ExitCode.NoInput;
break;
case ErrorCode.NotADirectory:
this.exitCode = ExitCode.NoInput;
break;
case ErrorCode.NotEmpty:
// TODO: There's an argument for this being an IoError.
this.exitCode = ExitCode.OsError;
break;
case ErrorCode.DnsNotFound:
this.exitCode = ExitCode.NoHost;
break;
case ErrorCode.NotPermitted:
// NOTE: Assuming this will not be seen for user filesystem
// permissions.
this.exitCode = ExitCode.NoPermission;
break;
case ErrorCode.BrokenPipe:
this.exitCode = ExitCode.OsError;
break;
case ErrorCode.TimedOut:
// NOTE: Unavailable is appropriate for network timeouts. For other
// kinds of timeout, there may be better exit codes.
this.exitCode = ExitCode.Unavailable;
break;
default:
this.exitCode = ExitCode.OsError;
}
}
}
format(formatter: Formatter): string {
return formatter.formatOsError(this);
}
}
/**
* The path(s) being used by an operations which raised a FileError.
*/
export type FileErrorPaths = [string] | [string, string];
function getFileErrorMessage(err: NodeJS.ErrnoException): string {
const split = err.message.split(': ');
if (split.length === 2) {
return split[1];
}
return err.message;
}
/**
* An error raised when a known file operation fails. Includes the target
* filename(s) and a more specific exit code.
*/
@errorType('FileError')
export class FileError extends OsError {
/**
* @param message The message for the exception.
* @param code The Node.JS system error code.
* @param exitCode The exit code for the exception. If null, a default exit
* code will be set based on the error code.
* @param paths The target path(s) for the operation.
* @param traceback The traceback for the exception.
*/
constructor(
public message: any,
public code: ErrorCode | string,
exitCode: ExitCode | null,
public paths: FileErrorPaths,
public traceback: Traceback | null,
) {
super(message, code, exitCode, traceback);
Object.setPrototypeOf(this, new.target.prototype);
}
/**
* Naively create a FileError from a Node.js error.
*
* @param message The message for the error. If null, taken directly from
* the Node.JS error.
* @param err The Node.JS error.
* @param traceback The traceback for the error.
*/
static fromError(
message: any,
err: NodeJS.ErrnoException,
traceback: Traceback | null = null,
): FileError {
const msg = message || getFileErrorMessage(err);
return new FileError(
msg,
err.code || '<unknown>',
null,
[err.path || '<unknown>'],
traceback,
);
}
/**
* Create a FileError from a Node.js error for a read operation.
*
* @param message The message for the error. If null, taken directly from
* the Node.JS error.
* @param err The Node.JS error.
* @param traceback The traceback for the error.
*/
static fromReadError(
message: any,
err: NodeJS.ErrnoException,
traceback: Traceback | null = null,
): FileError {
const msg = message || getFileErrorMessage(err);
const code = err.code;
let exitCode: ExitCode | null = null;
if (code == ErrorCode.Access) {
exitCode = ExitCode.NoInput;
}
return new FileError(
msg,
code || '<unknown>',
exitCode,
[err.path || '<unknown>'],
traceback,
);
}
/**
* Create a FileError from a Node.js error for a write operation.
*
* @param message The message for the error. If null, taken directly from
* the Node.JS error.
* @param err The Node.JS error.
* @param traceback The traceback for the error.
*/
static fromWriteError(
message: any | null,
err: NodeJS.ErrnoException,
traceback: Traceback | null = null,
): FileError {
const msg = message || getFileErrorMessage(err);
const code = err.code;
let exitCode: ExitCode | null = null;
if (code == ErrorCode.Access) {
exitCode = ExitCode.CantCreate;
}
return new FileError(
msg,
code || '<unknown>',
exitCode,
[err.path || '<unknown>'],
traceback,
);
}
format(formatter: Formatter): string {
return formatter.formatFileError(this);
}
}
//
// Syntax and parse errors and warnings.
//
// TODO: JavaScript and Python stop after a single error. However, Matanuska
// will attempt to complete the parse and flag multiple errors, more like C.
// This leads to some questions in their interfaces:
//
// 1. Individual syntax errors and warnings inherit from BaseException and
// BaseWarning respectively. However, they don't have tracebacks - rather,
// they have source locations. This suggests, along with the fact that they
// are never thrown, that it may be inappropriate for them to be
// Traceable - or even be called errors/warnings. Note that
// the reporting in Python for source locations is very similar to
// tracebacks, just without the word "Traceback".
// 2. ParseErrors and ParseWarnings also do not take tracebacks. This is
// because parsing happens before runtime execution can occur. It may,
// however, make sense to revisit this assumption.
// 2. ParseErrors and ParseWarnings have blank messages. This is acceptable
// because the reporting will be based on the syntax errors/warnings, not
// the top-level parse error. Should these classes have a message
// getter that calls a formatter? Should they have a sensible default
// message? This is an open question.
//
/**
* The location referenced by a syntax error or warning.
*/
export interface SourceLocation {
/**
* The filename for the source code. This may be <interactive> for
* interactive code, or <untitled> if the edited code has not been saved.
*/
filename: string;
/**
* The row number in the source code. This is well defined even if the
* input isn't a line.
*/
row: number;
/**
* Whether or not the source location is in a line.
*/
isLine: boolean;
/**
* The line number in the source code. When not in a line, this is the
* previous line number.
*/
lineNo: number | null;
/**
* The command number in the source code.
*/
cmdNo: number | null;
/**
* The column offset at which the location starts.
*/
offsetStart: number;
/**
* The column offset at which the location ends.
*/
offsetEnd: number;
/**
* The referenced source code. Will typically be a line or interactive
* command.
*/
source: Source;
// TODO: Add this when there are multi-line sytax structures.
// endLineNo: number | null,
}
export type LocationKey = 'row' | 'lineNo' | 'cmdNo' | 'offsetStart';
export type ParseErrorSplit = Record<number, ParseError | ParseWarning>;
export type ParseWarningSplit = Record<number, ParseWarning>;
export interface LocationSortable {
sort(keys: LocationKey[]): void;
}
function compareLocationKeys(keys: LocationKey[]) {
return function compare(a: SourceLocation, b: SourceLocation): number {
for (const key of keys) {
const aKey: number = a[key] === null ? -1 : (a[key] as number);
const bKey: number = b[key] === null ? -1 : (b[key] as number);
const cmp = aKey - bKey;
if (cmp) {
return cmp;
}
}
return 0;
};
}
/**
* An individual syntax error. Typically there will be multiple syntax errors
* or warnings encapsulated in a ParseError. They are not intended to be
* thrown.
*/
@errorType('SyntaxError')
export class SyntaxError extends BaseException implements SourceLocation {
public filename: string;
public row: number;
public isLine: boolean;
public lineNo: number;
public cmdNo: number;
public offsetStart: number;
public offsetEnd: number;
public source: Source;
/**
* @param message The message for the exception.
* @param location The location for the syntax error.
*/
constructor(message: any, location: SourceLocation) {
super(message, null);
Object.setPrototypeOf(this, new.target.prototype);
Object.assign(this, location);
}
format(formatter: Formatter): string {
return formatter.formatSyntaxError(this);
}
}
/**
* A parse error. May contain one or more syntax errors or warnings.
*/
export class ParseError
extends Exception
implements LocationSortable, ExitCoded
{
public exitCode = ExitCode.Software;
/**
* @param message The message for the exception.
* @param errors A collection of syntax errors and warnings.
* @param traceback The traceback for the exception.
*/
constructor(public errors: Array<SyntaxError | SyntaxWarning>) {
super('', null);
Object.setPrototypeOf(this, new.target.prototype);
}
sort(keys: LocationKey[]): void {
this.errors.sort(compareLocationKeys(keys));
}
format(formatter: Formatter): string {
return formatter.formatParseError(this);
}
}
/**
* A syntax warning. These warnings don't cause an unsuccessful parse, but are
* likely undesirable. Typically there will be multiple syntax warnings
* encapsulated in a ParseWarning. They are not intended to be logged
* directly.
*/
@errorType('SyntaxWarning')
export class SyntaxWarning extends BaseWarning implements SourceLocation {
public filename: string;
public row: number;
public isLine: boolean;
public lineNo: number;
public cmdNo: number;
public offsetStart: number;
public offsetEnd: number;
public source: Source;
/**
* @param message The message for the exception.
* @param location The location for the syntax error.
*/
constructor(message: any, location: SourceLocation) {
super(message, null);
Object.setPrototypeOf(this, new.target.prototype);
Object.assign(this, location);
}
format(formatter: Formatter): string {
return formatter.formatSyntaxWarning(this);
}
}
/**
* A parse warning. This is analogous to a syntax error, but contains only
* warnings.
*/
@errorType('ParseWarning')
export class ParseWarning extends Exception implements LocationSortable {
/**
* @param message The message for the exception.
* @param warnings A collection of syntax warnings.
* @param traceback The traceback for the exception.
*/
constructor(public warnings: Array<SyntaxWarning>) {
super('', null);
Object.setPrototypeOf(this, new.target.prototype);
}
sort(keys: LocationKey[]): void {
this.warnings.sort(compareLocationKeys(keys));
}
format(formatter: Formatter): string {
return formatter.formatParseWarning(this);
}
}
// The assumption is that errors are already sorted. This may not
// be technically true, but it may be true *enough* that the result is
// sensible.
function merge<T extends SourceLocation>(
xs: T[],
ys: T[],
keys: LocationKey[],
): T[] {
let i = 0;
let j = 0;
const merged: T[] = [];
while (true) {
if (i >= xs.length) {
return merged.concat(ys.slice(j));
}
if (j >= ys.length) {
return merged.concat(xs.slice(i));
}
for (const key of keys) {
const xKey: number =
typeof xs[i][key] === 'number' ? (xs[i][key] as number) : -1;
const yKey: number =
typeof ys[j][key] === 'number' ? (ys[j][key] as number) : -1;
if (xKey < yKey) {
merged.push(xs[i++]);
break;
}
if (xKey > yKey) {
merged.push(ys[j++]);
break;
}
}
}
}
/**
* Merge a collection of ParseErrors and/or ParseWarnings. Returns a
* ParseError if any of its arguments are errors. If all arguments are null,
* returns null. Otherwise, returns a ParseWarning.
*
* @param ...errors A list of ParseErrors and ParseWarnings
* @returns A ParseError or ParseWarning
*/
function mergeParseErrors(errors: Array<null>): null;
function mergeParseErrors(errors: Array<null>, keys: LocationKey[]): null;
function mergeParseErrors(errors: Array<ParseWarning | null>): ParseWarning;
function mergeParseErrors(
errors: Array<ParseWarning | null>,
keys: LocationKey[],
): ParseWarning;
function mergeParseErrors(
errors: Array<ParseError | ParseWarning | null>,
): ParseError;
function mergeParseErrors(
errors: Array<ParseError | ParseWarning | null>,
keys: LocationKey[],
): ParseError;
function mergeParseErrors(
errors: Array<ParseError | ParseWarning | null>,
keys: LocationKey[] = ['lineNo', 'row', 'offsetStart'],
): ParseError | ParseWarning | null {
let isError = false;
let isWarning = false;
let syntaxErrors: Array<SyntaxError | SyntaxWarning> = [];
for (const err of errors) {
if (err instanceof ParseError) {
isError = true;
syntaxErrors = merge(syntaxErrors, err.errors, keys);
} else if (err instanceof ParseWarning) {
isWarning = true;
syntaxErrors = merge(syntaxErrors, err.warnings, keys);
}
}
if (isError) {
return new ParseError(syntaxErrors as Array<SyntaxError | SyntaxWarning>);
}
if (isWarning) {
return new ParseWarning(syntaxErrors as SyntaxWarning[]);
}
return null;
}
/**
* Split a ParseError or ParseWarning into a Record of multiple ParseErrors or
* ParseWarnings, grouped by the given key. If passed null, returns an empty
* record.
*
* @returns A record mapping row number to ParseError or ParseWarning.
*/
function splitParseError(
error: ParseError | null,
key: LocationKey,
): ParseErrorSplit;
function splitParseError(
error: ParseWarning | null,
key: LocationKey,
): ParseWarningSplit;
function splitParseError(
error: ParseError | ParseWarning | null,
key: LocationKey,
): ParseErrorSplit | Record<number, null> {
const isError: Record<number, boolean> = {};
const splitted: Record<number, Array<SyntaxError | SyntaxWarning>> = {};
function split(errors: Array<SyntaxError | SyntaxWarning>): void {
for (const err of errors) {
if (!splitted[err[key]]) {
splitted[err[key]] = [];
}
if (err instanceof ParseError) {
isError[err[key]] = true;
}
splitted[err[key]].push(err);
}
}
if (error instanceof ParseError) {
split(error.errors);
} else if (error instanceof ParseWarning) {
split(error.warnings);
} else if (error === null) {
return {} as Record<number, null>;
}
return Object.fromEntries(
Object.entries(splitted).map(([row, errs]) => {
let error: ParseError | ParseWarning;
if (isError[row]) {
error = new ParseError(errs);
} else {
error = new ParseWarning(errs);
}
return [row, error];
}),
);
}
function removeFromParseError(
err: ParseError | null,
key: LocationKey,
value: number,
): ParseError | ParseWarning | null;
function removeFromParseError(
err: ParseWarning | null,
key: LocationKey,
value: number,
): ParseWarning | null;
function removeFromParseError(
err: ParseError | ParseWarning | null,
key: LocationKey,
value: number,
): ParseError | ParseWarning | null {
let errors: Array<SyntaxError | SyntaxWarning> = [];
if (err === null) {
return null;
}
if (err instanceof ParseError) {
errors = err.errors;
} else {
errors = err.warnings;
}
let isError = false;
errors = errors.filter((e) => {
if (e[key] === value) {
return false;
}
if (e instanceof SyntaxError) {
isError = true;
}
return true;
});
if (isError) {
return new ParseError(errors);
} else {
return new ParseWarning(errors);
}
}
function sortParseError(
err: ParseError | ParseWarning | null,
keys: LocationKey[],
): void {
if (err) {
err.sort(keys);
}
}
export {
mergeParseErrors,
splitParseError,
removeFromParseError,
sortParseError,
};