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
362
363
364
365
366
367
368
use std::{
    collections::{hash_map, HashMap, HashSet},
    fmt::Debug,
    hash::Hash,
    io::Read,
    path::{Path, PathBuf},
};

use crate::diagnostic::{Diagnostic, RelatedInfo};
use crate::rules;
use crate::{ast, diagnostic::DiagnosticKind};

/// A parser instance which receives the individual AIDL files via
/// Parser::add_content() or Parser::add_file(). Once all the files
/// have been added, call Parser::parser() to trigger the validation
/// and access the results.
/// It is also possible to replace or remote a content with a given
/// ID and re-trigger the parsing.
///
/// Example:
/// ```
/// use aidl_parser::{Parser, ParseFileResult};
///
/// let mut parser = Parser::new();
///
/// // Add files via ID + content
/// parser.add_content(1, "<content of AIDL file #1>");
/// parser.add_content(2, "<content of AIDL file #2>");
/// parser.add_content(3, "<content of AIDL file #3>");
///
/// // Parse and get results
/// let results = parser.parse();
///
/// assert_eq!(results.len(), 3);
/// assert!(results.contains_key(&1));
/// assert!(results.contains_key(&2));
/// assert!(results.contains_key(&3));
///
/// // Add/replace/remote files
/// parser.add_content(2, "<updated content of AIDL file #2>");
/// parser.add_content(4, "<content of AIDL file #4>");
/// parser.add_content(5, "<content of AIDL file #5>");
/// parser.remove_content(1);
///
/// // Parse again and get updated results
/// let results = parser.parse();
///
/// assert_eq!(results.len(), 4);
/// assert!(results.contains_key(&2));
/// assert!(results.contains_key(&3));
/// assert!(results.contains_key(&4));
/// assert!(results.contains_key(&5));
/// ```
pub struct Parser<ID>
where
    ID: Eq + Hash + Clone + Debug,
{
    lalrpop_results: HashMap<ID, ParseFileResult<ID>>,
}

/// The parse result of 1 file with its corresponding ID as given via
/// Parser::add_content() or Parser::add_file().
#[derive(Debug, Clone)]
pub struct ParseFileResult<ID>
where
    ID: Eq + Hash + Clone + Debug,
{
    pub id: ID,
    pub file: Option<ast::File>,
    pub diagnostics: Vec<Diagnostic>,
}

impl<ID> Parser<ID>
where
    ID: Eq + Hash + Clone + Debug,
{
    /// Create a new, empty parser
    pub fn new() -> Self {
        Parser {
            lalrpop_results: HashMap::new(),
        }
    }

    /// Add a file content and its key to the parser
    pub fn add_content(&mut self, id: ID, content: &str) {
        let lookup = line_col::LineColLookup::new(content);
        let mut diagnostics = Vec::new();

        let rule_result =
            rules::aidl::OptFileParser::new().parse(&lookup, &mut diagnostics, content);

        let lalrpop_result = match rule_result {
            Ok(file) => ParseFileResult {
                id: id.clone(),
                file,
                diagnostics,
            },
            Err(e) => {
                // Append the parse error to the diagnostics
                if let Some(diagnostic) = Diagnostic::from_parse_error(&lookup, e) {
                    diagnostics.push(diagnostic)
                }

                ParseFileResult {
                    id: id.clone(),
                    file: None,
                    diagnostics,
                }
            }
        };

        self.lalrpop_results.insert(id, lalrpop_result);
    }

    /// Remote the file with the given key
    pub fn remove_content(&mut self, id: ID) {
        self.lalrpop_results.remove(&id);
    }

    pub fn parse(&self) -> HashMap<ID, ParseFileResult<ID>> {
        let keys = self.collect_item_keys();

        self.lalrpop_results
            .clone()
            .into_iter()
            .map(|(id, mut fr)| {
                let mut file = match fr.file {
                    Some(f) => f,
                    None => return (id, ParseFileResult { file: None, ..fr }),
                };

                let resolved = resolve_types(&mut file, &mut fr.diagnostics);
                check_types(&mut file, &mut fr.diagnostics);
                check_imports(&file.imports, &resolved, &keys, &mut fr.diagnostics);

                // Sort diagnostics by line
                fr.diagnostics.sort_by_key(|d| d.range.start.line_col.0);

                (
                    id,
                    ParseFileResult {
                        file: Some(file),
                        ..fr
                    },
                )
            })
            .collect()
    }

    fn collect_item_keys(&self) -> HashSet<ast::ItemKey> {
        self.lalrpop_results
            .iter()
            .map(|(_, fr)| &fr.file)
            .flatten()
            .map(|f| f.get_key())
            .collect()
    }
}

fn walk_types<F: FnMut(&mut ast::Type)>(file: &mut ast::File, mut f: F) {
    let mut visit_type_helper = |type_: &mut ast::Type| {
        f(type_);
        type_.generic_types.iter_mut().for_each(|t| f(t));
    };

    match file.item {
        ast::Item::Interface(ref mut i) => {
            i.elements.iter_mut().for_each(|el| match el {
                ast::InterfaceElement::Method(m) => {
                    visit_type_helper(&mut m.return_type);
                    m.args.iter_mut().for_each(|arg| {
                        visit_type_helper(&mut arg.arg_type);
                    })
                }
                ast::InterfaceElement::Const(c) => {
                    visit_type_helper(&mut c.const_type);
                }
            });
        }
        ast::Item::Parcelable(ref mut p) => {
            p.members.iter_mut().for_each(|m| {
                visit_type_helper(&mut m.member_type);
            });
        }
        ast::Item::Enum(_) => (),
    }
}

