-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer_error.go
46 lines (40 loc) · 1.06 KB
/
lexer_error.go
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
package golex
import (
"fmt"
"strings"
)
// LexerError represents an error that occurred during lexical analysis.
type Error struct {
Message string
Position Position
Snippet string
}
// Error implements the error interface for LexerError
func (e *Error) Error() string {
return fmt.Sprintf("%s: %s\n%s", e.Position.String(), e.Message, e.formatSnippet())
}
func NewError(message string, position Position, input []rune) *Error {
snippet := extractSnippet(input, position.Cursor)
return &Error{
Message: message,
Position: position,
Snippet: snippet,
}
}
// Formats the snippet with a caret (^) to indicate the exact error location.
func (e *Error) formatSnippet() string {
caretPosition := strings.Repeat(" ", e.Position.Col-1) + "^"
return fmt.Sprintf(" %s\n %s", e.Snippet, caretPosition)
}
func extractSnippet(input []rune, cursor int) string {
const contextLength = 20
start := cursor - contextLength
if start < 0 {
start = 0
}
end := cursor + contextLength
if end > len(input) {
end = len(input)
}
return string(input[start:end])
}