]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting/tests.rs
Merge #11088
[rust.git] / crates / ide / src / syntax_highlighting / tests.rs
1 use std::time::Instant;
2
3 use expect_test::{expect_file, ExpectFile};
4 use ide_db::SymbolKind;
5 use test_utils::{bench, bench_fixture, skip_slow_tests, AssertLinear};
6
7 use crate::{fixture, FileRange, HlTag, TextRange};
8
9 #[test]
10 fn test_highlighting() {
11     check_highlighting(
12         r#"
13 //- proc_macros: identity, mirror
14 //- minicore: derive, copy
15 //- /main.rs crate:main deps:foo
16 use inner::{self as inner_mod};
17 mod inner {}
18
19 #[allow()]
20 #[rustfmt::skip]
21 #[proc_macros::identity]
22 pub mod ops {
23     #[lang = "fn_once"]
24     pub trait FnOnce<Args> {}
25
26     #[lang = "fn_mut"]
27     pub trait FnMut<Args>: FnOnce<Args> {}
28
29     #[lang = "fn"]
30     pub trait Fn<Args>: FnMut<Args> {}
31 }
32
33 proc_macros::mirror! {
34     {
35         ,i32 :x pub
36         ,i32 :y pub
37     } Foo struct
38 }
39
40 trait Bar where Self: {
41     fn bar(&self) -> i32;
42 }
43
44 impl Bar for Foo where Self: {
45     fn bar(&self) -> i32 {
46         self.x
47     }
48 }
49
50 impl Foo {
51     fn baz(mut self, f: Foo) -> i32 {
52         f.baz(self)
53     }
54
55     fn qux(&mut self) {
56         self.x = 0;
57     }
58
59     fn quop(&self) -> i32 {
60         self.x
61     }
62 }
63
64 use self::FooCopy::{self as BarCopy};
65 #[derive(Copy)]
66 struct FooCopy {
67     x: u32,
68 }
69
70 impl FooCopy {
71     fn baz(self, f: FooCopy) -> u32 {
72         f.baz(self)
73     }
74
75     fn qux(&mut self) {
76         self.x = 0;
77     }
78
79     fn quop(&self) -> u32 {
80         self.x
81     }
82 }
83
84 fn str() {
85     str();
86 }
87
88 fn foo<'a, T>() -> T {
89     foo::<'a, i32>()
90 }
91
92 fn never() -> ! {
93     loop {}
94 }
95
96 fn const_param<const FOO: usize>() -> usize {
97     FOO
98 }
99
100 use ops::Fn;
101 fn baz<F: Fn() -> ()>(f: F) {
102     f()
103 }
104
105 fn foobar() -> impl Copy {}
106
107 fn foo() {
108     let bar = foobar();
109 }
110
111 macro_rules! def_fn {
112     ($($tt:tt)*) => {$($tt)*}
113 }
114
115 def_fn! {
116     fn bar() -> u32 {
117         100
118     }
119 }
120
121 macro_rules! dont_color_me_braces {
122     () => {0}
123 }
124
125 macro_rules! noop {
126     ($expr:expr) => {
127         $expr
128     }
129 }
130
131 macro_rules! keyword_frag {
132     ($type:ty) => ($type)
133 }
134
135 macro with_args($i:ident) {
136     $i
137 }
138
139 macro without_args {
140     ($i:ident) => {
141         $i
142     }
143 }
144
145 // comment
146 fn main() {
147     println!("Hello, {}!", 92);
148     dont_color_me_braces!();
149
150     let mut vec = Vec::new();
151     if true {
152         let x = 92;
153         vec.push(Foo { x, y: 1 });
154     }
155
156     for e in vec {
157         // Do nothing
158     }
159
160     noop!(noop!(1));
161
162     let mut x = 42;
163     x += 1;
164     let y = &mut x;
165     let z = &y;
166
167     let Foo { x: z, y } = Foo { x: z, y };
168
169     y;
170
171     let mut foo = Foo { x, y: x };
172     let foo2 = Foo { x, y: x };
173     foo.quop();
174     foo.qux();
175     foo.baz(foo2);
176
177     let mut copy = FooCopy { x };
178     copy.quop();
179     copy.qux();
180     copy.baz(copy);
181
182     let a = |x| x;
183     let bar = Foo::baz;
184
185     let baz = (-42,);
186     let baz = -baz.0;
187
188     let _ = !true;
189
190     'foo: loop {
191         break 'foo;
192         continue 'foo;
193     }
194 }
195
196 enum Option<T> {
197     Some(T),
198     None,
199 }
200 use Option::*;
201
202 impl<T> Option<T> {
203     fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
204         match other {
205             None => unimplemented!(),
206             Nope => Nope,
207         }
208     }
209 }
210
211 async fn learn_and_sing() {
212     let song = learn_song().await;
213     sing_song(song).await;
214 }
215
216 async fn async_main() {
217     let f1 = learn_and_sing();
218     let f2 = dance();
219     futures::join!(f1, f2);
220 }
221
222 fn use_foo_items() {
223     let bob = foo::Person {
224         name: "Bob",
225         age: foo::consts::NUMBER,
226     };
227
228     let control_flow = foo::identity(foo::ControlFlow::Continue);
229
230     if control_flow.should_die() {
231         foo::die!();
232     }
233 }
234
235 pub enum Bool { True, False }
236
237 impl Bool {
238     pub const fn to_primitive(self) -> bool {
239         matches!(self, Self::True)
240     }
241 }
242 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
243
244 trait Baz {
245     type Qux;
246 }
247
248 fn baz<T>(t: T)
249 where
250     T: Baz,
251     <T as Baz>::Qux: Bar {}
252
253 //- /foo.rs crate:foo
254 pub struct Person {
255     pub name: &'static str,
256     pub age: u8,
257 }
258
259 pub enum ControlFlow {
260     Continue,
261     Die,
262 }
263
264 impl ControlFlow {
265     pub fn should_die(self) -> bool {
266         matches!(self, ControlFlow::Die)
267     }
268 }
269
270 pub fn identity<T>(x: T) -> T { x }
271
272 pub mod consts {
273     pub const NUMBER: i64 = 92;
274 }
275
276 macro_rules! die {
277     () => {
278         panic!();
279     };
280 }
281 "#
282         .trim(),
283         expect_file!["./test_data/highlighting.html"],
284         false,
285     );
286 }
287
288 #[test]
289 fn test_rainbow_highlighting() {
290     check_highlighting(
291         r#"
292 fn main() {
293     let hello = "hello";
294     let x = hello.to_string();
295     let y = hello.to_string();
296
297     let x = "other color please!";
298     let y = x.to_string();
299 }
300
301 fn bar() {
302     let mut hello = "hello";
303 }
304 "#
305         .trim(),
306         expect_file!["./test_data/rainbow_highlighting.html"],
307         true,
308     );
309 }
310
311 #[test]
312 fn benchmark_syntax_highlighting_long_struct() {
313     if skip_slow_tests() {
314         return;
315     }
316
317     let fixture = bench_fixture::big_struct();
318     let (analysis, file_id) = fixture::file(&fixture);
319
320     let hash = {
321         let _pt = bench("syntax highlighting long struct");
322         analysis
323             .highlight(file_id)
324             .unwrap()
325             .iter()
326             .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
327             .count()
328     };
329     assert_eq!(hash, 2001);
330 }
331
332 #[test]
333 fn syntax_highlighting_not_quadratic() {
334     if skip_slow_tests() {
335         return;
336     }
337
338     let mut al = AssertLinear::default();
339     while al.next_round() {
340         for i in 6..=10 {
341             let n = 1 << i;
342
343             let fixture = bench_fixture::big_struct_n(n);
344             let (analysis, file_id) = fixture::file(&fixture);
345
346             let time = Instant::now();
347
348             let hash = analysis
349                 .highlight(file_id)
350                 .unwrap()
351                 .iter()
352                 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
353                 .count();
354             assert!(hash > n as usize);
355
356             let elapsed = time.elapsed();
357             al.sample(n as f64, elapsed.as_millis() as f64);
358         }
359     }
360 }
361
362 #[test]
363 fn benchmark_syntax_highlighting_parser() {
364     if skip_slow_tests() {
365         return;
366     }
367
368     let fixture = bench_fixture::glorious_old_parser();
369     let (analysis, file_id) = fixture::file(&fixture);
370
371     let hash = {
372         let _pt = bench("syntax highlighting parser");
373         analysis
374             .highlight(file_id)
375             .unwrap()
376             .iter()
377             .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
378             .count()
379     };
380     assert_eq!(hash, 1616);
381 }
382
383 #[test]
384 fn test_ranges() {
385     let (analysis, file_id) = fixture::file(
386         r#"
387 #[derive(Clone, Debug)]
388 struct Foo {
389     pub x: i32,
390     pub y: i32,
391 }
392 "#,
393     );
394
395     // The "x"
396     let highlights = &analysis
397         .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
398         .unwrap();
399
400     assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
401 }
402
403 #[test]
404 fn test_flattening() {
405     check_highlighting(
406         r##"
407 fn fixture(ra_fixture: &str) {}
408
409 fn main() {
410     fixture(r#"
411         trait Foo {
412             fn foo() {
413                 println!("2 + 2 = {}", 4);
414             }
415         }"#
416     );
417 }"##
418         .trim(),
419         expect_file!["./test_data/highlight_injection.html"],
420         false,
421     );
422 }
423
424 #[test]
425 fn ranges_sorted() {
426     let (analysis, file_id) = fixture::file(
427         r#"
428 #[foo(bar = "bar")]
429 macro_rules! test {}
430 }"#
431         .trim(),
432     );
433     let _ = analysis.highlight(file_id).unwrap();
434 }
435
436 #[test]
437 fn test_string_highlighting() {
438     // The format string detection is based on macro-expansion,
439     // thus, we have to copy the macro definition from `std`
440     check_highlighting(
441         r#"
442 macro_rules! println {
443     ($($arg:tt)*) => ({
444         $crate::io::_print($crate::format_args_nl!($($arg)*));
445     })
446 }
447 #[rustc_builtin_macro]
448 #[macro_export]
449 macro_rules! format_args {}
450 #[rustc_builtin_macro]
451 #[macro_export]
452 macro_rules! const_format_args {}
453 #[rustc_builtin_macro]
454 #[macro_export]
455 macro_rules! format_args_nl {}
456
457 mod panic {
458     pub macro panic_2015 {
459         () => (
460             $crate::panicking::panic("explicit panic")
461         ),
462         ($msg:literal $(,)?) => (
463             $crate::panicking::panic($msg)
464         ),
465         // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
466         ($msg:expr $(,)?) => (
467             $crate::panicking::panic_str($msg)
468         ),
469         // Special-case the single-argument case for const_panic.
470         ("{}", $arg:expr $(,)?) => (
471             $crate::panicking::panic_display(&$arg)
472         ),
473         ($fmt:expr, $($arg:tt)+) => (
474             $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
475         ),
476     }
477 }
478
479 #[rustc_builtin_macro(std_panic)]
480 #[macro_export]
481 macro_rules! panic {}
482 #[rustc_builtin_macro]
483 macro_rules! assert {}
484 #[rustc_builtin_macro]
485 macro_rules! asm {}
486
487 macro_rules! toho {
488     () => ($crate::panic!("not yet implemented"));
489     ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
490 }
491
492 fn main() {
493     // from https://doc.rust-lang.org/std/fmt/index.html
494     println!("Hello");                 // => "Hello"
495     println!("Hello, {}!", "world");   // => "Hello, world!"
496     println!("The number is {}", 1);   // => "The number is 1"
497     println!("{:?}", (3, 4));          // => "(3, 4)"
498     println!("{value}", value=4);      // => "4"
499     println!("{} {}", 1, 2);           // => "1 2"
500     println!("{:04}", 42);             // => "0042" with leading zerosV
501     println!("{1} {} {0} {}", 1, 2);   // => "2 1 1 2"
502     println!("{argument}", argument = "test");   // => "test"
503     println!("{name} {}", 1, name = 2);          // => "2 1"
504     println!("{a} {c} {b}", a="a", b='b', c=3);  // => "a 3 b"
505     println!("{{{}}}", 2);                       // => "{2}"
506     println!("Hello {:5}!", "x");
507     println!("Hello {:1$}!", "x", 5);
508     println!("Hello {1:0$}!", 5, "x");
509     println!("Hello {:width$}!", "x", width = 5);
510     println!("Hello {:<5}!", "x");
511     println!("Hello {:-<5}!", "x");
512     println!("Hello {:^5}!", "x");
513     println!("Hello {:>5}!", "x");
514     println!("Hello {:+}!", 5);
515     println!("{:#x}!", 27);
516     println!("Hello {:05}!", 5);
517     println!("Hello {:05}!", -5);
518     println!("{:#010x}!", 27);
519     println!("Hello {0} is {1:.5}", "x", 0.01);
520     println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
521     println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
522     println!("Hello {} is {:.*}",    "x", 5, 0.01);
523     println!("Hello {} is {2:.*}",   "x", 5, 0.01);
524     println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
525     println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
526     println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
527     println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
528     println!("Hello {{}}");
529     println!("{{ Hello");
530
531     println!(r"Hello, {}!", "world");
532
533     // escape sequences
534     println!("Hello\nWorld");
535     println!("\u{48}\x65\x6C\x6C\x6F World");
536
537     println!("{\x41}", A = 92);
538     println!("{ничоси}", ничоси = 92);
539
540     println!("{:x?} {} ", thingy, n2);
541     panic!("{}", 0);
542     panic!("more {}", 1);
543     assert!(true, "{}", 1);
544     assert!(true, "{} asdasd", 1);
545     toho!("{}fmt", 0);
546     asm!("mov eax, {0}");
547     format_args!(concat!("{}"), "{}");
548 }"#
549         .trim(),
550         expect_file!["./test_data/highlight_strings.html"],
551         false,
552     );
553 }
554
555 #[test]
556 fn test_unsafe_highlighting() {
557     check_highlighting(
558         r#"
559 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
560 static GLOBAL: Struct = Struct { field: 0 };
561 unsafe fn unsafe_fn() {}
562
563 union Union {
564     a: u32,
565     b: f32,
566 }
567
568 struct Struct { field: i32 }
569 impl Struct {
570     unsafe fn unsafe_method(&self) {}
571 }
572
573 #[repr(packed)]
574 struct Packed {
575     a: u16,
576 }
577
578 unsafe trait UnsafeTrait {}
579 unsafe impl UnsafeTrait for Packed {}
580 impl !UnsafeTrait for () {}
581
582 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
583
584 trait DoTheAutoref {
585     fn calls_autoref(&self);
586 }
587
588 impl DoTheAutoref for u16 {
589     fn calls_autoref(&self) {}
590 }
591
592 fn main() {
593     let x = &5 as *const _ as *const usize;
594     let u = Union { b: 0 };
595     unsafe {
596         // unsafe fn and method calls
597         unsafe_fn();
598         let b = u.b;
599         match u {
600             Union { b: 0 } => (),
601             Union { a } => (),
602         }
603         Struct { field: 0 }.unsafe_method();
604
605         // unsafe deref
606         *x;
607
608         // unsafe access to a static mut
609         MUT_GLOBAL.field;
610         GLOBAL.field;
611
612         // unsafe ref of packed fields
613         let packed = Packed { a: 0 };
614         let a = &packed.a;
615         let ref a = packed.a;
616         let Packed { ref a } = packed;
617         let Packed { a: ref _a } = packed;
618
619         // unsafe auto ref of packed field
620         packed.a.calls_autoref();
621     }
622 }
623 "#
624         .trim(),
625         expect_file!["./test_data/highlight_unsafe.html"],
626         false,
627     );
628 }
629
630 #[test]
631 fn test_highlight_doc_comment() {
632     check_highlighting(
633         r#"
634 //! This is a module to test doc injection.
635 //! ```
636 //! fn test() {}
637 //! ```
638
639 /// ```
640 /// let _ = "early doctests should not go boom";
641 /// ```
642 struct Foo {
643     bar: bool,
644 }
645
646 /// This is an impl with a code block.
647 ///
648 /// ```
649 /// fn foo() {
650 ///
651 /// }
652 /// ```
653 impl Foo {
654     /// ```
655     /// let _ = "Call me
656     //    KILLER WHALE
657     ///     Ishmael.";
658     /// ```
659     pub const bar: bool = true;
660
661     /// Constructs a new `Foo`.
662     ///
663     /// # Examples
664     ///
665     /// ```
666     /// # #![allow(unused_mut)]
667     /// let mut foo: Foo = Foo::new();
668     /// ```
669     pub const fn new() -> Foo {
670         Foo { bar: true }
671     }
672
673     /// `bar` method on `Foo`.
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// use x::y;
679     ///
680     /// let foo = Foo::new();
681     ///
682     /// // calls bar on foo
683     /// assert!(foo.bar());
684     ///
685     /// let bar = foo.bar || Foo::bar;
686     ///
687     /// /* multi-line
688     ///        comment */
689     ///
690     /// let multi_line_string = "Foo
691     ///   bar\n
692     ///          ";
693     ///
694     /// ```
695     ///
696     /// ```rust,no_run
697     /// let foobar = Foo::new().bar();
698     /// ```
699     ///
700     /// ```sh
701     /// echo 1
702     /// ```
703     pub fn foo(&self) -> bool {
704         true
705     }
706 }
707
708 /// [`Foo`](Foo) is a struct
709 /// This function is > [`all_the_links`](all_the_links) <
710 /// [`noop`](noop) is a macro below
711 /// [`Item`] is a struct in the module [`module`]
712 ///
713 /// [`Item`]: module::Item
714 /// [mix_and_match]: ThisShouldntResolve
715 pub fn all_the_links() {}
716
717 pub mod module {
718     pub struct Item;
719 }
720
721 /// ```
722 /// macro_rules! noop { ($expr:expr) => { $expr }}
723 /// noop!(1);
724 /// ```
725 macro_rules! noop {
726     ($expr:expr) => {
727         $expr
728     }
729 }
730
731 /// ```rust
732 /// let _ = example(&[1, 2, 3]);
733 /// ```
734 ///
735 /// ```
736 /// loop {}
737 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
738 #[doc = "loop {}"]
739 /// ```
740 ///
741 #[cfg_attr(feature = "alloc", doc = "```rust")]
742 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
743 /// let _ = example(&alloc::vec![1, 2, 3]);
744 /// ```
745 pub fn mix_and_match() {}
746
747 /**
748 It is beyond me why you'd use these when you got ///
749 ```rust
750 let _ = example(&[1, 2, 3]);
751 ```
752 [`block_comments2`] tests these with indentation
753  */
754 pub fn block_comments() {}
755
756 /**
757     Really, I don't get it
758     ```rust
759     let _ = example(&[1, 2, 3]);
760     ```
761     [`block_comments`] tests these without indentation
762 */
763 pub fn block_comments2() {}
764 "#
765         .trim(),
766         expect_file!["./test_data/highlight_doctest.html"],
767         false,
768     );
769 }
770
771 #[test]
772 fn test_extern_crate() {
773     check_highlighting(
774         r#"
775         //- /main.rs crate:main deps:std,alloc
776         extern crate std;
777         extern crate alloc as abc;
778         //- /std/lib.rs crate:std
779         pub struct S;
780         //- /alloc/lib.rs crate:alloc
781         pub struct A
782         "#,
783         expect_file!["./test_data/highlight_extern_crate.html"],
784         false,
785     );
786 }
787
788 #[test]
789 fn test_crate_root() {
790     check_highlighting(
791         r#"
792         //- minicore: iterators
793         //- /main.rs crate:main deps:foo
794         extern crate foo;
795         use core::iter;
796
797         pub const NINETY_TWO: u8 = 92;
798
799         use foo as foooo;
800
801         pub(crate) fn main() {
802             let baz = iter::repeat(92);
803         }
804
805         mod bar {
806             pub(in super) const FORTY_TWO: u8 = 42;
807
808             mod baz {
809                 use super::super::NINETY_TWO;
810                 use crate::foooo::Point;
811
812                 pub(in super::super) const TWENTY_NINE: u8 = 29;
813             }
814         }
815         //- /foo.rs crate:foo
816         struct Point {
817             x: u8,
818             y: u8,
819         }
820
821         mod inner {
822             pub(super) fn swap(p: crate::Point) -> crate::Point {
823                 crate::Point { x: p.y, y: p.x }
824             }
825         }
826         "#,
827         expect_file!["./test_data/highlight_crate_root.html"],
828         false,
829     );
830 }
831
832 #[test]
833 fn test_default_library() {
834     check_highlighting(
835         r#"
836         //- minicore: option, iterators
837         use core::iter;
838
839         fn main() {
840             let foo = Some(92);
841             let nums = iter::repeat(foo.unwrap());
842         }
843         "#,
844         expect_file!["./test_data/highlight_default_library.html"],
845         false,
846     );
847 }
848
849 #[test]
850 fn test_associated_function() {
851     check_highlighting(
852         r#"
853 fn not_static() {}
854
855 struct foo {}
856
857 impl foo {
858     pub fn is_static() {}
859     pub fn is_not_static(&self) {}
860 }
861
862 trait t {
863     fn t_is_static() {}
864     fn t_is_not_static(&self) {}
865 }
866
867 impl t for foo {
868     pub fn is_static() {}
869     pub fn is_not_static(&self) {}
870 }
871         "#,
872         expect_file!["./test_data/highlight_assoc_functions.html"],
873         false,
874     )
875 }
876
877 #[test]
878 fn test_injection() {
879     check_highlighting(
880         r##"
881 fn f(ra_fixture: &str) {}
882 fn main() {
883     f(r"
884 fn foo() {
885     foo(\$0{
886         92
887     }\$0)
888 }");
889 }
890     "##,
891         expect_file!["./test_data/injection.html"],
892         false,
893     );
894 }
895
896 /// Highlights the code given by the `ra_fixture` argument, renders the
897 /// result as HTML, and compares it with the HTML file given as `snapshot`.
898 /// Note that the `snapshot` file is overwritten by the rendered HTML.
899 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
900     let (analysis, file_id) = fixture::file(ra_fixture);
901     let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
902     expect.assert_eq(actual_html)
903 }