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};
71 fn baz(self, f: FooCopy) -> u32 {
79 fn quop(&self) -> u32 {
88 fn foo<'a, T>() -> T {
96 fn const_param<const FOO: usize>() -> usize {
101 fn baz<F: Fn() -> ()>(f: F) {
105 fn foobar() -> impl Copy {}
111 macro_rules! def_fn {
112 ($($tt:tt)*) => {$($tt)*}
121 macro_rules! dont_color_me_braces {
131 macro_rules! keyword_frag {
132 ($type:ty) => ($type)
135 macro with_args($i:ident) {
147 println!("Hello, {}!", 92);
148 dont_color_me_braces!();
150 let mut vec = Vec::new();
153 vec.push(Foo { x, y: 1 });
167 let Foo { x: z, y } = Foo { x: z, y };
171 let mut foo = Foo { x, y: x };
172 let foo2 = Foo { x, y: x };
177 let mut copy = FooCopy { x };
203 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
205 None => unimplemented!(),
211 async fn learn_and_sing() {
212 let song = learn_song().await;
213 sing_song(song).await;
216 async fn async_main() {
217 let f1 = learn_and_sing();
219 futures::join!(f1, f2);
223 let bob = foo::Person {
225 age: foo::consts::NUMBER,
228 let control_flow = foo::identity(foo::ControlFlow::Continue);
230 if control_flow.should_die() {
235 pub enum Bool { True, False }
238 pub const fn to_primitive(self) -> bool {
239 matches!(self, Self::True)
242 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
251 <T as Baz>::Qux: Bar {}
253 //- /foo.rs crate:foo
255 pub name: &'static str,
259 pub enum ControlFlow {
265 pub fn should_die(self) -> bool {
266 matches!(self, ControlFlow::Die)
270 pub fn identity<T>(x: T) -> T { x }
273 pub const NUMBER: i64 = 92;
283 expect_file!["./test_data/highlighting.html"],
289 fn test_rainbow_highlighting() {
294 let x = hello.to_string();
295 let y = hello.to_string();
297 let x = "other color please!";
298 let y = x.to_string();
302 let mut hello = "hello";
306 expect_file!["./test_data/rainbow_highlighting.html"],
312 fn benchmark_syntax_highlighting_long_struct() {
313 if skip_slow_tests() {
317 let fixture = bench_fixture::big_struct();
318 let (analysis, file_id) = fixture::file(&fixture);
321 let _pt = bench("syntax highlighting long struct");
326 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
329 assert_eq!(hash, 2001);
333 fn syntax_highlighting_not_quadratic() {
334 if skip_slow_tests() {
338 let mut al = AssertLinear::default();
339 while al.next_round() {
343 let fixture = bench_fixture::big_struct_n(n);
344 let (analysis, file_id) = fixture::file(&fixture);
346 let time = Instant::now();
352 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
354 assert!(hash > n as usize);
356 let elapsed = time.elapsed();
357 al.sample(n as f64, elapsed.as_millis() as f64);
363 fn benchmark_syntax_highlighting_parser() {
364 if skip_slow_tests() {
368 let fixture = bench_fixture::glorious_old_parser();
369 let (analysis, file_id) = fixture::file(&fixture);
372 let _pt = bench("syntax highlighting parser");
377 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
380 assert_eq!(hash, 1616);
385 let (analysis, file_id) = fixture::file(
387 #[derive(Clone, Debug)]
396 let highlights = &analysis
397 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
400 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
404 fn test_flattening() {
407 fn fixture(ra_fixture: &str) {}
413 println!("2 + 2 = {}", 4);
419 expect_file!["./test_data/highlight_injection.html"],
426 let (analysis, file_id) = fixture::file(
433 let _ = analysis.highlight(file_id).unwrap();
437 fn test_string_highlighting() {
438 // The format string detection is based on macro-expansion,
439 // thus, we have to copy the macro definition from `std`
442 macro_rules! println {
444 $crate::io::_print($crate::format_args_nl!($($arg)*));
447 #[rustc_builtin_macro]
449 macro_rules! format_args {}
450 #[rustc_builtin_macro]
452 macro_rules! const_format_args {}
453 #[rustc_builtin_macro]
455 macro_rules! format_args_nl {}
458 pub macro panic_2015 {
460 $crate::panicking::panic("explicit panic")
462 ($msg:literal $(,)?) => (
463 $crate::panicking::panic($msg)
465 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
466 ($msg:expr $(,)?) => (
467 $crate::panicking::panic_str($msg)
469 // Special-case the single-argument case for const_panic.
470 ("{}", $arg:expr $(,)?) => (
471 $crate::panicking::panic_display(&$arg)
473 ($fmt:expr, $($arg:tt)+) => (
474 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
479 #[rustc_builtin_macro(std_panic)]
481 macro_rules! panic {}
482 #[rustc_builtin_macro]
483 macro_rules! assert {}
484 #[rustc_builtin_macro]
488 () => ($crate::panic!("not yet implemented"));
489 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
493 // from https://doc.rust-lang.org/std/fmt/index.html
494 println!("Hello"); // => "Hello"
495 println!("Hello, {}!", "world"); // => "Hello, world!"
496 println!("The number is {}", 1); // => "The number is 1"
497 println!("{:?}", (3, 4)); // => "(3, 4)"
498 println!("{value}", value=4); // => "4"
499 println!("{} {}", 1, 2); // => "1 2"
500 println!("{:04}", 42); // => "0042" with leading zerosV
501 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
502 println!("{argument}", argument = "test"); // => "test"
503 println!("{name} {}", 1, name = 2); // => "2 1"
504 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
505 println!("{{{}}}", 2); // => "{2}"
506 println!("Hello {:5}!", "x");
507 println!("Hello {:1$}!", "x", 5);
508 println!("Hello {1:0$}!", 5, "x");
509 println!("Hello {:width$}!", "x", width = 5);
510 println!("Hello {:<5}!", "x");
511 println!("Hello {:-<5}!", "x");
512 println!("Hello {:^5}!", "x");
513 println!("Hello {:>5}!", "x");
514 println!("Hello {:+}!", 5);
515 println!("{:#x}!", 27);
516 println!("Hello {:05}!", 5);
517 println!("Hello {:05}!", -5);
518 println!("{:#010x}!", 27);
519 println!("Hello {0} is {1:.5}", "x", 0.01);
520 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
521 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
522 println!("Hello {} is {:.*}", "x", 5, 0.01);
523 println!("Hello {} is {2:.*}", "x", 5, 0.01);
524 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
525 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
526 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
527 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
528 println!("Hello {{}}");
529 println!("{{ Hello");
531 println!(r"Hello, {}!", "world");
534 println!("Hello\nWorld");
535 println!("\u{48}\x65\x6C\x6C\x6F World");
537 println!("{\x41}", A = 92);
538 println!("{ничоси}", ничоси = 92);
540 println!("{:x?} {} ", thingy, n2);
542 panic!("more {}", 1);
543 assert!(true, "{}", 1);
544 assert!(true, "{} asdasd", 1);
546 asm!("mov eax, {0}");
547 format_args!(concat!("{}"), "{}");
550 expect_file!["./test_data/highlight_strings.html"],
556 fn test_unsafe_highlighting() {
559 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
560 static GLOBAL: Struct = Struct { field: 0 };
561 unsafe fn unsafe_fn() {}
568 struct Struct { field: i32 }
570 unsafe fn unsafe_method(&self) {}
578 unsafe trait UnsafeTrait {}
579 unsafe impl UnsafeTrait for Packed {}
580 impl !UnsafeTrait for () {}
582 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
585 fn calls_autoref(&self);
588 impl DoTheAutoref for u16 {
589 fn calls_autoref(&self) {}
593 let x = &5 as *const _ as *const usize;
594 let u = Union { b: 0 };
596 // unsafe fn and method calls
600 Union { b: 0 } => (),
603 Struct { field: 0 }.unsafe_method();
608 // unsafe access to a static mut
612 // unsafe ref of packed fields
613 let packed = Packed { a: 0 };
615 let ref a = packed.a;
616 let Packed { ref a } = packed;
617 let Packed { a: ref _a } = packed;
619 // unsafe auto ref of packed field
620 packed.a.calls_autoref();
625 expect_file!["./test_data/highlight_unsafe.html"],
631 fn test_highlight_doc_comment() {
634 //! This is a module to test doc injection.
640 /// let _ = "early doctests should not go boom";
646 /// This is an impl with a code block.
659 pub const bar: bool = true;
661 /// Constructs a new `Foo`.
666 /// # #![allow(unused_mut)]
667 /// let mut foo: Foo = Foo::new();
669 pub const fn new() -> Foo {
673 /// `bar` method on `Foo`.
680 /// let foo = Foo::new();
682 /// // calls bar on foo
683 /// assert!(foo.bar());
685 /// let bar = foo.bar || Foo::bar;
690 /// let multi_line_string = "Foo
697 /// let foobar = Foo::new().bar();
703 pub fn foo(&self) -> bool {
708 /// [`Foo`](Foo) is a struct
709 /// This function is > [`all_the_links`](all_the_links) <
710 /// [`noop`](noop) is a macro below
711 /// [`Item`] is a struct in the module [`module`]
713 /// [`Item`]: module::Item
714 /// [mix_and_match]: ThisShouldntResolve
715 pub fn all_the_links() {}
722 /// macro_rules! noop { ($expr:expr) => { $expr }}
732 /// let _ = example(&[1, 2, 3]);
737 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
741 #[cfg_attr(feature = "alloc", doc = "```rust")]
742 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
743 /// let _ = example(&alloc::vec![1, 2, 3]);
745 pub fn mix_and_match() {}
748 It is beyond me why you'd use these when you got ///
750 let _ = example(&[1, 2, 3]);
752 [`block_comments2`] tests these with indentation
754 pub fn block_comments() {}
757 Really, I don't get it
759 let _ = example(&[1, 2, 3]);
761 [`block_comments`] tests these without indentation
763 pub fn block_comments2() {}
766 expect_file!["./test_data/highlight_doctest.html"],
772 fn test_extern_crate() {
775 //- /main.rs crate:main deps:std,alloc
777 extern crate alloc as abc;
778 //- /std/lib.rs crate:std
780 //- /alloc/lib.rs crate:alloc
783 expect_file!["./test_data/highlight_extern_crate.html"],
789 fn test_crate_root() {
792 //- minicore: iterators
793 //- /main.rs crate:main deps:foo
797 pub const NINETY_TWO: u8 = 92;
801 pub(crate) fn main() {
802 let baz = iter::repeat(92);
806 pub(in super) const FORTY_TWO: u8 = 42;
809 use super::super::NINETY_TWO;
810 use crate::foooo::Point;
812 pub(in super::super) const TWENTY_NINE: u8 = 29;
815 //- /foo.rs crate:foo
822 pub(super) fn swap(p: crate::Point) -> crate::Point {
823 crate::Point { x: p.y, y: p.x }
827 expect_file!["./test_data/highlight_crate_root.html"],
833 fn test_default_library() {
836 //- minicore: option, iterators
841 let nums = iter::repeat(foo.unwrap());
844 expect_file!["./test_data/highlight_default_library.html"],
850 fn test_associated_function() {
858 pub fn is_static() {}
859 pub fn is_not_static(&self) {}
864 fn t_is_not_static(&self) {}
868 pub fn is_static() {}
869 pub fn is_not_static(&self) {}
872 expect_file!["./test_data/highlight_assoc_functions.html"],
878 fn test_injection() {
881 fn f(ra_fixture: &str) {}
891 expect_file!["./test_data/injection.html"],
896 /// Highlights the code given by the `ra_fixture` argument, renders the
897 /// result as HTML, and compares it with the HTML file given as `snapshot`.
898 /// Note that the `snapshot` file is overwritten by the rendered HTML.
899 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
900 let (analysis, file_id) = fixture::file(ra_fixture);
901 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
902 expect.assert_eq(actual_html)