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
use crate::ast;
use std::mem;
use syn::parse::{Parse, ParseStream};
use syn::{self, spanned::Spanned};
use syn::{punctuated::Punctuated, Token};

mod kw {
    syn::custom_keyword!(custom_id);
    syn::custom_keyword!(inc_id);
    syn::custom_keyword!(intern);
    syn::custom_keyword!(relation);
    syn::custom_keyword!(auto);
    syn::custom_keyword!(key);
}

impl Parse for ast::CustomId {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::custom_id>()?;
        let name = input.parse()?;
        input.parse::<Token![:]>()?;
        let typ = input.parse()?;
        let content;
        syn::braced!(content in input);
        let mut items = Vec::new();
        while !content.is_empty() {
            items.push(content.parse()?);
        }
        Ok(Self { name, typ, items })
    }
}

impl Parse for ast::Constant {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let _attrs = input.call(syn::Attribute::parse_outer)?;
        Ok(Self {
            name: input.parse()?,
            value: {
                input.parse::<Token![=]>()?;
                input.parse()?
            },
        })
    }
}

impl Parse for ast::IncrementalId {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::inc_id>()?;
        let name = input.parse()?;
        input.parse::<Token![:]>()?;
        let typ = input.parse()?;
        let content;
        syn::braced!(content in input);
        let punctuated: Punctuated<_, Token![,]> =
            content.parse_terminated(ast::Constant::parse)?;
        let constants = punctuated
            .into_pairs()
            .map(|pair| pair.into_value())
            .collect();
        Ok(Self {
            name,
            typ,
            constants,
        })
    }
}

impl Parse for ast::InternedId {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name = input.parse()?;
        input.parse::<Token![<]>()?;
        let typ = input.parse()?;
        input.parse::<Token![>]>()?;
        Ok(Self { name, typ })
    }
}

impl Parse for ast::InterningTable {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::intern>()?;
        let name = input.parse()?;
        input.parse::<Token![<]>()?;
        let value = input.parse()?;
        input.parse::<Token![as]>()?;
        let key = input.parse()?;
        input.parse::<Token![>]>()?;
        input.parse::<Token![;]>()?;
        Ok(Self { name, key, value })
    }
}

impl Parse for ast::Enum {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut item: syn::ItemEnum = input.parse()?;
        let mut default = None;
        for variant in &mut item.variants {
            let mut new_attrs = Vec::new();
            for attr in mem::replace(&mut variant.attrs, Vec::new()) {
                if attr.path.is_ident("default") && attr.tokens.is_empty() {
                    default = Some(variant.ident.clone());
                }
            }
            mem::swap(&mut variant.attrs, &mut new_attrs)
        }
        let default =
            default.ok_or_else(|| syn::Error::new(item.span(), "missing #[default] variant"))?;
        Ok(Self { item, default })
    }
}

impl Parse for ast::RelationParameter {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name = input.parse()?;
        input.parse::<Token![:]>()?;
        let is_autogenerated = if input.peek(kw::auto) {
            input.parse::<kw::auto>()?;
            true
        } else {
            false
        };
        let typ = input.parse()?;
        Ok(Self {
            name,
            typ,
            is_autogenerated,
        })
    }
}

/// A helper struct for parsing the relation key.
#[derive(PartialEq, Eq)]
enum RelationKey {
    /// No key.
    None,
    /// Some key.
    Some {
        source: RelationKeySource,
        target: Option<syn::Ident>,
    },
}

#[derive(PartialEq, Eq)]
enum RelationKeySource {
    /// Wildcard key `*`.
    Wildcard,
    /// An explicit key.
    Explicit(Vec<syn::Ident>),
}

impl Parse for RelationKey {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if !input.peek(kw::key) {
            return Ok(RelationKey::None);
        }
        input.parse::<kw::key>()?;
        input.parse::<Token![=]>()?;
        let key_content;
        syn::bracketed!(key_content in input);
        let lookahead = key_content.lookahead1();
        let key_source = if lookahead.peek(Token![*]) {
            key_content.parse::<Token![*]>()?;
            RelationKeySource::Wildcard
        } else {
            let content;
            syn::parenthesized!(content in key_content);
            let punctuated: Punctuated<_, Token![,]> =
                content.parse_terminated(syn::Ident::parse)?;
            RelationKeySource::Explicit(punctuated.into_iter().collect())
        };
        key_content.parse::<Token![=>]>()?;
        let target = if key_content.peek(Token![_]) {
            key_content.parse::<Token![_]>()?;
            None
        } else {
            Some(key_content.parse()?)
        };
        Ok(RelationKey::Some {
            source: key_source,
            target: target,
        })
    }
}

impl Parse for ast::Relation {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(kw::relation) {
            input.parse::<kw::relation>()?;
        } else {
            return Err(lookahead.error());
        }
        let parsed_key = input.parse()?;
        let name: syn::Ident = input.parse()?;
        let content;
        syn::parenthesized!(content in input);
        let punctuated: Punctuated<_, Token![,]> =
            content.parse_terminated(ast::RelationParameter::parse)?;
        let parameters: Vec<_> = punctuated
            .into_pairs()
            .map(|pair| pair.into_value())
            .collect();
        input.parse::<Token![;]>()?;
        if parsed_key != RelationKey::None {
            if parameters
                .iter()
                .filter(|parameter| parameter.is_autogenerated)
                .count()
                > 1
            {
                return Err(syn::Error::new(
                    name.span(),
                    "Relation must have exactly at most 1 auto parameter when `key` is specified.",
                ));
            }
        }
        let key = match parsed_key {
            RelationKey::None => None,
            RelationKey::Some { source, target } => match source {
                RelationKeySource::Wildcard => Some(ast::RelationKey {
                    source: parameters
                        .iter()
                        .filter(|parameter| {
                            target
                                .as_ref()
                                .map(|ident| ident != &parameter.name)
                                .unwrap_or(true)
                        })
                        .map(|parameter| parameter.name.clone())
                        .collect(),
                    target: target,
                }),
                RelationKeySource::Explicit(idents) => Some(ast::RelationKey {
                    source: idents,
                    target: target,
                }),
            },
        };
        Ok(Self {
            name,
            parameters,
            key,
        })
    }
}

impl Parse for ast::Relations {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut relations = Vec::new();
        while !input.is_empty() {
            let _attrs = input.call(syn::Attribute::parse_outer)?;
            let relation: ast::Relation = input.parse()?;
            relations.push(relation);
        }
        Ok(Self { relations })
    }
}

impl Parse for ast::DatabaseSchema {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut schema = ast::DatabaseSchema::default();
        while !input.is_empty() {
            let _attrs = input.call(syn::Attribute::parse_outer)?;
            let lookahead = input.lookahead1();
            if lookahead.peek(kw::custom_id) {
                let custom_id: ast::CustomId = input.parse()?;
                // inc_id.comments = _attrs; TODO
                schema.custom_ids.push(custom_id);
            } else if lookahead.peek(kw::inc_id) {
                let inc_id: ast::IncrementalId = input.parse()?;
                // inc_id.comments = _attrs; TODO
                schema.incremental_ids.push(inc_id);
            } else if lookahead.peek(kw::intern) {
                let intern_table: ast::InterningTable = input.parse()?;
                schema.interning_tables.push(intern_table);
            } else if lookahead.peek(Token![enum]) {
                let item: ast::Enum = input.parse()?;
                schema.enums.push(item);
            } else if lookahead.peek(kw::relation) {
                let relation: ast::Relation = input.parse()?;
                schema.relations.push(relation);
            } else {
                return Err(lookahead.error());
            }
        }
        Ok(schema)
    }
}