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