Debian Codegraph @

example/nolexer/util/litconv.go

raw symbols SCIP
1 // Code generated by gocc; DO NOT EDIT.
2
3 package util
4
5 import (
6 "fmt"
7 "strconv"
8 "unicode"
9 "unicode/utf8"
10 )
11
12 // Interface.
13
14 // RuneValue will convert the literal value of a scanned token to a rune.
15 func RuneValue(lit []byte) rune {
16 if lit[1] == '\\' {
17 return escapeCharVal(lit)
18 }
19 r, size := utf8.DecodeRune(lit[1:])
20 if size != len(lit)-2 {
21 panic(fmt.Sprintf("Error decoding rune. Lit: %s, rune: %d, size%d\n", lit, r, size))
22 }
23 return r
24 }
25
26 // UintValue will attempt to parse a byte-slice as a signed base-10 64-bit integer.
27 func IntValue(lit []byte) (int64, error) {
28 return strconv.ParseInt(string(lit), 10, 64)
29 }
30
31 // UintValue will attempt to parse a byte-slice as an unsigned base-10 64-bit integer.
32 func UintValue(lit []byte) (uint64, error) {
33 return strconv.ParseUint(string(lit), 10, 64)
34 }
35
36 // Helpers.
37 func escapeCharVal(lit []byte) rune {
38 var i, base, max uint32
39 offset := 2
40 switch lit[offset] {
41 case 'a':
42 return '\a'
43 case 'b':
44 return '\b'
45 case 'f':
46 return '\f'
47 case 'n':
48 return '\n'
49 case 'r':
50 return '\r'
51 case 't':
52 return '\t'
53 case 'v':
54 return '\v'
55 case '\\':
56 return '\\'
57 case '\'':
58 return '\''
59 case '0', '1', '2', '3', '4', '5', '6', '7':
60 i, base, max = 3, 8, 255
61 case 'x':
62 i, base, max = 2, 16, 255
63 offset++
64 case 'u':
65 i, base, max = 4, 16, unicode.MaxRune
66 offset++
67 case 'U':
68 i, base, max = 8, 16, unicode.MaxRune
69 offset++
70 default:
71 panic(fmt.Sprintf("Error decoding character literal: %s\n", lit))
72 }
73
74 var x uint32
75 for ; i > 0 && offset < len(lit)-1; i-- {
76 ch, size := utf8.DecodeRune(lit[offset:])
77 offset += size
78 d := uint32(digitVal(ch))
79 if d >= base {
80 panic(fmt.Sprintf("charVal(%s): illegal character (%c) in escape sequence. size=%d, offset=%d", lit, ch, size, offset))
81 }
82 x = x*base + d
83 }
84 if x > max || 0xD800 <= x && x < 0xE000 {
85 panic(fmt.Sprintf("Error decoding escape char value. Lit:%s, offset:%d, escape sequence is invalid Unicode code point\n", lit, offset))
86 }
87
88 return rune(x)
89 }
90
91 func digitVal(ch rune) int {
92 switch {
93 case '0' <= ch && ch <= '9':
94 return int(ch) - '0'
95 case 'a' <= ch && ch <= 'f':
96 return int(ch) - 'a' + 10
97 case 'A' <= ch && ch <= 'F':
98 return int(ch) - 'A' + 10
99 }
100 return 16 // larger than any legal digit val
101 }