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