error.go (1902B)
1 package ast 2 3 import ( 4 `fmt` 5 `strings` 6 `unsafe` 7 8 `github.com/bytedance/sonic/internal/native/types` 9 ) 10 11 func (self *Parser) syntaxError(err types.ParsingError) SyntaxError { 12 return SyntaxError{ 13 Pos : self.p, 14 Src : self.s, 15 Code: err, 16 } 17 } 18 19 func newSyntaxError(err SyntaxError) *Node { 20 msg := err.Description() 21 return &Node{ 22 t: V_ERROR, 23 v: int64(err.Code), 24 p: unsafe.Pointer(&msg), 25 } 26 } 27 28 type SyntaxError struct { 29 Pos int 30 Src string 31 Code types.ParsingError 32 Msg string 33 } 34 35 func (self SyntaxError) Error() string { 36 return fmt.Sprintf("%q", self.Description()) 37 } 38 39 func (self SyntaxError) Description() string { 40 return "Syntax error " + self.description() 41 } 42 43 func (self SyntaxError) description() string { 44 i := 16 45 p := self.Pos - i 46 q := self.Pos + i 47 48 /* check for empty source */ 49 if self.Src == "" { 50 return fmt.Sprintf("no sources available: %#v", self) 51 } 52 53 /* prevent slicing before the beginning */ 54 if p < 0 { 55 p, q, i = 0, q - p, i + p 56 } 57 58 /* prevent slicing beyond the end */ 59 if n := len(self.Src); q > n { 60 n = q - n 61 q = len(self.Src) 62 63 /* move the left bound if possible */ 64 if p > n { 65 i += n 66 p -= n 67 } 68 } 69 70 /* left and right length */ 71 x := clamp_zero(i) 72 y := clamp_zero(q - p - i - 1) 73 74 /* compose the error description */ 75 return fmt.Sprintf( 76 "at index %d: %s\n\n\t%s\n\t%s^%s\n", 77 self.Pos, 78 self.Message(), 79 self.Src[p:q], 80 strings.Repeat(".", x), 81 strings.Repeat(".", y), 82 ) 83 } 84 85 func (self SyntaxError) Message() string { 86 if self.Msg == "" { 87 return self.Code.Message() 88 } 89 return self.Msg 90 } 91 92 func clamp_zero(v int) int { 93 if v < 0 { 94 return 0 95 } else { 96 return v 97 } 98 }