]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting/tests.rs
Give defaultLibrary semantic token modifier to items from standard library
[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 //- /main.rs crate:main deps:foo
15 use inner::{self as inner_mod};
16 mod inner {}
17
18 #[rustc_builtin_macro]
19 macro Copy {}
20
21 // Needed for function consuming vs normal
22 pub mod marker {
23     #[lang = "copy"]
24     pub trait Copy {}
25 }
26
27 #[proc_macros::identity]
28 pub mod ops {
29     #[lang = "fn_once"]
30     pub trait FnOnce<Args> {}
31
32     #[lang = "fn_mut"]
33     pub trait FnMut<Args>: FnOnce<Args> {}
34
35     #[lang = "fn"]
36     pub trait Fn<Args>: FnMut<Args> {}
37 }
38
39 proc_macros::mirror! {
40     {
41         ,i32 :x pub
42         ,i32 :y pub
43     } Foo struct
44 }
45
46 trait Bar where Self: {
47     fn bar(&self) -> i32;
48 }
49
50 impl Bar for Foo where Self: {
51     fn bar(&self) -> i32 {
52         self.x
53     }
54 }
55
56 impl Foo {
57     fn baz(mut self, f: Foo) -> i32 {
58         f.baz(self)
59     }
60
61     fn qux(&mut self) {
62         self.x = 0;
63     }
64
65     fn quop(&self) -> i32 {
66         self.x
67     }
68 }
69
70 #[derive(Copy)]
71 struct FooCopy {
72     x: u32,
73 }
74
75 impl FooCopy {
76     fn baz(self, f: FooCopy) -> u32 {
77         f.baz(self)
78     }
79
80     fn qux(&mut self) {
81         self.x = 0;
82     }
83
84     fn quop(&self) -> u32 {
85         self.x
86     }
87 }
88
89 fn str() {
90     str();
91 }
92
93 fn foo<'a, T>() -> T {
94     foo::<'a, i32>()
95 }
96
97 fn never() -> ! {
98     loop {}
99 }
100
101 fn const_param<const FOO: usize>() -> usize {
102     FOO
103 }
104
105 use ops::Fn;
106 fn baz<F: Fn() -> ()>(f: F) {
107     f()
108 }
109
110 fn foobar() -> impl Copy {}
111
112 fn foo() {
113     let bar = foobar();
114 }
115
116 macro_rules! def_fn {
117     ($($tt:tt)*) => {$($tt)*}
118 }
119
120 def_fn! {
121     fn bar() -> u32 {
122         100
123     }
124 }
125
126 macro_rules! dont_color_me_braces {
127     () => {0}
128 }
129
130 macro_rules! noop {
131     ($expr:expr) => {
132         $expr
133     }
134 }
135
136 macro_rules! keyword_frag {
137     ($type:ty) => ($type)
138 }
139
140 macro with_args($i:ident) {
141     $i
142 }
143
144 macro without_args {
145     ($i:ident) => {
146         $i
147     }
148 }
149
150 // comment
151 fn main() {
152     println!("Hello, {}!", 92);
153     dont_color_me_braces!();
154
155     let mut vec = Vec::new();
156     if true {
157         let x = 92;
158         vec.push(Foo { x, y: 1 });
159     }
160
161     for e in vec {
162         // Do nothing
163     }
164
165     noop!(noop!(1));
166
167     let mut x = 42;
168     x += 1;
169     let y = &mut x;
170     let z = &y;
171
172     let Foo { x: z, y } = Foo { x: z, y };
173
174     y;
175
176     let mut foo = Foo { x, y: x };
177     let foo2 = Foo { x, y: x };
178     foo.quop();
179     foo.qux();
180     foo.baz(foo2);
181
182     let mut copy = FooCopy { x };
183     copy.quop();
184     copy.qux();
185     copy.baz(copy);
186
187     let a = |x| x;
188     let bar = Foo::baz;
189
190     let baz = (-42,);
191     let baz = -baz.0;
192
193     let _ = !true;
194
195     'foo: loop {
196         break 'foo;
197         continue 'foo;
198     }
199 }
200
201 enum Option<T> {
202     Some(T),
203     None,
204 }
205 use Option::*;
206
207 impl<T> Option<T> {
208     fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
209         match other {
210             None => unimplemented!(),
211             Nope => Nope,
212         }
213     }
214 }
215
216 async fn learn_and_sing() {
217     let song = learn_song().await;
218     sing_song(song).await;
219 }
220
221 async fn async_main() {
222     let f1 = learn_and_sing();
223     let f2 = dance();
224     futures::join!(f1, f2);
225 }
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 pub enum Bool { True, False }
241
242 impl Bool {
243     pub const fn to_primitive(self) -> bool {
244         matches!(self, Self::True)
245     }
246 }
247 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
248
249 //- /foo.rs crate:foo
250 pub struct Person {
251     pub name: &'static str,
252     pub age: u8,
253 }
254
255 pub enum ControlFlow {
256     Continue,
257     Die,
258 }
259
260 impl ControlFlow {
261     pub fn should_die(self) -> bool {
262         matches!(self, ControlFlow::Die)
263     }
264 }
265
266 pub fn identity<T>(x: T) -> T { x }
267
268 pub mod consts {
269     pub const NUMBER: i64 = 92;
270 }
271
272 macro_rules! die {
273     () => {
274         panic!();
275     };
276 }
277 "#
278         .trim(),
279         expect_file!["./test_data/highlighting.html"],
280         false,
281     );
282 }
283
284 #[test]
285 fn test_rainbow_highlighting() {
286     check_highlighting(
287         r#"
288 fn main() {
289     let hello = "hello";
290     let x = hello.to_string();
291     let y = hello.to_string();
292
293     let x = "other color please!";
294     let y = x.to_string();
295 }
296
297 fn bar() {
298     let mut hello = "hello";
299 }
300 "#
301         .trim(),
302         expect_file!["./test_data/rainbow_highlighting.html"],
303         true,
304     );
305 }
306
307 #[test]
308 fn benchmark_syntax_highlighting_long_struct() {
309     if skip_slow_tests() {
310         return;
311     }
312
313     let fixture = bench_fixture::big_struct();
314     let (analysis, file_id) = fixture::file(&fixture);
315
316     let hash = {
317         let _pt = bench("syntax highlighting long struct");
318         analysis
319             .highlight(file_id)
320             .unwrap()
321             .iter()
322             .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
323             .count()
324     };
325     assert_eq!(hash, 2001);
326 }
327
328 #[test]
329 fn syntax_highlighting_not_quadratic() {
330     if skip_slow_tests() {
331         return;
332     }
333
334     let mut al = AssertLinear::default();
335     while al.next_round() {
336         for i in 6..=10 {
337             let n = 1 << i;
338
339             let fixture = bench_fixture::big_struct_n(n);
340             let (analysis, file_id) = fixture::file(&fixture);
341
342             let time = Instant::now();
343
344             let hash = analysis
345                 .highlight(file_id)
346                 .unwrap()
347                 .iter()
348                 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
349                 .count();
350             assert!(hash > n as usize);
351
352             let elapsed = time.elapsed();
353             al.sample(n as f64, elapsed.as_millis() as f64);
354         }
355     }
356 }
357
358 #[test]
359 fn benchmark_syntax_highlighting_parser() {
360     if skip_slow_tests() {
361         return;
362     }
363
364     let fixture = bench_fixture::glorious_old_parser();
365     let (analysis, file_id) = fixture::file(&fixture);
366
367     let hash = {
368         let _pt = bench("syntax highlighting parser");
369         analysis
370             .highlight(file_id)
371             .unwrap()
372             .iter()
373             .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
374             .count()
375     };
376     assert_eq!(hash, 1616);
377 }
378
379 #[test]
380 fn test_ranges() {
381     let (analysis, file_id) = fixture::file(
382         r#"
383 #[derive(Clone, Debug)]
384 struct Foo {
385     pub x: i32,
386     pub y: i32,
387 }
388 "#,
389     );
390
391     // The "x"
392     let highlights = &analysis
393         .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
394         .unwrap();
395
396     assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
397 }
398
399 #[test]
400 fn test_flattening() {
401     check_highlighting(
402         r##"
403 fn fixture(ra_fixture: &str) {}
404
405 fn main() {
406     fixture(r#"
407         trait Foo {
408             fn foo() {
409                 println!("2 + 2 = {}", 4);
410             }
411         }"#
412     );
413 }"##
414         .trim(),
415         expect_file!["./test_data/highlight_injection.html"],
416         false,
417     );
418 }
419
420 #[test]
421 fn ranges_sorted() {
422     let (analysis, file_id) = fixture::file(
423         r#"
424 #[foo(bar = "bar")]
425 macro_rules! test {}
426 }"#
427         .trim(),
428     );
429     let _ = analysis.highlight(file_id).unwrap();
430 }
431
432 #[test]
433 fn test_string_highlighting() {
434     // The format string detection is based on macro-expansion,
435     // thus, we have to copy the macro definition from `std`
436     check_highlighting(
437         r#"
438 macro_rules! println {
439     ($($arg:tt)*) => ({
440         $crate::io::_print($crate::format_args_nl!($($arg)*));
441     })
442 }
443 #[rustc_builtin_macro]
444 macro_rules! format_args_nl {
445     ($fmt:expr) => {{ /* compiler built-in */ }};
446     ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
447 }
448
449 fn main() {
450     // from https://doc.rust-lang.org/std/fmt/index.html
451     println!("Hello");                 // => "Hello"
452     println!("Hello, {}!", "world");   // => "Hello, world!"
453     println!("The number is {}", 1);   // => "The number is 1"
454     println!("{:?}", (3, 4));          // => "(3, 4)"
455     println!("{value}", value=4);      // => "4"
456     println!("{} {}", 1, 2);           // => "1 2"
457     println!("{:04}", 42);             // => "0042" with leading zerosV
458     println!("{1} {} {0} {}", 1, 2);   // => "2 1 1 2"
459     println!("{argument}", argument = "test");   // => "test"
460     println!("{name} {}", 1, name = 2);          // => "2 1"
461     println!("{a} {c} {b}", a="a", b='b', c=3);  // => "a 3 b"
462     println!("{{{}}}", 2);                       // => "{2}"
463     println!("Hello {:5}!", "x");
464     println!("Hello {:1$}!", "x", 5);
465     println!("Hello {1:0$}!", 5, "x");
466     println!("Hello {:width$}!", "x", width = 5);
467     println!("Hello {:<5}!", "x");
468     println!("Hello {:-<5}!", "x");
469     println!("Hello {:^5}!", "x");
470     println!("Hello {:>5}!", "x");
471     println!("Hello {:+}!", 5);
472     println!("{:#x}!", 27);
473     println!("Hello {:05}!", 5);
474     println!("Hello {:05}!", -5);
475     println!("{:#010x}!", 27);
476     println!("Hello {0} is {1:.5}", "x", 0.01);
477     println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
478     println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
479     println!("Hello {} is {:.*}",    "x", 5, 0.01);
480     println!("Hello {} is {2:.*}",   "x", 5, 0.01);
481     println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
482     println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
483     println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
484     println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
485     println!("Hello {{}}");
486     println!("{{ Hello");
487
488     println!(r"Hello, {}!", "world");
489
490     // escape sequences
491     println!("Hello\nWorld");
492     println!("\u{48}\x65\x6C\x6C\x6F World");
493
494     println!("{\x41}", A = 92);
495     println!("{ничоси}", ничоси = 92);
496
497     println!("{:x?} {} ", thingy, n2);
498 }"#
499         .trim(),
500         expect_file!["./test_data/highlight_strings.html"],
501         false,
502     );
503 }
504
505 #[test]
506 fn test_unsafe_highlighting() {
507     check_highlighting(
508         r#"
509 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
510 static GLOBAL: Struct = Struct { field: 0 };
511 unsafe fn unsafe_fn() {}
512
513 union Union {
514     a: u32,
515     b: f32,
516 }
517
518 struct Struct { field: i32 }
519 impl Struct {
520     unsafe fn unsafe_method(&self) {}
521 }
522
523 #[repr(packed)]
524 struct Packed {
525     a: u16,
526 }
527
528 unsafe trait UnsafeTrait {}
529 unsafe impl UnsafeTrait for Packed {}
530 impl !UnsafeTrait for () {}
531
532 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
533
534 trait DoTheAutoref {
535     fn calls_autoref(&self);
536 }
537
538 impl DoTheAutoref for u16 {
539     fn calls_autoref(&self) {}
540 }
541
542 fn main() {
543     let x = &5 as *const _ as *const usize;
544     let u = Union { b: 0 };
545     unsafe {
546         // unsafe fn and method calls
547         unsafe_fn();
548         let b = u.b;
549         match u {
550             Union { b: 0 } => (),
551             Union { a } => (),
552         }
553         Struct { field: 0 }.unsafe_method();
554
555         // unsafe deref
556         *x;
557
558         // unsafe access to a static mut
559         MUT_GLOBAL.field;
560         GLOBAL.field;
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_default_library() {
739     check_highlighting(
740         r#"
741         //- minicore: option, iterators
742         use core::iter;
743
744         fn main() {
745             let foo = Some(92);
746             let nums = iter::repeat(foo.unwrap());
747         }
748         "#,
749         expect_file!["./test_data/highlight_default_library.html"],
750         false,
751     );
752 }
753
754 #[test]
755 fn test_associated_function() {
756     check_highlighting(
757         r#"
758 fn not_static() {}
759
760 struct foo {}
761
762 impl foo {
763     pub fn is_static() {}
764     pub fn is_not_static(&self) {}
765 }
766
767 trait t {
768     fn t_is_static() {}
769     fn t_is_not_static(&self) {}
770 }
771
772 impl t for foo {
773     pub fn is_static() {}
774     pub fn is_not_static(&self) {}
775 }
776         "#,
777         expect_file!["./test_data/highlight_assoc_functions.html"],
778         false,
779     )
780 }
781
782 #[test]
783 fn test_injection() {
784     check_highlighting(
785         r##"
786 fn f(ra_fixture: &str) {}
787 fn main() {
788     f(r"
789 fn foo() {
790     foo(\$0{
791         92
792     }\$0)
793 }");
794 }
795     "##,
796         expect_file!["./test_data/injection.html"],
797         false,
798     );
799 }
800
801 /// Highlights the code given by the `ra_fixture` argument, renders the
802 /// result as HTML, and compares it with the HTML file given as `snapshot`.
803 /// Note that the `snapshot` file is overwritten by the rendered HTML.
804 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
805     let (analysis, file_id) = fixture::file(ra_fixture);
806     let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
807     expect.assert_eq(actual_html)
808 }