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
355
356
357
358
359
360
361
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Intermediate representation (IR) for codegen.

use std::collections::{BTreeMap, BTreeSet};
use std::iter;

use anyhow::{bail, Result};
use itertools::Itertools;
use quote::ToTokens;

/// The intermediate representation.
pub struct Ir {
    /// The items in the IR.
    pub items: BTreeMap<String, Item>,
    /// The generic parameters that appear throughout the IR.
    ///
    /// Walkabout assumes that generic parameters are named consistently
    /// throughout the types in the IR. This field maps each generic parameter
    /// to the union of all trait bounds required of that parameter.
    pub generics: BTreeMap<String, BTreeSet<String>>,
}

/// An item in the IR.
#[derive(Debug)]
pub enum Item {
    /// A struct item.
    Struct(Struct),
    /// An enum item.
    Enum(Enum),
    /// An abstract item, introduced via a generic parameter.
    Abstract,
}

impl Item {
    pub fn fields<'a>(&'a self) -> Box<dyn Iterator<Item = &Field> + 'a> {
        match self {
            Item::Struct(s) => Box::new(s.fields.iter()),
            Item::Enum(e) => Box::new(e.variants.iter().flat_map(|v| &v.fields)),
            Item::Abstract => Box::new(iter::empty()),
        }
    }

    pub fn generics(&self) -> &[ItemGeneric] {
        match self {
            Item::Struct(s) => &s.generics,
            Item::Enum(e) => &e.generics,
            Item::Abstract => &[],
        }
    }
}

/// A struct in the IR.
#[derive(Debug)]
pub struct Struct {
    /// The fields of the struct.
    pub fields: Vec<Field>,
    /// The generic parameters on the struct.
    pub generics: Vec<ItemGeneric>,
}

/// An enum in the IRs.
#[derive(Debug)]
pub struct Enum {
    /// The variants of the enum.
    pub variants: Vec<Variant>,
    /// The generic parameters on the enum.
    pub generics: Vec<ItemGeneric>,
}

/// A variant of an [`Enum`].
#[derive(Debug)]
pub struct Variant {
    /// The name of the variant.
    pub name: String,
    /// The fields of the variant.
    pub fields: Vec<Field>,
}

/// A field of a [`Variant`] or [`Struct`].
#[derive(Debug)]
pub struct Field {
    /// The optional name of the field.
    ///
    /// If omitted, the field is referred to by its index in its container.
    pub name: Option<String>,
    /// The type of the field.
    pub ty: Type,
}

/// A generic parameter of an [`Item`].
#[derive(Debug)]
pub struct ItemGeneric {
    /// The name of the generic parameter.
    pub name: String,
    /// The trait bounds on the generic parameter.
    pub bounds: Vec<String>,
}

/// The type of a [`Field`].
#[derive(Debug)]
pub enum Type {
    /// A primitive Rust type.
    ///
    /// Primitive types do not need to be visited.
    Primitive,
    /// Abstract type.
    ///
    /// Abstract types are visited, but their default visit function does
    /// nothing.
    Abstract(String),
    /// An [`Option`] type..
    ///
    /// The value inside the option will need to be visited if the option is
    /// `Some`.
    Option(Box<Type>),
    /// A [`Vec`] type.
    ///
    /// Each value in the vector will need to be visited.
    Vec(Box<Type>),
    /// A [`Box`] type.
    ///
    /// The value inside the box will need to be visited.
    Box(Box<Type>),
    /// A type local to the AST.
    ///
    /// The value will need to be visited by calling the appropriate `Visit`
    /// or `VisitMut` trait method on the value.
    Local(String),
    /// A BTreeMap type
    ///
    /// Each value will need to be visited.
    Map { key: Box<Type>, value: Box<Type> },
}

/// Analyzes the provided items and produces an IR.
///
/// This is a very, very lightweight semantic analysis phase for Rust code. Our
/// main goal is to determine the type of each field of a struct or enum
/// variant, so we know how to visit it. See [`Type`] for details.
pub(crate) fn analyze(syn_items: &[syn::DeriveInput]) -> Result<Ir> {
    let mut items = BTreeMap::new();
    for syn_item in syn_items {
        let name = syn_item.ident.to_string();
        let generics = analyze_generics(&syn_item.generics)?;
        let item = match &syn_item.data {
            syn::Data::Struct(s) => Item::Struct(Struct {
                fields: analyze_fields(&s.fields)?,
                generics,
            }),
            syn::Data::Enum(e) => {
                let mut variants = vec![];
                for v in &e.variants {
                    variants.push(Variant {
                        name: v.ident.to_string(),
                        fields: analyze_fields(&v.fields)?,
                    });
                }
                Item::Enum(Enum { variants, generics })
            }
            syn::Data::Union(_) => bail!("Unable to analyze union: {}", syn_item.ident),
        };
        for field in item.fields() {
            let mut field_ty = &field.ty;
            while let Type::Box(ty) | Type::Vec(ty) | Type::Option(ty) = field_ty {
                field_ty = ty;
            }
            if let Type::Abstract(name) = field_ty {
                items.insert(name.clone(), Item::Abstract);
            }
        }
        items.insert(name, item);
    }

    let mut generics = BTreeMap::<_, BTreeSet<String>>::new();
    for item in items.values() {
        for ig in item.generics() {
            generics
                .entry(ig.name.clone())
                .or_default()
                .extend(ig.bounds.clone());
        }
    }

    for item in items.values() {
        validate_fields(&items, item.fields())?
    }

    Ok(Ir { items, generics })
}

