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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
use lalrpop_util::lalrpop_mod;

lalrpop_mod!(#[allow(clippy::all, dead_code, unused_imports)] pub aidl);

#[cfg(test)]
mod tests {
    use crate::diagnostic::DiagnosticKind;
    use crate::rules;
    use anyhow::Result;

    fn lookup(input: &str) -> line_col::LineColLookup {
        line_col::LineColLookup::new(input)
    }

    // Replace ranges into "..." and check parse output via insta Ron snapshot
    macro_rules! assert_parser {
        ($input:ident, $parser:expr) => {
            let mut diagnostics = Vec::new();
            let lookup = lookup($input);
            let res = $parser.parse(&lookup, &mut diagnostics, $input)?;
            ::insta::assert_ron_snapshot!(res, {
                ".**.symbol_range" => "...",
                ".**.full_range" => "...",
                ".**.value_range" => "...",
                ".**.oneway_range" => "...",
            });
            assert_eq!(diagnostics, &[]);
        };

        ($input:ident, $parser:expr, $diag:expr) => {
            let lookup = lookup($input);
            let res = $parser.parse(&lookup, $diag, $input)?;
            ::insta::assert_ron_snapshot!(res, {
                ".**.symbol_range" => "...",
                ".**.full_range" => "...",
                ".**.value_range" => "...",
                ".**.oneway_range" => "...",
            });
        };
    }

    macro_rules! assert_diagnostics {
        ($diag:expr, @$snapshot:literal) => {
            ::insta::assert_ron_snapshot!($diag, {
                ".**.range" => "...",
            }, @$snapshot);
        };
    }

    #[test]
    fn test_aidl() -> Result<()> {
        let input = r#"package x.y.z;
            import a.b.c;
            interface MyInterface {}
        "#;
        assert_parser!(input, rules::aidl::OptAidlParser::new());

        Ok(())
    }

    #[test]
    fn test_aidl_with_unrecovered_error() -> Result<()> {
        use crate::diagnostic::ParseError;

        let input = "wrong, wrong and wrong!";
        let lookup = lookup(input);
        let res = rules::aidl::OptAidlParser::new().parse(&lookup, &mut Vec::new(), input);

        assert!(matches!(res, Err(ParseError::InvalidToken { .. })));

        Ok(())
    }

    #[test]
    fn test_aidl_with_recovered_error() -> Result<()> {
        let input = r#"package x.y.z;
               import a.b.c;
               oops_interface MyInterface {}
           "#;
        let mut diagnostics = Vec::new();
        assert_parser!(input, rules::aidl::OptAidlParser::new(), &mut diagnostics);

        assert_diagnostics!(diagnostics, @r###"
        [
          Diagnostic(
            kind: Error,
            range: "...",
            message: "Invalid item - Unrecognized token `oops_interface`\nExpected one of ANNOTATION, ENUM, IMPORT, INTERFACE or PARCELABLE",
            context_message: Some("unrecognized token"),
            hint: None,
            related_infos: [],
          ),
        ]
        "###);

        Ok(())
    }

    #[test]
    fn test_package1() -> Result<()> {
        let input = "package x ;";
        assert_parser!(input, rules::aidl::PackageParser::new());

        Ok(())
    }

    #[test]
    fn test_package2() -> Result<()> {
        let input = "package x.y.z;";
        assert_parser!(input, rules::aidl::PackageParser::new());

        Ok(())
    }

    #[test]
    fn test_import() -> Result<()> {
        let input = "import x.y.z;";
        assert_parser!(input, rules::aidl::ImportParser::new());

        Ok(())
    }

    #[test]
    fn test_declared_parcelable() -> Result<()> {
        let mut diagnostics = Vec::new();

        let input = "parcelable X;";
        assert_parser!(
            input,
            rules::aidl::DeclaredParcelableParser::new(),
            &mut diagnostics
        );
        let input = "parcelable any.pkg.Y;";
        assert_parser!(
            input,
            rules::aidl::DeclaredParcelableParser::new(),
            &mut diagnostics
        );
        let input = "@Annotation1 @Annotation2\nparcelable any.pkg.Y;";
        assert_parser!(
            input,
            rules::aidl::DeclaredParcelableParser::new(),
            &mut diagnostics
        );

        // Warning generated because it is recommended to define parcelables in AIDL
        assert_eq!(diagnostics.len(), 3);
        assert_eq!(diagnostics[0].kind, DiagnosticKind::Warning);
        assert_eq!(diagnostics[1].kind, DiagnosticKind::Warning);
        assert_eq!(diagnostics[2].kind, DiagnosticKind::Warning);

        Ok(())
    }

    #[test]
    fn test_interface() -> Result<()> {
        let input = r#"interface Potato {
            /**
             * const1 documentation
             */
            const int const1 = 1;
    
            /**
             * method1 documentation
             */
            String method1();
    
            const String const2 = "two";
            int method2();
        }"#;
        assert_parser!(input, rules::aidl::InterfaceParser::new());

        Ok(())
    }

    #[test]
    fn test_oneway_interface() -> Result<()> {
        let input = r#"oneway interface OneWayInterface {}"#;
        assert_parser!(input, rules::aidl::InterfaceParser::new());

        Ok(())
    }

    #[test]
    fn test_interface_with_annotation() -> Result<()> {
        let input = r#"@InterfaceAnnotation1
            @InterfaceAnnotation2 interface Potato {
            }"#;
        assert_parser!(input, rules::aidl::InterfaceParser::new());

        Ok(())
    }

    #[test]
    fn test_interface_with_javadoc() -> Result<()> {
        let input = r#"
            /** Documentation before */
            /** Interface documentation */
            /* Comment after */
            // Line comment after
            interface Potato {
            }"#;
        assert_parser!(input, rules::aidl::InterfaceParser::new());

        Ok(())
    }

    #[test]
    fn test_interface_with_errors() -> Result<()> {
        let input = r#"interface Potato {
            String method1();
            int method2();
            int oops_not_a_valid_method;
            const String const2 = 123;
            const oops_not_a_valid_const;
        }"#;
        let mut diagnostics = Vec::new();
        assert_parser!(input, rules::aidl::InterfaceParser::new(), &mut diagnostics);

        assert_diagnostics!(diagnostics, @r###"
        [
          Diagnostic(
            kind: Error,
            range: "...",
            message: "Invalid interface element - Unrecognized token `;`\nExpected one of \"(\"",
            context_message: Some("unrecognized token"),
            hint: None,
            related_infos: [],
          ),
          Diagnostic(
            kind: Error,
            range: "...",
            message: "Invalid interface element - Unrecognized token `;`\nExpected one of \")\", \",\", \".\", \">\" or IDENT",
            context_message: Some("unrecognized token"),
            hint: None,
            related_infos: [],
          ),
        ]
        "###);

        Ok(())
    }

    #[test]
    fn test_parcelable() -> Result<()> {
        let input = r#"parcelable Tomato {
            /**
             * member1 documentation
             */
            int member1;
    
            String member2; // inline comment
        }"#;
        assert_parser!(input, rules::aidl::ParcelableParser::new());

        Ok(())
    }

    #[test]
    fn test_parcelable_with_javadoc() -> Result<()> {
        let input = r#"
            /** Parcelable documentation */
            parcelable Tomato {}"#;
        assert_parser!(input, rules::aidl::ParcelableParser::new());

        Ok(())
    }

    #[test]
    fn test_parcelable_with_errors() -> Result<()> {
        let input = r#"parcelable Tomato {
            int member1;
            wrongmember3;
            String member3;
        }"#;
        let mut diagnostics = Vec::new();
        assert_parser!(
            input,
            rules::aidl::ParcelableParser::new(),
            &mut diagnostics
        );
        assert_diagnostics!(diagnostics, @r###"
        [
          Diagnostic(
            kind: Error,
            range: "...",
            message: "Invalid member - Unrecognized token `;`\nExpected one of \",\", \".\", \">\" or IDENT",
            context_message: Some("unrecognized token"),
            hint: None,
            related_infos: [],
          ),
        ]
        "###);

        Ok(())
    }

    #[test]
    fn test_enum() -> Result<()> {
        let input = r#"enum Paprika {
                /**
                 * element1 documentation
                 */
                ELEMENT1 = 3,
    
                ELEMENT2 = "quattro",
                ELEMENT3
            }"#;
        assert_parser!(input, rules::aidl::EnumParser::new());

        Ok(())
    }

    #[test]
    fn test_enum_with_javadoc() -> Result<()> {
        let input = r#"
            /** Enum documentation */
            enum Tomato {
                /** ELEMENT1 documentation */
                ELEMENT1,
                ELEMENT2,
                /** ELEMENT3 documentation */
                ELEMENT3,
            }"#;
        assert_parser!(input, rules::aidl::EnumParser::new());

        Ok(())
    }

    #[test]
    fn test_enum_with_errors() -> Result<()> {
        let input = r#"enum Paprika {
                ELEMENT1 = 3,
                ELEMENT2 == "quattro",
                ELEMENT3,
                0843
            }"#;
        let mut diagnostics = Vec::new();
        assert_parser!(input, rules::aidl::EnumParser::new(), &mut diagnostics);
        assert_diagnostics!(diagnostics, @r###"
        [
          Diagnostic(
            kind: Error,
            range: "...",
            message: "Invalid enum element - Unrecognized token `=`\nExpected one of \"{\", BOOLEAN, FLOAT or QUOTED_STRING",
            context_message: Some("unrecognized token"),
            hint: None,
            related_infos: [],
          ),
          Diagnostic(
            kind: Error,
            range: "...",
            message: "Invalid enum element - Unrecognized token `0843`\nExpected one of \"}\" or IDENT",
            context_message: Some("unrecognized token"),
            hint: None,
            related_infos: [],
          ),
        ]
        "###);

        Ok(())
    }

    #[test]
    fn test_enum_with_trailing_comma() -> Result<()> {
        let input = r#"enum Paprika {
                ELEMENT1,
                ELEMENT2,
            }"#;
        assert_parser!(input, rules::aidl::EnumParser::new());

        Ok(())
    }

    #[test]
    fn test_method_without_arg() -> Result<()> {
        let input = "TypeName myMethod() ;";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_with_1_arg() -> Result<()> {
        let input = "TypeName myMethod(ArgType arg) ;";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_with_3_args() -> Result<()> {
        let input = "TypeName myMethod(ArgType1, ArgType2 arg2, ArgType3) ;";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_oneway() -> Result<()> {
        let input = "oneway TypeName myMethod();";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_with_value() -> Result<()> {
        let input = "TypeName myMethod() = 123;";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_with_invalid_value() -> Result<()> {
        let input = "TypeName myMethod() = 12.3;";
        assert!(rules::aidl::MethodParser::new()
            .parse(&lookup(input), &mut Vec::new(), input)
            .is_err());

        Ok(())
    }

    #[test]
    fn test_method_with_annotation() -> Result<()> {
        let input = "@AnnotationName void myMethod();";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_with_javadoc() -> Result<()> {
        let input = "/** Method documentation */ void myMethod() = 123;";
        assert_parser!(input, rules::aidl::MethodParser::new());

        Ok(())
    }

    #[test]
    fn test_method_arg_with_name() -> Result<()> {
        let input = "TypeName albert";
        assert_parser!(input, rules::aidl::ArgParser::new());

        Ok(())
    }

    #[test]
    fn test_method_arg_with_direction() -> Result<()> {
        let input = "in TypeName";
        assert_parser!(input, rules::aidl::ArgParser::new());

        Ok(())
    }

    #[test]
    fn test_method_arg_with_direction_and_name() -> Result<()> {
        let input = "out TypeName roger";
        assert_parser!(input, rules::aidl::ArgParser::new());

        Ok(())
    }

    #[test]
    fn test_method_arg_with_annotations() -> Result<()> {
        let input = r#"@Annotation1
            @Annotation2(AnnotationParam ) TypeName albert"#;
        assert_parser!(input, rules::aidl::ArgParser::new());

        Ok(())
    }

    #[test]
    fn test_method_arg_with_javadoc() -> Result<()> {
        let input = "/** Arg documentation */ TypeName albert";
        assert_parser!(input, rules::aidl::ArgParser::new());

        Ok(())
    }

    #[test]
    fn test_member() -> Result<()> {
        let input = "TypeName memberName ;";
        assert_parser!(input, rules::aidl::MemberParser::new());
        Ok(())
    }

    #[test]
    fn test_member_with_value() -> Result<()> {
        let input = "TypeName memberName = \"member value\";";
        assert_parser!(input, rules::aidl::MemberParser::new());

        Ok(())
    }

    #[test]
    fn test_member_with_javadoc() -> Result<()> {
        let input = r#"/**
             * Member documentation
             */
            TypeName memberName;"#;
        assert_parser!(input, rules::aidl::MemberParser::new());

        Ok(())
    }

    #[test]
    fn test_member_with_annotation() -> Result<()> {
        let input = "@AnnotationName TypeName memberName = \"member value\";";
        assert_parser!(input, rules::aidl::MemberParser::new());

        Ok(())
    }

    #[test]
    fn test_const_num() -> Result<()> {
        let input = "const int CONST_NAME = 123 ;";
        assert_parser!(input, rules::aidl::ConstParser::new());

        Ok(())
    }

    #[test]
    fn test_const_string() -> Result<()> {
        let input = "const TypeName CONST_NAME = \"const value\";";
        assert_parser!(input, rules::aidl::ConstParser::new());

        Ok(())
    }

    #[test]
    fn test_const_with_javadoc() -> Result<()> {
        let input = r#"/**
            * Const documentation
            */
           const TypeName CONST_NAME = 123;"#;
        assert_parser!(input, rules::aidl::ConstParser::new());

        Ok(())
    }

    #[test]
    fn test_const_with_annotation() -> Result<()> {
        let input = "@AnnotationName const TypeName CONST_NAME = 123;";
        assert_parser!(input, rules::aidl::ConstParser::new());

        Ok(())
    }

    #[test]
    fn test_type_primitive1() -> Result<()> {
        let input = "double";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_primitive2() -> Result<()> {
        let input = "doublegum";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_custom() -> Result<()> {
        let input = "TypeName";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_custom_with_namespace() -> Result<()> {
        let input = "com.example.TypeName";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_array() -> Result<()> {
        let input = "float []";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_array_bidirectional() -> Result<()> {
        let input = "int [] []";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_list() -> Result<()> {
        let input = "List <MyObject >";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_list_non_generic() -> Result<()> {
        let input = "List";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_list_invalid() -> Result<()> {
        let input = "List<A, B>";
        assert!(rules::aidl::ValueParser::new()
            .parse(&lookup(input), &mut Vec::new(), input)
            .is_err());

        Ok(())
    }

    #[test]
    fn test_type_map() -> Result<()> {
        let input = "Map<Key,List<V>>";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_map_non_generic() -> Result<()> {
        let input = "Map";
        assert_parser!(input, rules::aidl::TypeParser::new());

        Ok(())
    }

    #[test]
    fn test_type_map_invalid() -> Result<()> {
        let input = "Map<A>";
        assert!(rules::aidl::ValueParser::new()
            .parse(&lookup(input), &mut Vec::new(), input)
            .is_err());

        let input = "Map<A,B,C>";
        assert!(rules::aidl::ValueParser::new()
            .parse(&lookup(input), &mut Vec::new(), input)
            .is_err());

        Ok(())
    }

    #[test]
    fn test_value() -> Result<()> {
        // Numbers
        for input in ["12", "-12", "-0.12", "-.12", "-.12f"].into_iter() {
            assert_eq!(
                rules::aidl::ValueParser::new().parse(&lookup(input), &mut Vec::new(), input)?,
                input
            );
        }

        // Invalid numbers
        for input in ["-.", "--12", "0..2", "0.2y"].into_iter() {
            assert!(rules::aidl::ValueParser::new()
                .parse(&lookup(input), &mut Vec::new(), input)
                .is_err());
        }

        // Strings
        for input in ["\"hello\"", "\"\"", "\"\t\""].into_iter() {
            assert_eq!(
                rules::aidl::ValueParser::new().parse(&lookup(input), &mut Vec::new(), input)?,
                input
            );
        }

        // Invalid strings
        for input in ["\"\"\""].into_iter() {
            assert!(rules::aidl::ValueParser::new()
                .parse(&lookup(input), &mut Vec::new(), input)
                .is_err());
        }

        // Empty objects
        for input in ["{}", "{ }", "{      }"].into_iter() {
            assert_eq!(
                rules::aidl::ValueParser::new().parse(&lookup(input), &mut Vec::new(), input)?,
                "{}"
            );
        }

        // Non-empty objects
        for input in ["{\"hello{<\"}", "{1}", "{1, 2}", "{1, 2, 3, }"].into_iter() {
            assert_eq!(
                rules::aidl::ValueParser::new().parse(&lookup(input), &mut Vec::new(), input)?,
                "{...}"
            );
        }

        // Invalid objects
        for input in ["{\"hello{<\"", "{1sfewf}", "{1, 2, 3,, }"].into_iter() {
            assert!(rules::aidl::ValueParser::new()
                .parse(&lookup(input), &mut Vec::new(), input)
                .is_err());
        }

        Ok(())
    }

    #[test]
    fn test_annotation1() -> Result<()> {
        let input = "@AnnotationName";
        assert_parser!(input, rules::aidl::OptAnnotationParser::new());

        Ok(())
    }

    #[test]
    fn test_annotation2() -> Result<()> {
        let input = "@AnnotationName()";
        assert_parser!(input, rules::aidl::OptAnnotationParser::new());

        Ok(())
    }

    #[test]
    fn test_annotation3() -> Result<()> {
        let input = "@AnnotationName( Hello)";
        assert_parser!(input, rules::aidl::OptAnnotationParser::new());

        Ok(())
    }

    #[test]
    fn test_annotation4() -> Result<()> {
        let input = "@AnnotationName(Hello=\"World\")";
        assert_parser!(input, rules::aidl::OptAnnotationParser::new());

        Ok(())
    }

    #[test]
    fn test_annotation5() -> Result<()> {
        let mut settings = insta::Settings::clone_current();
        settings.set_sort_maps(true);
        settings.bind_to_thread();

        let input = "@AnnotationName(Hello=\"World\", Hi, Servus= 3 )";
        assert_parser!(input, rules::aidl::OptAnnotationParser::new());

        Ok(())
    }

    #[test]
    fn test_reserved_keywords() -> Result<()> {
        let input = "package a.for.b;";
        assert!(rules::aidl::PackageParser::new()
            .parse(&lookup(input), &mut Vec::new(), input)
            .is_err());

        Ok(())
    }
}