|
| 1 | +package tokenizer |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | +) |
| 6 | + |
| 7 | +/////////////////////////////////////////////////////////////////////////////// |
| 8 | +// TYPES |
| 9 | + |
| 10 | +// Pos marks the position within a context, like a file path. If path is |
| 11 | +// nil then Pos is not used. Note that Line and Col are zero-indexed, so |
| 12 | +// 1 needs to be added to them when printing. |
| 13 | +type Pos struct { |
| 14 | + Path *string |
| 15 | + Line uint |
| 16 | + Col uint |
| 17 | + |
| 18 | + // Record previous position for unread |
| 19 | + x, y uint |
| 20 | +} |
| 21 | + |
| 22 | +// Error with a position |
| 23 | +type PosError struct { |
| 24 | + Err error |
| 25 | + Pos Pos |
| 26 | +} |
| 27 | + |
| 28 | +/////////////////////////////////////////////////////////////////////////////// |
| 29 | +// LIFECYCLE |
| 30 | + |
| 31 | +func NewPosError(err error, pos Pos) error { |
| 32 | + return &PosError{Err: err, Pos: pos} |
| 33 | +} |
| 34 | + |
| 35 | +func NewParseError(t *Token) error { |
| 36 | + return &PosError{Err: ErrBadParameter.Withf("Parse error near %q", t.toString()), Pos: t.Pos} |
| 37 | +} |
| 38 | + |
| 39 | +/////////////////////////////////////////////////////////////////////////////// |
| 40 | +// STRINGIFY |
| 41 | + |
| 42 | +func (p *Pos) String() string { |
| 43 | + if p.Path == nil || *p.Path == "" { |
| 44 | + return fmt.Sprintf("pos<%d:%d>", p.Line+1, p.Col+1) |
| 45 | + } else { |
| 46 | + return fmt.Sprintf("pos<%s:%d:%d>", *p.Path, p.Line+1, p.Col+1) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func (e *PosError) Error() string { |
| 51 | + if e.Pos.Path == nil || *e.Pos.Path == "" { |
| 52 | + return fmt.Errorf("%d:%d: %w", e.Pos.Line+1, e.Pos.Col+1, e.Err).Error() |
| 53 | + } else { |
| 54 | + return fmt.Errorf("%s:%d:%d: %w", *e.Pos.Path, e.Pos.Line+1, e.Pos.Col+1, e.Err).Error() |
| 55 | + } |
| 56 | +} |
0 commit comments