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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
use {
proc_macro2::Span,
std::{collections::HashMap, iter::FromIterator, path::PathBuf},
syn::{
braced, bracketed,
parse::{Parse, ParseStream},
punctuated::Punctuated,
Error, Ident, LitStr, Result, Token,
},
};
#[derive(Debug, Clone)]
pub struct Config {
pub witx: WitxConf,
pub errors: ErrorConf,
pub async_: AsyncConf,
}
#[derive(Debug, Clone)]
pub enum ConfigField {
Witx(WitxConf),
Error(ErrorConf),
Async(AsyncConf),
}
mod kw {
syn::custom_keyword!(witx);
syn::custom_keyword!(witx_literal);
syn::custom_keyword!(errors);
}
impl Parse for ConfigField {
fn parse(input: ParseStream) -> Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(kw::witx) {
input.parse::<kw::witx>()?;
input.parse::<Token![:]>()?;
Ok(ConfigField::Witx(WitxConf::Paths(input.parse()?)))
} else if lookahead.peek(kw::witx_literal) {
input.parse::<kw::witx_literal>()?;
input.parse::<Token![:]>()?;
Ok(ConfigField::Witx(WitxConf::Literal(input.parse()?)))
} else if lookahead.peek(kw::errors) {
input.parse::<kw::errors>()?;
input.parse::<Token![:]>()?;
Ok(ConfigField::Error(input.parse()?))
} else if lookahead.peek(Token![async]) {
input.parse::<Token![async]>()?;
input.parse::<Token![:]>()?;
Ok(ConfigField::Async(input.parse()?))
} else {
Err(lookahead.error())
}
}
}
impl Config {
pub fn build(fields: impl Iterator<Item = ConfigField>, err_loc: Span) -> Result<Self> {
let mut witx = None;
let mut errors = None;
let mut async_ = None;
for f in fields {
match f {
ConfigField::Witx(c) => {
if witx.is_some() {
return Err(Error::new(err_loc, "duplicate `witx` field"));
}
witx = Some(c);
}
ConfigField::Error(c) => {
if errors.is_some() {
return Err(Error::new(err_loc, "duplicate `errors` field"));
}
errors = Some(c);
}
ConfigField::Async(c) => {
if async_.is_some() {
return Err(Error::new(err_loc, "duplicate `async` field"));
}
async_ = Some(c);
}
}
}
Ok(Config {
witx: witx
.take()
.ok_or_else(|| Error::new(err_loc, "`witx` field required"))?,
errors: errors.take().unwrap_or_default(),
async_: async_.take().unwrap_or_default(),
})
}
pub fn load_document(&self) -> witx::Document {
self.witx.load_document()
}
}
impl Parse for Config {
fn parse(input: ParseStream) -> Result<Self> {
let contents;
let _lbrace = braced!(contents in input);
let fields: Punctuated<ConfigField, Token![,]> =
contents.parse_terminated(ConfigField::parse)?;
Ok(Config::build(fields.into_iter(), input.span())?)
}
}
#[derive(Debug, Clone)]
pub enum WitxConf {
Paths(Paths),
Literal(Literal),
}
impl WitxConf {
pub fn load_document(&self) -> witx::Document {
match self {
Self::Paths(paths) => witx::load(paths.as_ref()).expect("loading witx"),
Self::Literal(doc) => witx::parse(doc.as_ref()).expect("parsing witx"),
}
}
}
#[derive(Debug, Clone)]
pub struct Paths(Vec<PathBuf>);
impl Paths {
pub fn new() -> Self {
Default::default()
}
}
impl Default for Paths {
fn default() -> Self {
Self(Default::default())
}
}
impl AsRef<[PathBuf]> for Paths {
fn as_ref(&self) -> &[PathBuf] {
self.0.as_ref()
}
}
impl AsMut<[PathBuf]> for Paths {
fn as_mut(&mut self) -> &mut [PathBuf] {
self.0.as_mut()
}
}
impl FromIterator<PathBuf> for Paths {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = PathBuf>,
{
Self(iter.into_iter().collect())
}
}
impl Parse for Paths {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let _ = bracketed!(content in input);
let path_lits: Punctuated<LitStr, Token![,]> = content.parse_terminated(Parse::parse)?;
let expanded_paths = path_lits
.iter()
.map(|lit| {
PathBuf::from(
shellexpand::env(&lit.value())
.expect("shell expansion")
.as_ref(),
)
})
.collect::<Vec<PathBuf>>();
Ok(Paths(expanded_paths))
}
}
#[derive(Debug, Clone)]
pub struct Literal(String);
impl AsRef<str> for Literal {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl Parse for Literal {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self(input.parse::<syn::LitStr>()?.value()))
}
}
#[derive(Clone, Default, Debug)]
pub struct ErrorConf(HashMap<Ident, ErrorConfField>);
impl ErrorConf {
pub fn iter(&self) -> impl Iterator<Item = (&Ident, &ErrorConfField)> {
self.0.iter()
}
}
impl Parse for ErrorConf {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let _ = braced!(content in input);
let items: Punctuated<ErrorConfField, Token![,]> =
content.parse_terminated(Parse::parse)?;
let mut m = HashMap::new();
for i in items {
match m.insert(i.abi_error.clone(), i.clone()) {
None => {}
Some(prev_def) => {
return Err(Error::new(
i.err_loc,
format!(
"duplicate definition of rich error type for {:?}: previously defined at {:?}",
i.abi_error, prev_def.err_loc,
),
))
}
}
}
Ok(ErrorConf(m))
}
}
#[derive(Clone)]
pub struct ErrorConfField {
pub abi_error: Ident,
pub rich_error: syn::Path,
pub err_loc: Span,
}
impl std::fmt::Debug for ErrorConfField {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ErrorConfField")
.field("abi_error", &self.abi_error)
.field("rich_error", &"(...)")
.field("err_loc", &self.err_loc)
.finish()
}
}
impl Parse for ErrorConfField {
fn parse(input: ParseStream) -> Result<Self> {
let err_loc = input.span();
let abi_error = input.parse::<Ident>()?;
let _arrow: Token![=>] = input.parse()?;
let rich_error = input.parse::<syn::Path>()?;
Ok(ErrorConfField {
abi_error,
rich_error,
err_loc,
})
}
}
#[derive(Clone, Default, Debug)]
pub struct AsyncConf(HashMap<String, Vec<String>>);
impl AsyncConf {
pub fn is_async(&self, module: &str, function: &str) -> bool {
self.0
.get(module)
.and_then(|fs| fs.iter().find(|f| *f == function))
.is_some()
}
}
impl Parse for AsyncConf {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let _ = braced!(content in input);
let items: Punctuated<AsyncConfField, Token![,]> =
content.parse_terminated(Parse::parse)?;
let mut m: HashMap<String, Vec<String>> = HashMap::new();
use std::collections::hash_map::Entry;
for i in items {
let function_names = i
.function_names
.iter()
.map(|i| i.to_string())
.collect::<Vec<String>>();
match m.entry(i.module_name.to_string()) {
Entry::Occupied(o) => o.into_mut().extend(function_names),
Entry::Vacant(v) => {
v.insert(function_names);
}
}
}
Ok(AsyncConf(m))
}
}
#[derive(Clone)]
pub struct AsyncConfField {
pub module_name: Ident,
pub function_names: Vec<Ident>,
pub err_loc: Span,
}
impl Parse for AsyncConfField {
fn parse(input: ParseStream) -> Result<Self> {
let err_loc = input.span();
let module_name = input.parse::<Ident>()?;
let _doublecolon: Token![::] = input.parse()?;
let lookahead = input.lookahead1();
if lookahead.peek(syn::token::Brace) {
let content;
let _ = braced!(content in input);
let function_names: Punctuated<Ident, Token![,]> =
content.parse_terminated(Parse::parse)?;
Ok(AsyncConfField {
module_name,
function_names: function_names.iter().cloned().collect(),
err_loc,
})
} else if lookahead.peek(Ident) {
let name = input.parse()?;
Ok(AsyncConfField {
module_name,
function_names: vec![name],
err_loc,
})
} else {
Err(lookahead.error())
}
}
}