]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting/tests.rs
Merge #9264
[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 unsafe trait UnsafeTrait {}
531 unsafe impl UnsafeTrait for Packed {}
532
533 fn require_unsafe_trait<T: UnsafeTrait>(_: T) {}
534
535 trait DoTheAutoref {
536     fn calls_autoref(&self);
537 }
538
539 impl DoTheAutoref for u16 {
540     fn calls_autoref(&self) {}
541 }
542
543 fn main() {
544     let x = &5 as *const _ as *const usize;
545     let u = Union { b: 0 };
546     unsafe {
547         // unsafe fn and method calls
548         unsafe_fn();
549         let b = u.b;
550         match u {
551             Union { b: 0 } => (),
552             Union { a } => (),
553         }
554         HasUnsafeFn.unsafe_method();
555
556         // unsafe deref
557         let y = *x;
558
559         // unsafe access to a static mut
560         let a = global_mut.a;
561
562         // unsafe ref of packed fields
563         let packed = Packed { a: 0 };
564         let a = &packed.a;
565         let ref a = packed.a;
566         let Packed { ref a } = packed;
567         let Packed { a: ref _a } = packed;
568
569         // unsafe auto ref of packed field
570         packed.a.calls_autoref();
571     }
572 }
573 "#
574         .trim(),
575         expect_file!["./test_data/highlight_unsafe.html"],
576         false,
577     );
578 }
579
580 #[test]
581 fn test_highlight_doc_comment() {
582     check_highlighting(
583         r#"
584 //! This is a module to test doc injection.
585 //! ```
586 //! fn test() {}
587 //! ```
588
589 /// ```
590 /// let _ = "early doctests should not go boom";
591 /// ```
592 struct Foo {
593     bar: bool,
594 }
595
596 /// This is an impl with a code block.
597 ///
598 /// ```
599 /// fn foo() {
600 ///
601 /// }
602 /// ```
603 impl Foo {
604     /// ```
605     /// let _ = "Call me
606     //    KILLER WHALE
607     ///     Ishmael.";
608     /// ```
609     pub const bar: bool = true;
610
611     /// Constructs a new `Foo`.
612     ///
613     /// # Examples
614     ///
615     /// ```
616     /// # #![allow(unused_mut)]
617     /// let mut foo: Foo = Foo::new();
618     /// ```
619     pub const fn new() -> Foo {
620         Foo { bar: true }
621     }
622
623     /// `bar` method on `Foo`.
624     ///
625     /// # Examples
626     ///
627     /// ```
628     /// use x::y;
629     ///
630     /// let foo = Foo::new();
631     ///
632     /// // calls bar on foo
633     /// assert!(foo.bar());
634     ///
635     /// let bar = foo.bar || Foo::bar;
636     ///
637     /// /* multi-line
638     ///        comment */
639     ///
640     /// let multi_line_string = "Foo
641     ///   bar\n
642     ///          ";
643     ///
644     /// ```
645     ///
646     /// ```rust,no_run
647     /// let foobar = Foo::new().bar();
648     /// ```
649     ///
650     /// ```sh
651     /// echo 1
652     /// ```
653     pub fn foo(&self) -> bool {
654         true
655     }
656 }
657
658 /// [`Foo`](Foo) is a struct
659 /// This function is > [`all_the_links`](all_the_links) <
660 /// [`noop`](noop) is a macro below
661 /// [`Item`] is a struct in the module [`module`]
662 ///
663 /// [`Item`]: module::Item
664 /// [mix_and_match]: ThisShouldntResolve
665 pub fn all_the_links() {}
666
667 pub mod module {
668     pub struct Item;
669 }
670
671 /// ```
672 /// noop!(1);
673 /// ```
674 macro_rules! noop {
675     ($expr:expr) => {
676         $expr
677     }
678 }
679
680 /// ```rust
681 /// let _ = example(&[1, 2, 3]);
682 /// ```
683 ///
684 /// ```
685 /// loop {}
686 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
687 #[doc = "loop {}"]
688 /// ```
689 ///
690 #[cfg_attr(feature = "alloc", doc = "```rust")]
691 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
692 /// let _ = example(&alloc::vec![1, 2, 3]);
693 /// ```
694 pub fn mix_and_match() {}
695
696 /**
697 It is beyond me why you'd use these when you got ///
698 ```rust
699 let _ = example(&[1, 2, 3]);
700 ```
701 [`block_comments2`] tests these with indentation
702  */
703 pub fn block_comments() {}
704
705 /**
706     Really, I don't get it
707     ```rust
708     let _ = example(&[1, 2, 3]);
709     ```
710     [`block_comments`] tests these without indentation
711 */
712 pub fn block_comments2() {}
713 "#
714         .trim(),
715         expect_file!["./test_data/highlight_doctest.html"],
716         false,
717     );
718 }
719
720 #[test]
721 fn test_extern_crate() {
722     check_highlighting(
723         r#"
724         //- /main.rs crate:main deps:std,alloc
725         extern crate std;
726         extern crate alloc as abc;
727         //- /std/lib.rs crate:std
728         pub struct S;
729         //- /alloc/lib.rs crate:alloc
730         pub struct A
731         "#,
732         expect_file!["./test_data/highlight_extern_crate.html"],
733         false,
734     );
735 }
736
737 #[test]
738 fn test_associated_function() {
739     check_highlighting(
740         r#"
741 fn not_static() {}
742
743 struct foo {}
744
745 impl foo {
746     pub fn is_static() {}
747     pub fn is_not_static(&self) {}
748 }
749
750 trait t {
751     fn t_is_static() {}
752     fn t_is_not_static(&self) {}
753 }
754
755 impl t for foo {
756     pub fn is_static() {}
757     pub fn is_not_static(&self) {}
758 }
759         "#,
760         expect_file!["./test_data/highlight_assoc_functions.html"],
761         false,
762     )
763 }
764
765 #[test]
766 fn test_injection() {
767     check_highlighting(
768         r##"
769 fn f(ra_fixture: &str) {}
770 fn main() {
771     f(r"
772 fn foo() {
773     foo(\$0{
774         92
775     }\$0)
776 }");
777 }
778     "##,
779         expect_file!["./test_data/injection.html"],
780         false,
781     );
782 }
783
784 /// Highlights the code given by the `ra_fixture` argument, renders the
785 /// result as HTML, and compares it with the HTML file given as `snapshot`.
786 /// Note that the `snapshot` file is overwritten by the rendered HTML.
787 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
788     let (analysis, file_id) = fixture::file(ra_fixture);
789     let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
790     expect.assert_eq(actual_html)
791 }