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
|
use proc_macro2::TokenStream;
use quote::ToTokens;
use shared::{Config, Syntax};
use std::path::PathBuf;
use syn;
pub struct TemplateInput<'a> {
pub ast: &'a syn::DeriveInput,
pub config: &'a Config<'a>,
pub syntax: &'a Syntax<'a>,
pub source: Source,
pub print: Print,
pub escaping: EscapeMode,
pub ext: Option<String>,
pub parent: Option<&'a syn::Type>,
pub path: PathBuf,
}
impl<'a> TemplateInput<'a> {
/// Extract the template metadata from the `DeriveInput` structure. This
/// mostly recovers the data for the `TemplateInput` fields from the
/// `template()` attribute list fields; it also finds the of the `_parent`
/// field, if any.
pub fn new<'n>(ast: &'n syn::DeriveInput, config: &'n Config) -> TemplateInput<'n> {
// Check that an attribute called `template()` exists and that it is
// the proper type (list).
let mut meta = None;
for attr in &ast.attrs {
match attr.interpret_meta() {
Some(m) => if m.name() == "template" {
meta = Some(m)
},
None => {
let mut tokens = TokenStream::new();
attr.to_tokens(&mut tokens);
panic!("unable to interpret attribute: {}", tokens)
}
}
}
let meta_list = match meta.expect("no attribute 'template' found") {
syn::Meta::List(inner) => inner,
_ => panic!("attribute 'template' has incorrect type"),
};
// Loop over the meta attributes and find everything that we
// understand. Raise panics if something is not right.
// `source` contains an enum that can represent `path` or `source`.
let mut source = None;
let mut print = Print::None;
let mut escaping = None;
let mut ext = None;
let mut syntax = None;
for nm_item in meta_list.nested {
if let syn::NestedMeta::Meta(ref item) = nm_item {
if let syn::Meta::NameValue(ref pair) = item {
match pair.ident.to_string().as_ref() {
"path" => if let syn::Lit::Str(ref s) = pair.lit {
if source.is_some() {
panic!("must specify 'source' or 'path', not both");
}
source = Some(Source::Path(s.value()));
} else {
panic!("template path must be string literal");
},
"source" => if let syn::Lit::Str(ref s) = pair.lit {
if source.is_some() {
panic!("must specify 'source' or 'path', not both");
}
source = Some(Source::Source(s.value()));
} else {
panic!("template source must be string literal");
},
"print" => if let syn::Lit::Str(ref s) = pair.lit {
print = s.value().into();
} else {
panic!("print value must be string literal");
},
"escape" => if let syn::Lit::Str(ref s) = pair.lit {
escaping = Some(s.value().into());
} else {
panic!("escape value must be string literal");
},
"ext" => if let syn::Lit::Str(ref s) = pair.lit {
ext = Some(s.value());
} else {
panic!("ext value must be string literal");
},
"syntax" => if let syn::Lit::Str(ref s) = pair.lit {
syntax = Some(s.value())
} else {
panic!("syntax value must be string literal");
},
attr => panic!("unsupported annotation key '{}' found", attr),
}
}
}
}
// Validate the `source` and `ext` value together, since they are
// related. In case `source` was used instead of `path`, the value
// of `ext` is merged into a synthetic `path` value here.
let source = source.expect("template path or source not found in attributes");
let path = match (&source, &ext) {
(&Source::Path(ref path), None) => config.find_template(path, None),
(&Source::Source(_), Some(ext)) => PathBuf::from(format!("{}.{}", ast.ident, ext)),
(&Source::Path(_), Some(_)) => {
panic!("'ext' attribute cannot be used with 'path' attribute")
}
(&Source::Source(_), None) => {
panic!("must include 'ext' attribute when using 'source' attribute")
}
};
// Check to see if a `_parent` field was defined on the context
// struct, and store the type for it for use in the code generator.
let parent = match ast.data {
syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(ref fields),
..
}) => fields
.named
.iter()
.find(|f| f.ident.as_ref().filter(|name| *name == "_parent").is_some())
.map(|f| &f.ty),
_ => None,
};
// Validate syntax
let syntax = syntax.map_or_else(
|| config.syntaxes.get(config.default_syntax).unwrap(),
|s| {
config
.syntaxes
.get(&s)
.expect(&format!("attribute syntax {} not exist", s))
},
);
if syntax.block_start.len() != 2
|| syntax.block_end.len() != 2
|| syntax.expr_start.len() != 2
|| syntax.expr_end.len() != 2
|| syntax.comment_start.len() != 2
|| syntax.comment_end.len() != 2
{
panic!("length of delimiters must be two")
}
let bs = syntax.block_start.as_bytes()[0];
let be = syntax.block_start.as_bytes()[1];
let cs = syntax.comment_start.as_bytes()[0];
let ce = syntax.comment_start.as_bytes()[1];
let es = syntax.block_start.as_bytes()[0];
let ee = syntax.block_start.as_bytes()[1];
if !(bs == cs && bs == es) && !(be == ce && be == ee) {
panic!("bad delimiters block_start: {}, comment_start: {}, expr_start: {}, needs one of the two characters in common", syntax.block_start, syntax.comment_start, syntax.expr_start);
}
TemplateInput {
ast,
config,
source,
print,
escaping: escaping.unwrap_or_else(|| EscapeMode::from_path(&path)),
ext,
parent,
path,
syntax,
}
}
}
pub enum Source {
Path(String),
Source(String),
}
#[derive(PartialEq)]
pub enum EscapeMode {
Html,
None,
}
impl From<String> for EscapeMode {
fn from(s: String) -> EscapeMode {
use self::EscapeMode::*;
match s.as_ref() {
"html" => Html,
"none" => None,
v => panic!("invalid value for escape option: {}", v),
}
}
}
impl EscapeMode {
fn from_path(path: &PathBuf) -> EscapeMode {
let extension = path.extension().map(|s| s.to_str().unwrap()).unwrap_or("");
if HTML_EXTENSIONS.contains(&extension) {
EscapeMode::Html
} else {
EscapeMode::None
}
}
}
#[derive(PartialEq)]
pub enum Print {
All,
Ast,
Code,
None,
}
impl From<String> for Print {
fn from(s: String) -> Print {
use self::Print::*;
match s.as_ref() {
"all" => All,
"ast" => Ast,
"code" => Code,
"none" => None,
v => panic!("invalid value for print option: {}", v),
}
}
}
const HTML_EXTENSIONS: [&str; 3] = ["html", "htm", "xml"];
|