fn validate_fields<'a, I>(items: &BTreeMap<String, Item>, fields: I) -> Result<()>
where
    I: IntoIterator<Item = &'a Field>,
{
    for f in fields {
        match &f.ty {
            Type::Local(s) if !items.contains_key(s) => {
                bail!(
                    "Unable to analyze non built-in type that is not defined in input: {}",
                    s
                );
            }
            _ => (),
        }
    }
    Ok(())
}

fn analyze_fields(fields: &syn::Fields) -> Result<Vec<Field>> {
    fields
        .iter()
        .map(|f| {
            Ok(Field {
                name: f.ident.as_ref().map(|id| id.to_string()),
                ty: analyze_type(&f.ty)?,
            })
        })
        .collect()
}

fn analyze_generics(generics: &syn::Generics) -> Result<Vec<ItemGeneric>> {
    let mut out = vec![];
    for g in generics.params.iter() {
        match g {
            syn::GenericParam::Type(syn::TypeParam { ident, bounds, .. }) => {
                let name = ident.to_string();
                let bounds = analyze_generic_bounds(bounds)?;
                // Generic parameter names that end in '2' conflict with the
                // folder's name generation.
                if name.ends_with('2') {
                    bail!("Generic parameters whose name ends in '2' conflict with folder's naming scheme: {}", name);
                }
                out.push(ItemGeneric { name, bounds });
            }
            _ => {
                bail!(
                    "Unable to analyze non-type generic parameter: {}",
                    g.to_token_stream()
                )
            }
        }
    }
    Ok(out)
}

fn analyze_generic_bounds<'a, I>(bounds: I) -> Result<Vec<String>>
where
    I: IntoIterator<Item = &'a syn::TypeParamBound>,
{
    let mut out = vec![];
    for b in bounds {
        match b {
            syn::TypeParamBound::Trait(t) if t.path.segments.len() != 1 => {
                bail!(
                    "Unable to analyze trait bound with more than one path segment: {}",
                    b.to_token_stream()
                )
            }
            syn::TypeParamBound::Trait(t) => out.push(t.path.segments[0].ident.to_string()),
            _ => bail!("Unable to analyze non-trait bound: {}", b.to_token_stream()),
        }
    }
    Ok(out)
}

fn analyze_type(ty: &syn::Type) -> Result<Type> {
    match ty {
        syn::Type::Path(syn::TypePath { qself: None, path }) => match path.segments.len() {
            2 => {
                let name = path.segments.iter().map(|s| s.ident.to_string()).join("::");
                Ok(Type::Abstract(name))
            }
            1 => {
                let segment = path.segments.last().unwrap();
                let segment_name = segment.ident.to_string();

                let container = |construct_ty: fn(Box<Type>) -> Type| match &segment.arguments {
                    syn::PathArguments::AngleBracketed(args) if args.args.len() == 1 => {
                        match args.args.last().unwrap() {
                            syn::GenericArgument::Type(ty) => {
                                let inner = Box::new(analyze_type(ty)?);
                                Ok(construct_ty(inner))
                            }
                            _ => bail!("Container type argument is not a basic (i.e., non-lifetime, non-constraint) type argument: {}", ty.into_token_stream()),
                        }
                    }
                    syn::PathArguments::AngleBracketed(_) => bail!(
                        "Container type does not have exactly one type argument: {}",
                        ty.into_token_stream()
                    ),
                    syn::PathArguments::Parenthesized(_) => bail!(
                        "Container type has unexpected parenthesized type arguments: {}",
                        ty.into_token_stream()
                    ),
                    syn::PathArguments::None => bail!(
                        "Container type is missing type argument: {}",
                        ty.into_token_stream()
                    ),
                };

                match &*segment_name {
                    "bool" | "usize" | "u8" | "u16" | "u32" | "u64" | "isize" | "i8" | "i16"
                    | "i32" | "i64" | "f32" | "f64" | "char" | "String" | "PathBuf" => {
                        match segment.arguments {
                            syn::PathArguments::None => Ok(Type::Primitive),
                            _ => bail!(
                                "Primitive type had unexpected arguments: {}",
                                ty.into_token_stream()
                            ),
                        }
                    }
                    "Vec" => container(Type::Vec),
                    "Option" => container(Type::Option),
                    "Box" => container(Type::Box),
                    "BTreeMap" => match &segment.arguments {
                        syn::PathArguments::None => bail!("Map type missing arguments"),
                        syn::PathArguments::AngleBracketed(args) if args.args.len() == 2 => {
                            let key = match &args.args[0] {
                                syn::GenericArgument::Type(t) => t,
                                _ => bail!("Invalid argument to map container, should be a Type"),
                            };
                            let value = match &args.args[1] {
                                syn::GenericArgument::Type(t) => t,
                                _ => bail!("Invalid argument to map container, should be a Type"),
                            };
                            Ok(Type::Map {
                                key: Box::new(analyze_type(key)?),
                                value: Box::new(analyze_type(value)?),
                            })
                        }
                        &syn::PathArguments::AngleBracketed(_) => {
                            bail!("wrong type of arguments for map container")
                        }
                        syn::PathArguments::Parenthesized(_) => {
                            bail!("wrong type of arguments for map container")
                        }
                    },
                    _ => Ok(Type::Local(segment_name)),
                }
            }
            _ => {
                bail!(
                    "Unable to analyze type path with more than two components: '{}'",
                    path.into_token_stream()
                )
            }
        },
        _ => bail!(
            "Unable to analyze non-struct, non-enum type: {}",
            ty.into_token_stream()
        ),
    }
}