-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
418 lines (366 loc) · 10.3 KB
/
Copy patherrors.go
File metadata and controls
418 lines (366 loc) · 10.3 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
// Completion: 100% - Error handling complete, clear and helpful messages
package main
import (
"errors"
"fmt"
"strings"
)
// ErrAlreadyReported signals that a full, formatted diagnostic has already been
// written to stderr (e.g. by the parser's ErrorCollector, complete with source
// snippet and caret). Callers that see this error should fail with a non-zero
// exit status WITHOUT printing anything further, so the user is not shown a
// second, redundant, context-free copy of the same failure.
var ErrAlreadyReported = errors.New("compilation aborted (diagnostics already reported)")
// reportedError is an error that has already been printed to stderr in full. It
// still carries the plain-text diagnostic so programmatic callers (and tests)
// can inspect err.Error(), while matching ErrAlreadyReported via errors.Is so
// the top-level CLI knows not to print it a second time.
type reportedError struct{ msg string }
func (e *reportedError) Error() string { return e.msg }
// Is lets errors.Is(err, ErrAlreadyReported) succeed for any reportedError.
func (e *reportedError) Is(target error) bool { return target == ErrAlreadyReported }
// newReportedError builds an already-reported error carrying the given message.
func newReportedError(msg string) error { return &reportedError{msg: msg} }
// ErrorLevel indicates the severity of an error
type ErrorLevel int
const (
LevelWarning ErrorLevel = iota
LevelError
LevelFatal
)
func (l ErrorLevel) String() string {
switch l {
case LevelWarning:
return "warning"
case LevelError:
return "error"
case LevelFatal:
return "fatal error"
default:
return "unknown"
}
}
// ErrorCategory classifies the type of error
type ErrorCategory int
const (
CategorySyntax ErrorCategory = iota
CategorySemantic
CategoryCodegen
CategoryInternal
)
func (c ErrorCategory) String() string {
switch c {
case CategorySyntax:
return "syntax"
case CategorySemantic:
return "semantic"
case CategoryCodegen:
return "codegen"
case CategoryInternal:
return "internal"
default:
return "unknown"
}
}
// SourceLocation represents a position in source code
type SourceLocation struct {
File string
Line int
Column int
Length int // Length of the problematic token/expression
}
func (loc SourceLocation) String() string {
if loc.File == "" {
return fmt.Sprintf("%d:%d", loc.Line, loc.Column)
}
return fmt.Sprintf("%s:%d:%d", loc.File, loc.Line, loc.Column)
}
// ErrorContext provides additional context for an error
type ErrorContext struct {
SourceLine string // The actual line of source code
Suggestion string // "Did you mean 'x'?"
HelpText string // Explanatory help text
}
// CompilerError represents a single compilation error
type CompilerError struct {
Level ErrorLevel
Category ErrorCategory
Message string
Location SourceLocation
Context ErrorContext
}
// Error implements the error interface
func (e CompilerError) Error() string {
return fmt.Sprintf("%s: %s", e.Location, e.Message)
}
// Format returns a nicely formatted error message with context
func (e CompilerError) Format(useColor bool) string {
var sb strings.Builder
// Error header
if useColor {
sb.WriteString("\033[1;31m") // Bold red
}
sb.WriteString(e.Level.String())
sb.WriteString(": ")
if useColor {
sb.WriteString("\033[0m") // Reset
}
sb.WriteString(e.Message)
sb.WriteString("\n")
// Location
if useColor {
sb.WriteString("\033[1;34m") // Bold blue
}
sb.WriteString(" --> ")
sb.WriteString(e.Location.String())
if useColor {
sb.WriteString("\033[0m")
}
sb.WriteString("\n")
// Source context
if e.Context.SourceLine != "" {
lineNum := fmt.Sprintf("%d", e.Location.Line)
padding := strings.Repeat(" ", len(lineNum)+1)
sb.WriteString(padding)
sb.WriteString("|\n")
sb.WriteString(lineNum)
sb.WriteString(" | ")
sb.WriteString(e.Context.SourceLine)
sb.WriteString("\n")
sb.WriteString(padding)
sb.WriteString("| ")
// Underline the error position
if e.Location.Column > 0 {
sb.WriteString(strings.Repeat(" ", e.Location.Column-1))
if useColor {
sb.WriteString("\033[1;31m") // Bold red
}
if e.Location.Length > 0 {
sb.WriteString(strings.Repeat("^", e.Location.Length))
} else {
sb.WriteString("^")
}
if useColor {
sb.WriteString("\033[0m")
}
sb.WriteString("\n")
}
}
// Suggestion
if e.Context.Suggestion != "" {
if useColor {
sb.WriteString("\033[1;32m") // Bold green
}
sb.WriteString(" help: ")
if useColor {
sb.WriteString("\033[0m")
}
sb.WriteString(e.Context.Suggestion)
sb.WriteString("\n")
}
// Help text
if e.Context.HelpText != "" {
if useColor {
sb.WriteString("\033[1;36m") // Bold cyan
}
sb.WriteString(" note: ")
if useColor {
sb.WriteString("\033[0m")
}
sb.WriteString(e.Context.HelpText)
sb.WriteString("\n")
}
return sb.String()
}
// ErrorCollector accumulates errors during compilation
type ErrorCollector struct {
errors []CompilerError
warnings []CompilerError
maxErrors int
sourceCode string // Full source code for context
}
// NewErrorCollector creates a new error collector
func NewErrorCollector(maxErrors int) *ErrorCollector {
if maxErrors <= 0 {
maxErrors = 10 // Default: stop after 10 errors
}
return &ErrorCollector{
errors: make([]CompilerError, 0),
warnings: make([]CompilerError, 0),
maxErrors: maxErrors,
}
}
// SetSourceCode stores the source code for error context
func (ec *ErrorCollector) SetSourceCode(source string) {
ec.sourceCode = source
}
// AddError adds a compilation error
func (ec *ErrorCollector) AddError(err CompilerError) {
// Auto-populate source line if not provided
if err.Context.SourceLine == "" && ec.sourceCode != "" {
err.Context.SourceLine = ec.getSourceLine(err.Location.Line)
}
if err.Level == LevelFatal || err.Level == LevelError {
ec.errors = append(ec.errors, err)
} else {
ec.warnings = append(ec.warnings, err)
}
}
// AddWarning adds a warning
func (ec *ErrorCollector) AddWarning(warn CompilerError) {
warn.Level = LevelWarning
if warn.Context.SourceLine == "" && ec.sourceCode != "" {
warn.Context.SourceLine = ec.getSourceLine(warn.Location.Line)
}
ec.warnings = append(ec.warnings, warn)
}
// getSourceLine extracts a specific line from source code
func (ec *ErrorCollector) getSourceLine(lineNum int) string {
if ec.sourceCode == "" || lineNum <= 0 {
return ""
}
lines := strings.Split(ec.sourceCode, "\n")
if lineNum > len(lines) {
return ""
}
return lines[lineNum-1]
}
// HasErrors returns true if any errors were collected
func (ec *ErrorCollector) HasErrors() bool {
return len(ec.errors) > 0
}
// HasFatalError returns true if any fatal errors were collected
func (ec *ErrorCollector) HasFatalError() bool {
for _, err := range ec.errors {
if err.Level == LevelFatal {
return true
}
}
return false
}
// ErrorCount returns the number of errors
func (ec *ErrorCollector) ErrorCount() int {
return len(ec.errors)
}
// WarningCount returns the number of warnings
func (ec *ErrorCollector) WarningCount() int {
return len(ec.warnings)
}
// ShouldStop returns true if we've hit the error limit
func (ec *ErrorCollector) ShouldStop() bool {
return len(ec.errors) >= ec.maxErrors
}
// Report formats all errors and warnings for display
func (ec *ErrorCollector) Report(useColor bool) string {
var sb strings.Builder
// Report all errors
for i, err := range ec.errors {
if i > 0 {
sb.WriteString("\n")
}
sb.WriteString(err.Format(useColor))
}
// Report all warnings
for i, warn := range ec.warnings {
if i > 0 || len(ec.errors) > 0 {
sb.WriteString("\n")
}
sb.WriteString(warn.Format(useColor))
}
// Summary
if len(ec.errors) > 0 || len(ec.warnings) > 0 {
sb.WriteString("\n")
if len(ec.errors) > 0 {
if useColor {
sb.WriteString("\033[1;31m")
}
sb.WriteString(fmt.Sprintf("%d error(s)", len(ec.errors)))
if useColor {
sb.WriteString("\033[0m")
}
}
if len(ec.warnings) > 0 {
if len(ec.errors) > 0 {
sb.WriteString(", ")
}
if useColor {
sb.WriteString("\033[1;33m")
}
sb.WriteString(fmt.Sprintf("%d warning(s)", len(ec.warnings)))
if useColor {
sb.WriteString("\033[0m")
}
}
sb.WriteString(" found\n")
}
return sb.String()
}
// Clear resets the error collector
func (ec *ErrorCollector) Clear() {
ec.errors = make([]CompilerError, 0)
ec.warnings = make([]CompilerError, 0)
}
// Helper functions for creating common errors
// UndefinedVariableError creates an error for undefined variables
func UndefinedVariableError(name string, loc SourceLocation) CompilerError {
return CompilerError{
Level: LevelError,
Category: CategorySemantic,
Message: fmt.Sprintf("undefined variable '%s'", name),
Location: loc,
Context: ErrorContext{
HelpText: "Variables must be declared before use",
},
}
}
// TypeMismatchError creates an error for type mismatches
func TypeMismatchError(expected, actual string, loc SourceLocation) CompilerError {
return CompilerError{
Level: LevelError,
Category: CategorySemantic,
Message: fmt.Sprintf("type mismatch: expected %s, got %s", expected, actual),
Location: loc,
}
}
// ImmutableUpdateError creates an error for updating immutable variables
func ImmutableUpdateError(name string, loc SourceLocation) CompilerError {
return CompilerError{
Level: LevelError,
Category: CategorySemantic,
Message: fmt.Sprintf("cannot update immutable variable '%s'", name),
Location: loc,
Context: ErrorContext{
Suggestion: fmt.Sprintf("declare '%s' as mutable with ':='", name),
},
}
}
// SyntaxError creates a syntax error
func SyntaxError(message string, loc SourceLocation) CompilerError {
return CompilerError{
Level: LevelError,
Category: CategorySyntax,
Message: message,
Location: loc,
}
}
// UnexpectedTokenError creates an error for unexpected tokens
func UnexpectedTokenError(expected, got string, loc SourceLocation) CompilerError {
return CompilerError{
Level: LevelError,
Category: CategorySyntax,
Message: fmt.Sprintf("expected %s, got %s", expected, got),
Location: loc,
}
}
// FatalError creates a fatal internal error
func FatalError(message string, loc SourceLocation) CompilerError {
return CompilerError{
Level: LevelFatal,
Category: CategoryInternal,
Message: message,
Location: loc,
Context: ErrorContext{
HelpText: "This is an internal compiler error. Please report this bug.",
},
}
}