-
Notifications
You must be signed in to change notification settings - Fork 24
/
token.go
210 lines (178 loc) · 4.59 KB
/
token.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
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
// Copyright 2020 Marius Ackerman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package token generates the Rust token module
package token
import (
"bytes"
"text/template"
"github.com/goccmack/gogll/v3/symbols"
"github.com/goccmack/goutil/ioutil"
)
type Data struct {
Types []*TypeDef
TypeToString []string
}
type TypeDef struct {
Name, Comment string
Suppress bool
}
func Gen(fname string) {
// fmt.Println(fname)
tmpl, err := template.New("Rust token").Parse(tmplSrc)
if err != nil {
panic(err)
}
w := new(bytes.Buffer)
if err := tmpl.Execute(w, getData()); err != nil {
panic(err)
}
if err := ioutil.WriteFile(fname, w.Bytes()); err != nil {
panic(err)
}
}
func getData() *Data {
return &Data{
Types: getTypes(),
TypeToString: symbols.GetTerminalTypeStrings(),
}
}
func getTypes() (types []*TypeDef) {
for _, t := range symbols.GetTerminals() {
types = append(types,
&TypeDef{
Name: t.TypeString(),
Comment: t.Literal(),
Suppress: t.Suppress(),
})
}
return
}
const tmplSrc = `
//! Module token is generated by GoGLL. Do not edit
extern crate lazy_static;
use std::rc::Rc;
use std::fmt;
use lazy_static::lazy_static;
use std::collections::HashMap;
/// Token is returned by the lexer for every scanned lexical token
pub struct Token {
pub typ: Type,
pub lext: usize,
pub rext: usize,
input: Rc<Vec<char>>,
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub enum Type { {{range $t := .Types}}
{{$t.Name}}, // "{{$t.Comment}}"{{end}}
}
/**
New returns a new token.
lext is the left extent and rext the right extent of the token in the input.
input is the input slice scanned by the lexer.
*/
pub fn new<'a>(t: Type, lext: usize, rext: usize, input: &Rc<Vec<char>>) -> Rc<Token> {
Rc::new(Token{
typ: t,
lext: lext,
rext: rext,
input: input.clone(),
})
}
impl Token {
/// get_line_column returns the (line, column) of the left extent of the token
pub fn get_line_column(&self) -> (usize, usize) {
let mut line = 1;
let mut col = 1;
let mut j = 0;
while j < self.lext {
match self.input[j] {
'\n' => {
line += 1;
col = 1
},
'\t' => col += 4,
_ => col += 1
}
j += 1
}
(line, col)
}
/// returns the id of the token
#[allow(dead_code)]
pub fn id(&self) -> &'static str {
TYPE_TO_ID[&self.typ]
}
/// literal returns the literal runes of t scanned by the lexer
pub fn literal(&self) -> Vec<char> {
self.input[self.lext..self.rext].to_vec()
}
/// literal_string returns the literal string of t scanned by the lexer
#[allow(dead_code)]
pub fn literal_string(&self) -> String {
self.literal().iter().collect::<String>()
}
/// returns true iff this token is suppressed by the lexer
#[allow(dead_code)]
pub fn suppress(&self) -> bool {
SUPPRESS[&self.typ]
}
} // impl Token
impl <'a>fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (ln, col) = self.get_line_column();
write!(f, "({}, ({},{}) {})",
self.typ, ln, col, self.literal().iter().collect::<String>())
}
}
impl <'a>Type {
/// id returns the token type ID of token Type t
#[allow(dead_code)]
pub fn id(&self) -> &'a str {
TYPE_TO_ID[self]
}
}
impl <'a>fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", TYPE_TO_ID[self])
}
}
lazy_static! {
static ref TYPE_TO_ID: HashMap<Type, &'static str> = {
let mut m = HashMap::new(); {{range $t := .Types}}
m.insert(Type::{{$t.Name}}, "{{$t.Comment}}");{{end}}
m
};
}
lazy_static! {
static ref ID_TO_TYPE: HashMap<&'static str, Type> = {
let mut m = HashMap::new(); {{range $t := .Types}}
m.insert("{{$t.Comment}}", Type::{{$t.Name}}); {{end}}
m
};
}
lazy_static! {
static ref STRING_TO_TYPE: HashMap<&'static str, Type> = {
let mut m = HashMap::new(); {{range $typ := .TypeToString}}
m.insert("{{$typ}}", Type::{{$typ}}); {{end}}
m
};
}
lazy_static! {
static ref SUPPRESS: HashMap<Type, bool> = {
let mut m = HashMap::new(); {{range $t := .Types}}
m.insert(Type::{{$t.Name}}, {{$t.Suppress}});{{end}}
m
};
}
`