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