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
//! Base helper routines for a code generator.
use grammar::repr::*;
use lr1::core::*;
use rust::RustWrite;
use std::io::{self, Write};
use util::Sep;
/// Base struct for various kinds of code generator. The flavor of
/// code generator is customized by supplying distinct types for `C`
/// (e.g., `self::ascent::RecursiveAscent`).
pub struct CodeGenerator<'codegen, 'grammar: 'codegen, W: Write + 'codegen, C> {
/// the complete grammar
pub grammar: &'grammar Grammar,
/// some suitable prefix to separate our identifiers from the user's
pub prefix: &'grammar str,
/// types from the grammar
pub types: &'grammar Types,
/// the start symbol S the user specified
pub user_start_symbol: NonterminalString,
/// the synthetic start symbol S' that we specified
pub start_symbol: NonterminalString,
/// the vector of states
pub states: &'codegen [LR1State<'grammar>],
/// where we write output
pub out: &'codegen mut RustWrite<W>,
/// where to find the action routines (typically `super`)
pub action_module: String,
/// custom fields for the specific kind of codegenerator
/// (recursive ascent, table-driven, etc)
pub custom: C,
pub repeatable: bool,
}
impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> {
pub fn new(grammar: &'grammar Grammar,
user_start_symbol: NonterminalString,
start_symbol: NonterminalString,
states: &'codegen [LR1State<'grammar>],
out: &'codegen mut RustWrite<W>,
repeatable: bool,
action_module: &str,
custom: C)
-> Self {
CodeGenerator {
grammar: grammar,
prefix: &grammar.prefix,
types: &grammar.types,
states: states,
user_start_symbol: user_start_symbol,
start_symbol: start_symbol,
out: out,
custom: custom,
repeatable: repeatable,
action_module: action_module.to_string(),
}
}
pub fn write_parse_mod<F>(&mut self, body: F) -> io::Result<()>
where F: FnOnce(&mut Self) -> io::Result<()>
{
rust!(self.out, "");
rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol);
// these stylistic lints are annoying for the generated code,
// which doesn't follow conventions:
rust!(self.out,
"#![allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, \
unused_imports)]");
rust!(self.out, "");
try!(self.write_uses());
try!(body(self));
rust!(self.out, "}}");
Ok(())
}
pub fn write_uses(&mut self) -> io::Result<()> {
try!(self.out.write_uses(&format!("{}::", self.action_module), &self.grammar));
if self.grammar.intern_token.is_none() {
rust!(self.out, "use {}::{}ToTriple;", self.action_module, self.prefix);
}
Ok(())
}
pub fn start_parser_fn(&mut self) -> io::Result<()> {
let error_type = self.types.error_type();
let parse_error_type = self.types.parse_error_type();
let (type_parameters, parameters, mut where_clauses);
if self.grammar.intern_token.is_some() {
// if we are generating the tokenizer, we just need the
// input, and that has already been added as one of the
// user parameters
type_parameters = vec![];
parameters = vec![];
where_clauses = vec![];
} else {
// otherwise, we need an iterator of type `TOKENS`
let mut user_type_parameters = String::new();
for type_parameter in &self.grammar.type_parameters {
user_type_parameters.push_str(&format!("{}, ", type_parameter));
}
type_parameters = vec![format!("{}TOKEN: {}ToTriple<{}Error={}>",
self.prefix,
self.prefix,
user_type_parameters,
error_type),
format!("{}TOKENS: IntoIterator<Item={}TOKEN>",
self.prefix,
self.prefix)];
parameters = vec![format!("{}tokens0: {}TOKENS", self.prefix, self.prefix)];
where_clauses = vec![];
if self.repeatable {
where_clauses.push(format!("{}TOKENS: Clone", self.prefix));
}
}
try!(self.out.write_pub_fn_header(self.grammar,
format!("parse_{}", self.user_start_symbol),
type_parameters,
parameters,
format!("Result<{}, {}>",
self.types.nonterminal_type(self.start_symbol),
parse_error_type),
where_clauses));
rust!(self.out, "{{");
Ok(())
}
pub fn define_tokens(&mut self) -> io::Result<()> {
if self.grammar.intern_token.is_some() {
// if we are generating the tokenizer, create a matcher as our input iterator
rust!(self.out,
"let mut {}tokens = {}::{}intern_token::{}Matcher::new(input);",
self.prefix,
self.action_module,
self.prefix,
self.prefix);
} else {
// otherwise, convert one from the `IntoIterator`
// supplied, using the `ToTriple` trait which inserts
// errors/locations etc if none are given
let clone_call = if self.repeatable { ".clone()" } else { "" };
rust!(self.out,
"let {}tokens = {}tokens0{}.into_iter();",
self.prefix,
self.prefix,
clone_call);
rust!(self.out,
"let mut {}tokens = {}tokens.map(|t| {}ToTriple::to_triple(t));",
self.prefix,
self.prefix,
self.prefix);
}
Ok(())
}
pub fn end_parser_fn(&mut self) -> io::Result<()> {
rust!(self.out, "}}");
Ok(())
}
/// Returns phantom data type that captures the user-declared type
/// parameters in a phantom-data. This helps with ensuring that
/// all type parameters are constrained, even if they are not
/// used.
pub fn phantom_data_type(&self) -> String {
format!("::std::marker::PhantomData<({})>",
Sep(", ", &self.grammar.non_lifetime_type_parameters()))
}
/// Returns expression that captures the user-declared type
/// parameters in a phantom-data. This helps with ensuring that
/// all type parameters are constrained, even if they are not
/// used.
pub fn phantom_data_expr(&self) -> String {
format!("::std::marker::PhantomData::<({})>",
Sep(", ", &self.grammar.non_lifetime_type_parameters()))
}
}