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
use crate::ast::*;
use regex::{Captures, Regex};
use std::collections::HashMap;

enum Context {
    None,
    Struct(String),
    Enum(String),
}

pub fn process<F>(
    ast: &Ast,
    separator: &str,
    variables: HashMap<String, String>,
    _on_import: F,
) -> Result<String, String>
where
    F: FnMut(&str) -> Result<String, String>,
{
    let impls = get_impl_targets(ast);
    validate_type_impls(ast, &impls)?;
    let mut output = String::default();
    for code in &ast.injects {
        process_code(&Context::None, code, ast, &variables, &mut output)?;
        output.push_str(separator);
    }
    for external in &ast.externs {
        process_extern(external, ast, separator, &mut output)?;
    }
    for enum_ in &ast.enums {
        process_enum(enum_, ast, separator, &mut output)?;
    }
    for struct_ in &ast.structs {
        process_struct(struct_, ast, separator, &mut output)?;
    }
    for replace in &ast.replacements {
        output = process_replacement(replace, &output, ast, &variables);
    }
    Ok(output)
}

fn get_impl_targets(ast: &Ast) -> Vec<(String, AstImplementationTarget)> {
    ast.implementations
        .iter()
        .map(|i| (i.name.to_owned(), i.target.clone()))
        .collect::<Vec<_>>()
}

fn validate_type_impls(
    ast: &Ast,
    impl_targets: &Vec<(String, AstImplementationTarget)>,
) -> Result<(), String> {
    for external in &ast.externs {
        for type_ in &external.types {
            for (implementation, _) in &external.implementations {
                if !impl_targets.iter().any(|(n, _)| implementation == n) {
                    return Err(format!(
                        "Trying to apply non-existing trait `{}` for external type `{}`",
                        implementation, type_
                    ));
                }
            }
        }
    }
    for struct_ in &ast.structs {
        for (tag, _) in &struct_.tags {
            if !impl_targets
                .iter()
                .any(|(n, t)| tag == n && t.is_valid(AstImplementationTarget::Struct))
            {
                return Err(format!(
                    "Trying to apply non-existing or non-struct trait `{}` for struct `{}`",
                    tag, struct_.name
                ));
            }
        }
    }
    for enum_ in &ast.enums {
        for (tag, _) in &enum_.tags {
            if !impl_targets
                .iter()
                .any(|(n, t)| tag == n && t.is_valid(AstImplementationTarget::Enum))
            {
                return Err(format!(
                    "Trying to apply non-existing or non-enum trait `{}` for enum `{}`",
                    tag, enum_.name
                ));
            }
        }
    }
    Ok(())
}

fn process_code(
    context: &Context,
    code: &AstCode,
    ast: &Ast,
    variables: &HashMap<String, String>,
    output: &mut String,
) -> Result<(), String> {
    for chunk in &code.0 {
        match chunk {
            AstCodeChunk::Content(content) => output.push_str(&content),
            AstCodeChunk::Variable(variable) => {
                if let Some(found) = variables.get(variable) {
                    output.push_str(found);
                } else {
                    return Err(format!(
                        "Trying to place non-existing variable `{}`",
                        variable
                    ));
                }
            }
            AstCodeChunk::For(for_) => process_code_for(context, for_, ast, variables, output)?,
            AstCodeChunk::None => {}
        }
    }
    Ok(())
}

fn process_code_for(
    context: &Context,
    code: &AstCodeFor,
    ast: &Ast,
    variables: &HashMap<String, String>,
    output: &mut String,
) -> Result<(), String> {
    if code.variables.is_empty() {
        unreachable!();
    }
    let iterables = get_container_iterables(context, &code.container, ast, variables)?;
    let count = iterables.len() / code.variables.len();
    for i in 0..count {
        let start = i * code.variables.len();
        let end = start + code.variables.len();
        let values = &iterables[start..end];
        let mut variables = variables.clone();
        for (name, value) in code.variables.iter().zip(values.iter()) {
            variables.insert(name.to_owned(), value.to_owned());
        }
        process_code(context, &code.code, ast, &variables, output)?;
    }
    Ok(())
}

