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
#![cfg_attr(feature = "nightly", feature(proc_macro_diagnostic))]

extern crate proc_macro;

use proc_macro2::{Literal, TokenStream};
use quote::quote;
use std::collections::{hash_map::Entry, HashMap};
use syn::parse::{self, Parse, ParseStream};
use syn::{braced, parse_macro_input, token, Ident, LitStr, Token};

struct FileTree(Vec<FileNode>);

struct FileNode {
    name: Ident,
    path: String,
    children: Option<FileTree>,
}

impl Parse for FileNode {
    fn parse(input: ParseStream) -> parse::Result<FileNode> {
        let name = input.parse()?;
        input.parse::<Token![:]>()?;
        let path = input.parse::<LitStr>()?.value();
        let children = if input.peek(token::Brace) {
            let tree;
            braced!(tree in input);
            Some(tree.parse()?)
        } else {
            None
        };

        Ok(FileNode {
            name,
            path,
            children,
        })
    }
}

impl Parse for FileTree {
    fn parse(input: ParseStream) -> parse::Result<FileTree> {
        let nodes = input.parse_terminated::<_, Token![,]>(FileNode::parse)?;
        Ok(FileTree(nodes.into_iter().collect()))
    }
}

impl FileTree {
    /// Checks for duplicates at each layer of the tree.
    fn validate(&self) {
        // Build up a map of names to spans for each node
        let mut names: HashMap<String, proc_macro::Span> = HashMap::new();
        for node in &self.0 {
            let span = node.name.span().unwrap();
            let name = node.name.to_string();

            match names.entry(name) {
                Entry::Occupied(entry) => {
                    // If a collision is found, report it
                    #[cfg(feature = "nightly")]
                    {
                        span.error(format!(
                            "Node named `{}` is a duplicate of a previous node",
                            node.name
                        ))
                        .span_note(
                            entry.get().clone(),
                            format!("Duplicate found here"),
                        )
                        .emit();
                    }
                    #[cfg(not(feature = "nightly"))]
                    {
                        panic!(
                            "Node named `{}` at {:?} is a duplicate of a \
                             previous node",
                            node.name,
                            entry.get(),
                        );
                    }
                },
                Entry::Vacant(entry) => {
                    entry.insert(span);
                },
            };
        }

        // Recursively validate all children
        for node in &self.0 {
            if let Some(ref children) = node.children {
                children.validate();
            }
        }
    }
}

impl FileNode {
    fn expand(self, parent: Option<String>) -> TokenStream {
        let FileNode {
            name,
            path,
            children,
        } = self;

        let fn_name = Ident::new(&name.to_string(), name.span());

        let path = match parent {
            Some(mut parent) => {
                // Construct the next segment of the path
                // Using '/' is okay here since it's supported on all platforms
                parent.push('/');
                parent.push_str(&path);
                parent
            },
            // This is the first segment, so just use path unaltered
            None => path,
        };
        let fs_name = Literal::string(&path);

        let mut expanded = quote! {
            pub fn #fn_name() -> &'static std::path::Path {
                std::path::Path::new(#fs_name)
            }
        };

        if let Some(children) = children {
            let children = children
                .0
                .into_iter()
                .map(|child| child.expand(Some(path.to_string())));
            expanded.extend(quote! {
                pub mod #name {
                    #(#children)*
                }
            })
        }

        expanded
    }
}

#[proc_macro]
pub fn directree(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let tree = parse_macro_input!(input as FileTree);
    tree.validate();

    let mut expanded = TokenStream::new();
    for node in tree.0 {
        expanded.extend(node.expand(None));
    }
    expanded.into()
}