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
// 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.

//! A basic parser for Rust code.

use std::fs;
use std::path::Path;

use anyhow::{Context, Result};
use syn::{Data, DataEnum, DataStruct, DataUnion, DeriveInput, Item};

/// Parses the module at `path` and any contained submodules.
///
/// Returns [`DeriveInput`]s representing all struct and enum items in the
/// module. This is exactly what a custom derive procedural macro would see,
/// except that we can present information for all types simultaneously.
///

pub fn parse_mod<P>(path: P) -> Result<Vec<DeriveInput>>
where
    P: AsRef<Path>,
{
    let mut out = vec![];
    collect_items(path, &mut out)?;
    Ok(out)
}

fn collect_items<P>(path: P, out: &mut Vec<DeriveInput>) -> Result<()>
where
    P: AsRef<Path>,
{
    let path = path.as_ref();
    let dir = path.parent().expect("missing parent directory");
    let stem = path
        .file_stem()
        .expect("missing file stem")
        .to_str()
        .expect("file stem is not valid UTF-8");

    let src =
        fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))?;
    let file =
        syn::parse_file(&src).with_context(|| format!("Failed to parse {}", path.display()))?;

    for item in file.items {
        match item {
            Item::Mod(item) if item.content.is_none() => {
                let path = match stem {
                    "mod" | "lib" => dir.join(format!("{}.rs", item.ident)),
                    _ => dir.join(format!("{}/{}.rs", stem, item.ident)),
                };
                collect_items(path, out)?;
            }
            Item::Struct(item) => {
                out.push(DeriveInput {
                    ident: item.ident,
                    vis: item.vis,
                    attrs: item.attrs,
                    generics: item.generics,
                    data: Data::Struct(DataStruct {
                        fields: item.fields,
                        struct_token: item.struct_token,
                        semi_token: item.semi_token,
                    }),
                });
            }
            Item::Enum(item) => {
                out.push(DeriveInput {
                    ident: item.ident,
                    vis: item.vis,
                    attrs: item.attrs,
                    generics: item.generics,
                    data: Data::Enum(DataEnum {
                        enum_token: item.enum_token,
                        brace_token: item.brace_token,
                        variants: item.variants,
                    }),
                });
            }
            Item::Union(item) => {
                out.push(DeriveInput {
                    ident: item.ident,
                    vis: item.vis,
                    attrs: item.attrs,
                    generics: item.generics,
                    data: Data::Union(DataUnion {
                        union_token: item.union_token,
                        fields: item.fields,
                    }),
                });
            }
            _ => (),
        }
    }
    Ok(())
}