fn resolve_types(file: &mut ast::File, diagnostics: &mut Vec<Diagnostic>) -> HashSet<String> {
    let imports: Vec<String> = file
        .imports
        .iter()
        .map(|i| i.get_qualified_name())
        .collect();

    let mut resolved = HashSet::new();

    walk_types(file, |type_: &mut ast::Type| {
        if type_.kind == ast::TypeKind::Custom && type_.definition.is_none() {
            if let Some(import) = imports
                .iter()
                .find(|i| &type_.name == *i || i.ends_with(&format!(".{}", type_.name)))
            {
                resolved.insert(import.clone());
                type_.definition = Some(import.clone());
            } else {
                diagnostics.push(Diagnostic {
                    kind: DiagnosticKind::Error,
                    range: type_.symbol_range.clone(),
                    message: format!("Unknown type `{}`", type_.name),
                    context_message: Some("unknown type".to_owned()),
                    hint: None,
                    related_infos: Vec::new(),
                });
            }
        }
    });

    resolved
}

fn check_imports(
    imports: &[ast::Import],
    resolved: &HashSet<String>,
    defined: &HashSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    // array of Import -> map of "qualified name" -> Import
    let imports: HashMap<String, &ast::Import> =
        imports.iter().fold(HashMap::new(), |mut map, import| {
            match map.entry(import.get_qualified_name()) {
                hash_map::Entry::Occupied(previous) => {
                    diagnostics.push(Diagnostic {
                        kind: DiagnosticKind::Error,
                        range: import.symbol_range.clone(),
                        message: format!("Duplicated import `{}`", import.get_qualified_name()),
                        context_message: Some("duplicated import".to_owned()),
                        hint: None,
                        related_infos: Vec::from([RelatedInfo {
                            message: "previous location".to_owned(),
                            range: previous.get().symbol_range.clone(),
                        }]),
                    });
                }
                hash_map::Entry::Vacant(v) => {
                    v.insert(import);
                }
            }
            map
        });

    for (qualified_import, import) in imports.into_iter() {
        if !defined.contains(&qualified_import) {
            diagnostics.push(Diagnostic {
                kind: DiagnosticKind::Error,
                range: import.symbol_range.clone(),
                message: format!("Unresolved import `{}`", import.name),
                context_message: Some("unresolved import".to_owned()),
                hint: None,
                related_infos: Vec::new(),
            });
        } else if !resolved.contains(&qualified_import) {
            diagnostics.push(Diagnostic {
                kind: DiagnosticKind::Warning,
                range: import.symbol_range.clone(),
                message: format!("Unused import `{}`", import.name),
                context_message: Some("unused import".to_owned()),
                hint: None,
                related_infos: Vec::new(),
            });
        }
    }
}

// TODO: additional type checks
fn check_types(file: &mut ast::File, _diagnostics: &mut Vec<Diagnostic>) {
    walk_types(file, |type_: &mut ast::Type| match &type_.definition {
        Some(_type_def) if type_.kind == ast::TypeKind::Custom => {
            //println!("Resolved type: {}", type_def);
        }
        _ => (),
    });
}

impl Parser<PathBuf> {
    /// Add a file to the parser and use its path as key
    pub fn add_file<P: AsRef<Path>>(&mut self, path: P) -> std::io::Result<()> {
        let mut file = std::fs::File::open(path.as_ref())?;
        let mut buffer = String::new();
        file.read_to_string(&mut buffer)?;

        self.add_content(PathBuf::from(path.as_ref()), &buffer);
        Ok(())
    }
}

impl<ID> Default for Parser<ID>
where
    ID: Eq + Hash + Clone + Debug,
{
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use anyhow::Result;

    #[test]
    fn test_parse() -> Result<()> {
        let interface_aidl = r#"
            package com.bwa.aidl_test;
        
            import com.bwa.aidl_test.MyEnum;
            import com.bwa.aidl_test.MyEnum;
            import com.bwa.aidl_test.MyEnum;
            import com.bwa.aidl_test.MyParcelable;
            import com.bwa.aidl_test.MyUnexisting;

            interface MyInterface {
                const int MY_CONST = 12;
                /**
                 * Be polite and say hello
                 */
                //String hello(MyEnum e, MyParcelable);
                String servus(MyEnum e, MyWrong);
                String bonjour(MyEnum e, MyUnexisting);
            }
        "#;

        let enum_aidl = r#"
            package com.bwa.aidl_test;
        
            enum MyEnum {
                VALUE1 = 1,
                VALUE2 = 2,
            }
        "#;

        let parcelable_aidl = r#"
            package com.bwa.aidl_test;
        
            parcelable MyParcelable {
                String name;
                byte[] data;
            }
        "#;

        // Parse AIDL files
        let mut parser = Parser::new();
        parser.add_content(0, interface_aidl);
        parser.add_content(1, parcelable_aidl);
        parser.add_content(2, enum_aidl);
        let res = parser.parse();

        // For each file, 1 result
        assert_eq!(res.len(), 3);

        // No error/warning
        println!("...\nDiagnostics 1:\n{:#?}", res[&0].diagnostics);
        println!("...\nDiagnostics 2:\n{:#?}", res[&1].diagnostics);
        println!("...\nDiagnostics 3:\n{:#?}", res[&2].diagnostics);

        Ok(())
    }
}