-
Notifications
You must be signed in to change notification settings - Fork 24
/
slot.go
277 lines (241 loc) · 6.54 KB
/
slot.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// 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 slot generates Rust code for parser slots
package slot
import (
"bytes"
"fmt"
"text/template"
"github.com/goccmack/gogll/v3/ast"
"github.com/goccmack/gogll/v3/frstflw"
"github.com/goccmack/gogll/v3/gslot"
"github.com/goccmack/gogll/v3/symbols"
"github.com/goccmack/goutil/ioutil"
)
func Gen(slotFile string, g *ast.GoGLL, gs *gslot.GSlot, ff *frstflw.FF) {
tmpl, err := template.New("Rust Slot").Parse(slotTmpl)
if err != nil {
panic(err)
}
buf, data := new(bytes.Buffer), getData(g, gs, ff)
if err = tmpl.Execute(buf, data); err != nil {
panic(err)
}
if err := ioutil.WriteFile(slotFile, buf.Bytes()); err != nil {
panic(err)
}
}
type Data struct {
Package string
Slots []*SlotData
Alts []*AltData
}
type AltData struct {
NT string
Labels []string
}
type SlotData struct {
Label string
NT string
Alt int
Pos int
Symbols []string
Comment string
}
func getData(g *ast.GoGLL, gs *gslot.GSlot, ff *frstflw.FF) *Data {
return &Data{
Package: g.Package.GetString(),
Slots: getSlotData(gs),
Alts: getAltData(g, gs, ff),
}
}
func getAltData(g *ast.GoGLL, gs *gslot.GSlot, ff *frstflw.FF) (data []*AltData) {
for _, r := range g.SyntaxRules {
d := &AltData{r.Head.ID(), getLabelList(r, g, gs, ff)}
data = append(data, d)
}
return
}
func getLabelList(rule *ast.SyntaxRule, g *ast.GoGLL, gs *gslot.GSlot, ff *frstflw.FF) (labels []string) {
for i := range rule.Alternates {
labels = append(labels,
gslot.NewLabel(rule.Head.ID(), i, 0, gs, ff).Label())
}
return
}
func getSlotData(gs *gslot.GSlot) (data []*SlotData) {
for _, s := range gs.Slots() {
d := &SlotData{
Label: s.Label(),
NT: s.Head,
Alt: s.Alternate,
Pos: s.Pos,
Symbols: getSymbols(s.Symbols()),
Comment: s.String(),
}
data = append(data, d)
}
return
}
func getSymbols(syms symbols.Symbols) []string {
ss := make([]string, len(syms))
for i, sym := range syms {
switch s := sym.(type) {
case symbols.NT:
ss[i] = fmt.Sprintf("NT(NT::%s)", s.Literal())
case symbols.T:
ss[i] = fmt.Sprintf("T(T::T%d)", s-symbols.StartOfTokens)
default:
panic("invalid")
}
}
return ss
}
const slotTmpl = `//! Module slot is generated by gogll. Do not edit.
extern crate lazy_static;
use lazy_static::lazy_static;
use super::symbols::{Symbol, NT, T};
use std::collections::HashMap;
use std::fmt;
#[derive(Hash, Eq, PartialEq, Clone, Copy, Debug)]
pub enum Label { {{range $i, $l := .Slots}}
{{$l.Label}},{{end}}
}
#[allow(dead_code)]
pub struct Slot {
nt: NT,
alt: usize,
pos: usize,
symbols: Vec<Symbol>,
label: Label,
}
#[derive(Hash, Eq, PartialEq)]
pub struct Index {
pub nt: NT,
pub alt: usize,
pub pos: usize,
}
#[allow(dead_code)]
pub fn get_alternates(nt: &NT) -> &'static Vec<Label> {
if let Some(alts) = ALTERNATES.get(nt) {
return alts
}
panic!("{} has no alternates", nt)
}
#[allow(dead_code)]
pub fn get_label(nt: &NT, alt: usize, pos: usize) -> Label {
if let Some(l) = LABELS.get(&Index{nt: nt.clone(), alt: alt, pos: pos}) {
return l.clone()
}
panic!("No label for {} alt {} pos {}", nt, alt, pos)
}
impl <'a>Label {
#[allow(dead_code)]
pub fn eor(&self) -> bool {
self.slot().eor()
}
#[allow(dead_code)]
pub fn head(&self) -> &'static NT {
&self.slot().nt
}
pub fn index(&self) -> Index {
let s = self.slot();
Index{nt: s.nt, alt: s.alt, pos: s.pos}
}
#[allow(dead_code)]
pub fn alternate(&self) -> usize {
self.slot().alt
}
#[allow(dead_code)]
pub fn pos(&self) -> usize {
self.slot().pos
}
#[allow(dead_code)]
pub fn slot(&self) -> &'static Slot {
if let Some(s) = SLOTS.get(self) {
return s
}
panic!("Invalid slot label {}", self)
}
#[allow(dead_code)]
pub fn symbols(&self) -> &'a Vec<Symbol> {
&self.slot().symbols
}
}
/*** end of impl Label***/
impl fmt::Display for Label {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let slt = self.slot();
let mut s = format!("{} :", slt.nt);
for (i, sym) in slt.symbols.iter().enumerate() {
if i == slt.pos {
s.push_str("•")
}
s.push_str(&format!("{} ", sym));
}
write!(f, "{}", s)
}
}
impl Slot {
#[allow(dead_code)]
pub fn eor(&self) -> bool {
self.pos >= self.symbols.len()
}
} /*** impl Slot ***/
impl fmt::Display for Slot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = format!("{} : ", self.nt);
for (i, sym) in self.symbols.iter().enumerate() {
if i == self.pos {
s.push_str("•")
}
s.push_str(&format!("{} ", sym));
}
if self.pos >= self.symbols.len() {
s.push_str("•")
}
write!(f, "{}", s)
}
}
lazy_static! {
static ref ALTERNATES: HashMap<NT, Vec<Label>> = {
let mut m = HashMap::new(); {{range $a := .Alts}}
m.insert(NT::{{$a.NT}},
vec![ {{range $l := $a.Labels}}
Label::{{$l}},{{end}}
]);{{end}}
m
};
static ref LABELS: HashMap<Index, Label> = {
let mut m = HashMap::new(); {{range $i, $s := .Slots}}
m.insert(Index{nt:NT::{{$s.NT}}, alt:{{$s.Alt}}, pos:{{$s.Pos}}}, Label::{{$s.Label}}); {{end}}
m
};
static ref SLOTS: HashMap<Label, Slot> = {
let mut m = HashMap::new(); {{range $i, $s := .Slots}}
// {{$s.Comment}}
m.insert(Label::{{$s.Label}},
Slot{
nt: NT::{{$s.NT}},
alt: {{$s.Alt}},
pos: {{$s.Pos}},
symbols: vec![ {{range $sym := $s.Symbols}}
Symbol::{{$sym}}, {{end}}
],
label: Label::{{$s.Label}},
});{{end}}
m
};
}
`