fn get_container_iterables(
    context: &Context,
    container: &AstIn,
    ast: &Ast,
    variables: &HashMap<String, String>,
) -> Result<Vec<String>, String> {
    match container {
        AstIn::Fields => match context {
            Context::Struct(name) => {
                let s = ast.structs.iter().find(|s| &s.name == name).unwrap();
                Ok(s.fields
                    .iter()
                    .flat_map(|(n, t)| vec![n.to_owned(), t.to_string()])
                    .collect::<Vec<_>>())
            }
            Context::Enum(name) => {
                let e = ast.enums.iter().find(|e| &e.name == name).unwrap();
                Ok(e.fields.clone())
            }
            Context::None => Err("Trying to iterate over fields of no context".to_owned()),
        },
        AstIn::Variable(variable) => {
            if let Some(found) = variables.get(variable) {
                Ok(found.split("|").map(str::to_owned).collect::<Vec<_>>())
            } else {
                Err(format!(
                    "Trying to iterate over non-existing variable `{}`",
                    variable
                ))
            }
        }
        AstIn::None => Err("There is no container specified to iterate over".to_owned()),
    }
}

fn process_replacement(
    replace: &AstReplace,
    input: &str,
    ast: &Ast,
    variables: &HashMap<String, String>,
) -> String {
    let pattern = Regex::new(&replace.pattern).expect("Could not parse replacement pattern");
    println!("* Replace pattern: `{:?}`", pattern);
    pattern
        .replace_all(input, |captures: &Captures| {
            let mut variables = variables.clone();
            for i in 0..captures.len() {
                if let Some(capture) = captures.get(i) {
                    variables.insert(format!("_{}", i), capture.as_str().to_owned());
                }
            }
            let mut output = String::new();
            process_code(
                &Context::None,
                &replace.template,
                ast,
                &variables,
                &mut output,
            )
            .expect("Could not process replacement template code");
            output
        })
        .to_owned()
        .into()
}

fn process_extern(
    external: &AstExtern,
    ast: &Ast,
    separator: &str,
    output: &mut String,
) -> Result<(), String> {
    for type_ in &external.types {
        let mut variables = HashMap::new();
        variables.insert("TYPENAME".to_owned(), type_.to_owned());
        for (_, code) in &external.implementations {
            process_code(&Context::None, code, ast, &variables, output)?;
            output.push_str(separator);
        }
    }
    Ok(())
}

fn process_enum(
    enum_: &AstEnum,
    ast: &Ast,
    separator: &str,
    output: &mut String,
) -> Result<(), String> {
    let context = Context::Enum(enum_.name.to_owned());
    for (name, params) in &enum_.tags {
        let mut variables = HashMap::new();
        variables.insert("TYPENAME".to_owned(), enum_.name.to_owned());
        for (key, value) in params {
            variables.insert(key.to_owned(), value.to_owned());
        }
        let trait_ = ast
            .implementations
            .iter()
            .find(|i| &i.name == name && i.target == AstImplementationTarget::Enum)
            .unwrap();
        // TODO: where rules validation.
        process_code(&context, &trait_.code, ast, &variables, output)?;
        output.push_str(separator);
    }
    Ok(())
}

fn process_struct(
    struct_: &AstStruct,
    ast: &Ast,
    separator: &str,
    output: &mut String,
) -> Result<(), String> {
    let context = Context::Struct(struct_.name.to_owned());
    for (name, params) in &struct_.tags {
        let mut variables = HashMap::new();
        variables.insert("TYPENAME".to_owned(), struct_.name.to_owned());
        for (key, value) in params {
            variables.insert(key.to_owned(), value.to_owned());
        }
        let trait_ = ast
            .implementations
            .iter()
            .find(|i| &i.name == name && i.target == AstImplementationTarget::Struct)
            .unwrap();
        // TODO: where rules validation.
        process_code(&context, &trait_.code, ast, &variables, output)?;
        output.push_str(separator);
    }
    Ok(())
}