1 use std::time::Instant;
3 use expect_test::{expect_file, ExpectFile};
4 use ide_db::SymbolKind;
5 use test_utils::{bench, bench_fixture, skip_slow_tests, AssertLinear};
7 use crate::{fixture, FileRange, HlTag, TextRange};
10 fn test_highlighting() {
13 //- proc_macros: identity, mirror
14 //- minicore: derive, copy
15 //- /main.rs crate:main deps:foo
16 use inner::{self as inner_mod};
21 #[proc_macros::identity]
24 pub trait FnOnce<Args> {}
27 pub trait FnMut<Args>: FnOnce<Args> {}
30 pub trait Fn<Args>: FnMut<Args> {}
33 proc_macros::mirror! {
40 trait Bar where Self: {
44 impl Bar for Foo where Self: {
45 fn bar(&self) -> i32 {
51 fn baz(mut self, f: Foo) -> i32 {
59 fn quop(&self) -> i32 {
64 use self::FooCopy::{self as BarCopy};
67 /// This is a doc comment
68 // This is a normal comment
69 /// This is a doc comment
71 // This is another normal comment
72 /// This is another doc comment
73 // This is another normal comment
75 // The reason for these being here is to test AttrIds
81 fn baz(self, f: FooCopy) -> u32 {
89 fn quop(&self) -> u32 {
98 fn foo<'a, T>() -> T {
106 fn const_param<const FOO: usize>() -> usize {
111 fn baz<F: Fn() -> ()>(f: F) {
115 fn foobar() -> impl Copy {}
121 macro_rules! def_fn {
122 ($($tt:tt)*) => {$($tt)*}
131 macro_rules! dont_color_me_braces {
141 macro_rules! keyword_frag {
142 ($type:ty) => ($type)
145 macro with_args($i:ident) {
157 println!("Hello, {}!", 92);
158 dont_color_me_braces!();
160 let mut vec = Vec::new();
163 vec.push(Foo { x, y: 1 });
177 let Foo { x: z, y } = Foo { x: z, y };
181 let mut foo = Foo { x, y: x };
182 let foo2 = Foo { x, y: x };
187 let mut copy = FooCopy { x };
213 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
215 None => unimplemented!(),
221 async fn learn_and_sing() {
222 let song = learn_song().await;
223 sing_song(song).await;
226 async fn async_main() {
227 let f1 = learn_and_sing();
229 futures::join!(f1, f2);
233 let bob = foo::Person {
235 age: foo::consts::NUMBER,
238 let control_flow = foo::identity(foo::ControlFlow::Continue);
240 if control_flow.should_die() {
245 pub enum Bool { True, False }
248 pub const fn to_primitive(self) -> bool {
249 matches!(self, Self::True)
252 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
261 <T as Baz>::Qux: Bar {}
263 //- /foo.rs crate:foo
265 pub name: &'static str,
269 pub enum ControlFlow {
275 pub fn should_die(self) -> bool {
276 matches!(self, ControlFlow::Die)
280 pub fn identity<T>(x: T) -> T { x }
283 pub const NUMBER: i64 = 92;
293 expect_file!["./test_data/highlighting.html"],
299 fn test_rainbow_highlighting() {
304 let x = hello.to_string();
305 let y = hello.to_string();
307 let x = "other color please!";
308 let y = x.to_string();
312 let mut hello = "hello";
316 expect_file!["./test_data/rainbow_highlighting.html"],
322 fn benchmark_syntax_highlighting_long_struct() {
323 if skip_slow_tests() {
327 let fixture = bench_fixture::big_struct();
328 let (analysis, file_id) = fixture::file(&fixture);
331 let _pt = bench("syntax highlighting long struct");
336 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
339 assert_eq!(hash, 2001);
343 fn syntax_highlighting_not_quadratic() {
344 if skip_slow_tests() {
348 let mut al = AssertLinear::default();
349 while al.next_round() {
353 let fixture = bench_fixture::big_struct_n(n);
354 let (analysis, file_id) = fixture::file(&fixture);
356 let time = Instant::now();
362 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
364 assert!(hash > n as usize);
366 let elapsed = time.elapsed();
367 al.sample(n as f64, elapsed.as_millis() as f64);
373 fn benchmark_syntax_highlighting_parser() {
374 if skip_slow_tests() {
378 let fixture = bench_fixture::glorious_old_parser();
379 let (analysis, file_id) = fixture::file(&fixture);
382 let _pt = bench("syntax highlighting parser");
387 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
390 assert_eq!(hash, 1616);
395 let (analysis, file_id) = fixture::file(
397 #[derive(Clone, Debug)]
406 let highlights = &analysis
407 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
410 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
414 fn test_flattening() {
417 fn fixture(ra_fixture: &str) {}
423 println!("2 + 2 = {}", 4);
429 expect_file!["./test_data/highlight_injection.html"],
436 let (analysis, file_id) = fixture::file(
443 let _ = analysis.highlight(file_id).unwrap();
447 fn test_string_highlighting() {
448 // The format string detection is based on macro-expansion,
449 // thus, we have to copy the macro definition from `std`
452 macro_rules! println {
454 $crate::io::_print($crate::format_args_nl!($($arg)*));
457 #[rustc_builtin_macro]
459 macro_rules! format_args {}
460 #[rustc_builtin_macro]
462 macro_rules! const_format_args {}
463 #[rustc_builtin_macro]
465 macro_rules! format_args_nl {}
468 pub macro panic_2015 {
470 $crate::panicking::panic("explicit panic")
472 ($msg:literal $(,)?) => (
473 $crate::panicking::panic($msg)
475 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
476 ($msg:expr $(,)?) => (
477 $crate::panicking::panic_str($msg)
479 // Special-case the single-argument case for const_panic.
480 ("{}", $arg:expr $(,)?) => (
481 $crate::panicking::panic_display(&$arg)
483 ($fmt:expr, $($arg:tt)+) => (
484 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
489 #[rustc_builtin_macro(std_panic)]
491 macro_rules! panic {}
492 #[rustc_builtin_macro]
493 macro_rules! assert {}
494 #[rustc_builtin_macro]
498 () => ($crate::panic!("not yet implemented"));
499 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
503 // from https://doc.rust-lang.org/std/fmt/index.html
504 println!("Hello"); // => "Hello"
505 println!("Hello, {}!", "world"); // => "Hello, world!"
506 println!("The number is {}", 1); // => "The number is 1"
507 println!("{:?}", (3, 4)); // => "(3, 4)"
508 println!("{value}", value=4); // => "4"
509 println!("{} {}", 1, 2); // => "1 2"
510 println!("{:04}", 42); // => "0042" with leading zerosV
511 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
512 println!("{argument}", argument = "test"); // => "test"
513 println!("{name} {}", 1, name = 2); // => "2 1"
514 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
515 println!("{{{}}}", 2); // => "{2}"
516 println!("Hello {:5}!", "x");
517 println!("Hello {:1$}!", "x", 5);
518 println!("Hello {1:0$}!", 5, "x");
519 println!("Hello {:width$}!", "x", width = 5);
520 println!("Hello {:<5}!", "x");
521 println!("Hello {:-<5}!", "x");
522 println!("Hello {:^5}!", "x");
523 println!("Hello {:>5}!", "x");
524 println!("Hello {:+}!", 5);
525 println!("{:#x}!", 27);
526 println!("Hello {:05}!", 5);
527 println!("Hello {:05}!", -5);
528 println!("{:#010x}!", 27);
529 println!("Hello {0} is {1:.5}", "x", 0.01);
530 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
531 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
532 println!("Hello {} is {:.*}", "x", 5, 0.01);
533 println!("Hello {} is {2:.*}", "x", 5, 0.01);
534 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
535 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
536 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
537 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
538 println!("Hello {{}}");
539 println!("{{ Hello");
541 println!(r"Hello, {}!", "world");
544 println!("Hello\nWorld");
545 println!("\u{48}\x65\x6C\x6C\x6F World");
547 println!("{\x41}", A = 92);
548 println!("{ничоси}", ничоси = 92);
550 println!("{:x?} {} ", thingy, n2);
552 panic!("more {}", 1);
553 assert!(true, "{}", 1);
554 assert!(true, "{} asdasd", 1);
556 asm!("mov eax, {0}");
557 format_args!(concat!("{}"), "{}");
560 expect_file!["./test_data/highlight_strings.html"],
566 fn test_unsafe_highlighting() {
569 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
570 static GLOBAL: Struct = Struct { field: 0 };
571 unsafe fn unsafe_fn() {}
578 struct Struct { field: i32 }
580 unsafe fn unsafe_method(&self) {}
588 unsafe trait UnsafeTrait {}
589 unsafe impl UnsafeTrait for Packed {}
590 impl !UnsafeTrait for () {}
592 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
595 fn calls_autoref(&self);
598 impl DoTheAutoref for u16 {
599 fn calls_autoref(&self) {}
603 let x = &5 as *const _ as *const usize;
604 let u = Union { b: 0 };
606 // unsafe fn and method calls
610 Union { b: 0 } => (),
613 Struct { field: 0 }.unsafe_method();
618 // unsafe access to a static mut
622 // unsafe ref of packed fields
623 let packed = Packed { a: 0 };
625 let ref a = packed.a;
626 let Packed { ref a } = packed;
627 let Packed { a: ref _a } = packed;
629 // unsafe auto ref of packed field
630 packed.a.calls_autoref();
635 expect_file!["./test_data/highlight_unsafe.html"],
641 fn test_highlight_doc_comment() {
644 //! This is a module to test doc injection.
650 /// let _ = "early doctests should not go boom";
656 /// This is an impl with a code block.
669 pub const bar: bool = true;
671 /// Constructs a new `Foo`.
676 /// # #![allow(unused_mut)]
677 /// let mut foo: Foo = Foo::new();
679 pub const fn new() -> Foo {
683 /// `bar` method on `Foo`.
690 /// let foo = Foo::new();
692 /// // calls bar on foo
693 /// assert!(foo.bar());
695 /// let bar = foo.bar || Foo::bar;
700 /// let multi_line_string = "Foo
707 /// let foobar = Foo::new().bar();
713 pub fn foo(&self) -> bool {
718 /// [`Foo`](Foo) is a struct
719 /// This function is > [`all_the_links`](all_the_links) <
720 /// [`noop`](noop) is a macro below
721 /// [`Item`] is a struct in the module [`module`]
723 /// [`Item`]: module::Item
724 /// [mix_and_match]: ThisShouldntResolve
725 pub fn all_the_links() {}
732 /// macro_rules! noop { ($expr:expr) => { $expr }}
742 /// let _ = example(&[1, 2, 3]);
747 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
751 #[cfg_attr(feature = "alloc", doc = "```rust")]
752 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
753 /// let _ = example(&alloc::vec![1, 2, 3]);
755 pub fn mix_and_match() {}
758 It is beyond me why you'd use these when you got ///
760 let _ = example(&[1, 2, 3]);
762 [`block_comments2`] tests these with indentation
764 pub fn block_comments() {}
767 Really, I don't get it
769 let _ = example(&[1, 2, 3]);
771 [`block_comments`] tests these without indentation
773 pub fn block_comments2() {}
776 expect_file!["./test_data/highlight_doctest.html"],
782 fn test_extern_crate() {
785 //- /main.rs crate:main deps:std,alloc
787 extern crate alloc as abc;
788 //- /std/lib.rs crate:std
790 //- /alloc/lib.rs crate:alloc
793 expect_file!["./test_data/highlight_extern_crate.html"],
799 fn test_crate_root() {
802 //- minicore: iterators
803 //- /main.rs crate:main deps:foo
807 pub const NINETY_TWO: u8 = 92;
811 pub(crate) fn main() {
812 let baz = iter::repeat(92);
816 pub(in super) const FORTY_TWO: u8 = 42;
819 use super::super::NINETY_TWO;
820 use crate::foooo::Point;
822 pub(in super::super) const TWENTY_NINE: u8 = 29;
825 //- /foo.rs crate:foo
832 pub(super) fn swap(p: crate::Point) -> crate::Point {
833 crate::Point { x: p.y, y: p.x }
837 expect_file!["./test_data/highlight_crate_root.html"],
843 fn test_default_library() {
846 //- minicore: option, iterators
851 let nums = iter::repeat(foo.unwrap());
854 expect_file!["./test_data/highlight_default_library.html"],
860 fn test_associated_function() {
868 pub fn is_static() {}
869 pub fn is_not_static(&self) {}
874 fn t_is_not_static(&self) {}
878 pub fn is_static() {}
879 pub fn is_not_static(&self) {}
882 expect_file!["./test_data/highlight_assoc_functions.html"],
888 fn test_injection() {
891 fn f(ra_fixture: &str) {}
901 expect_file!["./test_data/injection.html"],
906 /// Highlights the code given by the `ra_fixture` argument, renders the
907 /// result as HTML, and compares it with the HTML file given as `snapshot`.
908 /// Note that the `snapshot` file is overwritten by the rendered HTML.
909 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
910 let (analysis, file_id) = fixture::file(ra_fixture);
911 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
912 expect.assert_eq(actual_html)