]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting/tests.rs
Merge #9002
[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! 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
149     let mut vec = Vec::new();
150     if true {
151         let x = 92;
152         vec.push(Foo { x, y: 1 });
153     }
154     unsafe {
155         vec.set_len(0);
156         STATIC_MUT = 1;
157     }
158
159     for e in vec {
160         // Do nothing
161     }
162
163     noop!(noop!(1));
164
165     let mut x = 42;
166     let y = &mut x;
167     let z = &y;
168
169     let Foo { x: z, y } = Foo { x: z, y };
170
171     y;
172
173     let mut foo = Foo { x, y: x };
174     let foo2 = Foo { x, y: x };
175     foo.quop();
176     foo.qux();
177     foo.baz(foo2);
178
179     let mut copy = FooCopy { x };
180     copy.quop();
181     copy.qux();
182     copy.baz(copy);
183
184     let a = |x| x;
185     let bar = Foo::baz;
186
187     let baz = -42;
188     let baz = -baz;
189
190     let _ = !true;
191
192     'foo: loop {
193         break 'foo;
194         continue 'foo;
195     }
196 }
197
198 enum Option<T> {
199     Some(T),
200     None,
201 }
202 use Option::*;
203
204 impl<T> Option<T> {
205     fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
206         match other {
207             None => unimplemented!(),
208             Nope => Nope,
209         }
210     }
211 }
212
213 async fn learn_and_sing() {
214     let song = learn_song().await;
215     sing_song(song).await;
216 }
217
218 async fn async_main() {
219     let f1 = learn_and_sing();
220     let f2 = dance();
221     futures::join!(f1, f2);
222 }
223
224 unsafe trait Dangerous {}
225 impl Dangerous for () {}
226
227 fn use_foo_items() {
228     let bob = foo::Person {
229         name: "Bob",
230         age: foo::consts::NUMBER,
231     };
232
233     let control_flow = foo::identity(foo::ControlFlow::Continue);
234
235     if control_flow.should_die() {
236         foo::die!();
237     }
238 }
239
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, 1632);
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");
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_rules! format_args_nl {
437     ($fmt:expr) => {{ /* compiler built-in */ }};
438     ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
439 }
440
441 fn main() {
442     // from https://doc.rust-lang.org/std/fmt/index.html
443     println!("Hello");                 // => "Hello"
444     println!("Hello, {}!", "world");   // => "Hello, world!"
445     println!("The number is {}", 1);   // => "The number is 1"
446     println!("{:?}", (3, 4));          // => "(3, 4)"
447     println!("{value}", value=4);      // => "4"
448     println!("{} {}", 1, 2);           // => "1 2"
449     println!("{:04}", 42);             // => "0042" with leading zerosV
450     println!("{1} {} {0} {}", 1, 2);   // => "2 1 1 2"
451     println!("{argument}", argument = "test");   // => "test"
452     println!("{name} {}", 1, name = 2);          // => "2 1"
453     println!("{a} {c} {b}", a="a", b='b', c=3);  // => "a 3 b"
454     println!("{{{}}}", 2);                       // => "{2}"
455     println!("Hello {:5}!", "x");
456     println!("Hello {:1$}!", "x", 5);
457     println!("Hello {1:0$}!", 5, "x");
458     println!("Hello {:width$}!", "x", width = 5);
459     println!("Hello {:<5}!", "x");
460     println!("Hello {:-<5}!", "x");
461     println!("Hello {:^5}!", "x");
462     println!("Hello {:>5}!", "x");
463     println!("Hello {:+}!", 5);
464     println!("{:#x}!", 27);
465     println!("Hello {:05}!", 5);
466     println!("Hello {:05}!", -5);
467     println!("{:#010x}!", 27);
468     println!("Hello {0} is {1:.5}", "x", 0.01);
469     println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
470     println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
471     println!("Hello {} is {:.*}",    "x", 5, 0.01);
472     println!("Hello {} is {2:.*}",   "x", 5, 0.01);
473     println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
474     println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
475     println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
476     println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
477     println!("Hello {{}}");
478     println!("{{ Hello");
479
480     println!(r"Hello, {}!", "world");
481
482     // escape sequences
483     println!("Hello\nWorld");
484     println!("\u{48}\x65\x6C\x6C\x6F World");
485
486     println!("{\x41}", A = 92);
487     println!("{ничоси}", ничоси = 92);
488
489     println!("{:x?} {} ", thingy, n2);
490 }"#
491         .trim(),
492         expect_file!["./test_data/highlight_strings.html"],
493         false,
494     );
495 }
496
497 #[test]
498 fn test_unsafe_highlighting() {
499     check_highlighting(
500         r#"
501 unsafe fn unsafe_fn() {}
502
503 union Union {
504     a: u32,
505     b: f32,
506 }
507
508 struct HasUnsafeFn;
509
510 impl HasUnsafeFn {
511     unsafe fn unsafe_method(&self) {}
512 }
513
514 struct TypeForStaticMut {
515     a: u8
516 }
517
518 static mut global_mut: TypeForStaticMut = TypeForStaticMut { a: 0 };
519
520 #[repr(packed)]
521 struct Packed {
522     a: u16,
523 }
524
525 trait DoTheAutoref {
526     fn calls_autoref(&self);
527 }
528
529 impl DoTheAutoref for u16 {
530     fn calls_autoref(&self) {}
531 }
532
533 fn main() {
534     let x = &5 as *const _ as *const usize;
535     let u = Union { b: 0 };
536     unsafe {
537         // unsafe fn and method calls
538         unsafe_fn();
539         let b = u.b;
540         match u {
541             Union { b: 0 } => (),
542             Union { a } => (),
543         }
544         HasUnsafeFn.unsafe_method();
545
546         // unsafe deref
547         let y = *x;
548
549         // unsafe access to a static mut
550         let a = global_mut.a;
551
552         // unsafe ref of packed fields
553         let packed = Packed { a: 0 };
554         let a = &packed.a;
555         let ref a = packed.a;
556         let Packed { ref a } = packed;
557         let Packed { a: ref _a } = packed;
558
559         // unsafe auto ref of packed field
560         packed.a.calls_autoref();
561     }
562 }
563 "#
564         .trim(),
565         expect_file!["./test_data/highlight_unsafe.html"],
566         false,
567     );
568 }
569
570 #[test]
571 fn test_highlight_doc_comment() {
572     check_highlighting(
573         r#"
574 //! This is a module to test doc injection.
575 //! ```
576 //! fn test() {}
577 //! ```
578
579 /// ```
580 /// let _ = "early doctests should not go boom";
581 /// ```
582 struct Foo {
583     bar: bool,
584 }
585
586 /// This is an impl with a code block.
587 ///
588 /// ```
589 /// fn foo() {
590 ///
591 /// }
592 /// ```
593 impl Foo {
594     /// ```
595     /// let _ = "Call me
596     //    KILLER WHALE
597     ///     Ishmael.";
598     /// ```
599     pub const bar: bool = true;
600
601     /// Constructs a new `Foo`.
602     ///
603     /// # Examples
604     ///
605     /// ```
606     /// # #![allow(unused_mut)]
607     /// let mut foo: Foo = Foo::new();
608     /// ```
609     pub const fn new() -> Foo {
610         Foo { bar: true }
611     }
612
613     /// `bar` method on `Foo`.
614     ///
615     /// # Examples
616     ///
617     /// ```
618     /// use x::y;
619     ///
620     /// let foo = Foo::new();
621     ///
622     /// // calls bar on foo
623     /// assert!(foo.bar());
624     ///
625     /// let bar = foo.bar || Foo::bar;
626     ///
627     /// /* multi-line
628     ///        comment */
629     ///
630     /// let multi_line_string = "Foo
631     ///   bar\n
632     ///          ";
633     ///
634     /// ```
635     ///
636     /// ```rust,no_run
637     /// let foobar = Foo::new().bar();
638     /// ```
639     ///
640     /// ```sh
641     /// echo 1
642     /// ```
643     pub fn foo(&self) -> bool {
644         true
645     }
646 }
647
648 /// [`Foo`](Foo) is a struct
649 /// This function is > [`all_the_links`](all_the_links) <
650 /// [`noop`](noop) is a macro below
651 /// [`Item`] is a struct in the module [`module`]
652 ///
653 /// [`Item`]: module::Item
654 /// [mix_and_match]: ThisShouldntResolve
655 pub fn all_the_links() {}
656
657 pub mod module {
658     pub struct Item;
659 }
660
661 /// ```
662 /// noop!(1);
663 /// ```
664 macro_rules! noop {
665     ($expr:expr) => {
666         $expr
667     }
668 }
669
670 /// ```rust
671 /// let _ = example(&[1, 2, 3]);
672 /// ```
673 ///
674 /// ```
675 /// loop {}
676 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
677 #[doc = "loop {}"]
678 /// ```
679 ///
680 #[cfg_attr(feature = "alloc", doc = "```rust")]
681 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
682 /// let _ = example(&alloc::vec![1, 2, 3]);
683 /// ```
684 pub fn mix_and_match() {}
685
686 /**
687 It is beyond me why you'd use these when you got ///
688 ```rust
689 let _ = example(&[1, 2, 3]);
690 ```
691 [`block_comments2`] tests these with indentation
692  */
693 pub fn block_comments() {}
694
695 /**
696     Really, I don't get it
697     ```rust
698     let _ = example(&[1, 2, 3]);
699     ```
700     [`block_comments`] tests these without indentation
701 */
702 pub fn block_comments2() {}
703 "#
704         .trim(),
705         expect_file!["./test_data/highlight_doctest.html"],
706         false,
707     );
708 }
709
710 #[test]
711 fn test_extern_crate() {
712     check_highlighting(
713         r#"
714         //- /main.rs crate:main deps:std,alloc
715         extern crate std;
716         extern crate alloc as abc;
717         //- /std/lib.rs crate:std
718         pub struct S;
719         //- /alloc/lib.rs crate:alloc
720         pub struct A
721         "#,
722         expect_file!["./test_data/highlight_extern_crate.html"],
723         false,
724     );
725 }
726
727 #[test]
728 fn test_associated_function() {
729     check_highlighting(
730         r#"
731 fn not_static() {}
732
733 struct foo {}
734
735 impl foo {
736     pub fn is_static() {}
737     pub fn is_not_static(&self) {}
738 }
739
740 trait t {
741     fn t_is_static() {}
742     fn t_is_not_static(&self) {}
743 }
744
745 impl t for foo {
746     pub fn is_static() {}
747     pub fn is_not_static(&self) {}
748 }
749         "#,
750         expect_file!["./test_data/highlight_assoc_functions.html"],
751         false,
752     )
753 }
754
755 #[test]
756 fn test_injection() {
757     check_highlighting(
758         r##"
759 fn f(ra_fixture: &str) {}
760 fn main() {
761     f(r"
762 fn foo() {
763     foo(\$0{
764         92
765     }\$0)
766 }");
767 }
768     "##,
769         expect_file!["./test_data/injection.html"],
770         false,
771     );
772 }
773
774 /// Highlights the code given by the `ra_fixture` argument, renders the
775 /// result as HTML, and compares it with the HTML file given as `snapshot`.
776 /// Note that the `snapshot` file is overwritten by the rendered HTML.
777 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
778     let (analysis, file_id) = fixture::file(ra_fixture);
779     let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
780     expect.assert_eq(actual_html)
781 }