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 //- /main.rs crate:main deps:foo
15 use inner::{self as inner_mod};
18 #[rustc_builtin_macro]
21 // Needed for function consuming vs normal
27 #[proc_macros::identity]
30 pub trait FnOnce<Args> {}
33 pub trait FnMut<Args>: FnOnce<Args> {}
36 pub trait Fn<Args>: FnMut<Args> {}
39 proc_macros::mirror! {
46 trait Bar where Self: {
50 impl Bar for Foo where Self: {
51 fn bar(&self) -> i32 {
57 fn baz(mut self, f: Foo) -> i32 {
65 fn quop(&self) -> i32 {
76 fn baz(self, f: FooCopy) -> u32 {
84 fn quop(&self) -> u32 {
93 fn foo<'a, T>() -> T {
101 fn const_param<const FOO: usize>() -> usize {
106 fn baz<F: Fn() -> ()>(f: F) {
110 fn foobar() -> impl Copy {}
116 macro_rules! def_fn {
117 ($($tt:tt)*) => {$($tt)*}
126 macro_rules! dont_color_me_braces {
136 macro_rules! keyword_frag {
137 ($type:ty) => ($type)
140 macro with_args($i:ident) {
152 println!("Hello, {}!", 92);
153 dont_color_me_braces!();
155 let mut vec = Vec::new();
158 vec.push(Foo { x, y: 1 });
172 let Foo { x: z, y } = Foo { x: z, y };
176 let mut foo = Foo { x, y: x };
177 let foo2 = Foo { x, y: x };
182 let mut copy = FooCopy { x };
208 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
210 None => unimplemented!(),
216 async fn learn_and_sing() {
217 let song = learn_song().await;
218 sing_song(song).await;
221 async fn async_main() {
222 let f1 = learn_and_sing();
224 futures::join!(f1, f2);
228 let bob = foo::Person {
230 age: foo::consts::NUMBER,
233 let control_flow = foo::identity(foo::ControlFlow::Continue);
235 if control_flow.should_die() {
240 pub enum Bool { True, False }
243 pub const fn to_primitive(self) -> bool {
244 matches!(self, Self::True)
247 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
249 //- /foo.rs crate:foo
251 pub name: &'static str,
255 pub enum ControlFlow {
261 pub fn should_die(self) -> bool {
262 matches!(self, ControlFlow::Die)
266 pub fn identity<T>(x: T) -> T { x }
269 pub const NUMBER: i64 = 92;
279 expect_file!["./test_data/highlighting.html"],
285 fn test_rainbow_highlighting() {
290 let x = hello.to_string();
291 let y = hello.to_string();
293 let x = "other color please!";
294 let y = x.to_string();
298 let mut hello = "hello";
302 expect_file!["./test_data/rainbow_highlighting.html"],
308 fn benchmark_syntax_highlighting_long_struct() {
309 if skip_slow_tests() {
313 let fixture = bench_fixture::big_struct();
314 let (analysis, file_id) = fixture::file(&fixture);
317 let _pt = bench("syntax highlighting long struct");
322 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
325 assert_eq!(hash, 2001);
329 fn syntax_highlighting_not_quadratic() {
330 if skip_slow_tests() {
334 let mut al = AssertLinear::default();
335 while al.next_round() {
339 let fixture = bench_fixture::big_struct_n(n);
340 let (analysis, file_id) = fixture::file(&fixture);
342 let time = Instant::now();
348 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
350 assert!(hash > n as usize);
352 let elapsed = time.elapsed();
353 al.sample(n as f64, elapsed.as_millis() as f64);
359 fn benchmark_syntax_highlighting_parser() {
360 if skip_slow_tests() {
364 let fixture = bench_fixture::glorious_old_parser();
365 let (analysis, file_id) = fixture::file(&fixture);
368 let _pt = bench("syntax highlighting parser");
373 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
376 assert_eq!(hash, 1616);
381 let (analysis, file_id) = fixture::file(
383 #[derive(Clone, Debug)]
392 let highlights = &analysis
393 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
396 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
400 fn test_flattening() {
403 fn fixture(ra_fixture: &str) {}
409 println!("2 + 2 = {}", 4);
415 expect_file!["./test_data/highlight_injection.html"],
422 let (analysis, file_id) = fixture::file(
429 let _ = analysis.highlight(file_id).unwrap();
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`
438 macro_rules! println {
440 $crate::io::_print($crate::format_args_nl!($($arg)*));
443 #[rustc_builtin_macro]
445 macro_rules! format_args {}
446 #[rustc_builtin_macro]
448 macro_rules! const_format_args {}
449 #[rustc_builtin_macro]
451 macro_rules! format_args_nl {}
454 pub macro panic_2015 {
456 $crate::panicking::panic("explicit panic")
458 ($msg:literal $(,)?) => (
459 $crate::panicking::panic($msg)
461 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
462 ($msg:expr $(,)?) => (
463 $crate::panicking::panic_str($msg)
465 // Special-case the single-argument case for const_panic.
466 ("{}", $arg:expr $(,)?) => (
467 $crate::panicking::panic_display(&$arg)
469 ($fmt:expr, $($arg:tt)+) => (
470 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
475 #[rustc_builtin_macro(std_panic)]
477 macro_rules! panic {}
478 #[rustc_builtin_macro]
479 macro_rules! assert {}
480 #[rustc_builtin_macro]
484 () => ($crate::panic!("not yet implemented"));
485 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
489 // from https://doc.rust-lang.org/std/fmt/index.html
490 println!("Hello"); // => "Hello"
491 println!("Hello, {}!", "world"); // => "Hello, world!"
492 println!("The number is {}", 1); // => "The number is 1"
493 println!("{:?}", (3, 4)); // => "(3, 4)"
494 println!("{value}", value=4); // => "4"
495 println!("{} {}", 1, 2); // => "1 2"
496 println!("{:04}", 42); // => "0042" with leading zerosV
497 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
498 println!("{argument}", argument = "test"); // => "test"
499 println!("{name} {}", 1, name = 2); // => "2 1"
500 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
501 println!("{{{}}}", 2); // => "{2}"
502 println!("Hello {:5}!", "x");
503 println!("Hello {:1$}!", "x", 5);
504 println!("Hello {1:0$}!", 5, "x");
505 println!("Hello {:width$}!", "x", width = 5);
506 println!("Hello {:<5}!", "x");
507 println!("Hello {:-<5}!", "x");
508 println!("Hello {:^5}!", "x");
509 println!("Hello {:>5}!", "x");
510 println!("Hello {:+}!", 5);
511 println!("{:#x}!", 27);
512 println!("Hello {:05}!", 5);
513 println!("Hello {:05}!", -5);
514 println!("{:#010x}!", 27);
515 println!("Hello {0} is {1:.5}", "x", 0.01);
516 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
517 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
518 println!("Hello {} is {:.*}", "x", 5, 0.01);
519 println!("Hello {} is {2:.*}", "x", 5, 0.01);
520 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
521 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
522 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
523 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
524 println!("Hello {{}}");
525 println!("{{ Hello");
527 println!(r"Hello, {}!", "world");
530 println!("Hello\nWorld");
531 println!("\u{48}\x65\x6C\x6C\x6F World");
533 println!("{\x41}", A = 92);
534 println!("{ничоси}", ничоси = 92);
536 println!("{:x?} {} ", thingy, n2);
538 panic!("more {}", 1);
539 assert!(true, "{}", 1);
540 assert!(true, "{} asdasd", 1);
542 asm!("mov eax, {0}");
543 format_args!(concat!("{}"), "{}");
546 expect_file!["./test_data/highlight_strings.html"],
552 fn test_unsafe_highlighting() {
555 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
556 static GLOBAL: Struct = Struct { field: 0 };
557 unsafe fn unsafe_fn() {}
564 struct Struct { field: i32 }
566 unsafe fn unsafe_method(&self) {}
574 unsafe trait UnsafeTrait {}
575 unsafe impl UnsafeTrait for Packed {}
576 impl !UnsafeTrait for () {}
578 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
581 fn calls_autoref(&self);
584 impl DoTheAutoref for u16 {
585 fn calls_autoref(&self) {}
589 let x = &5 as *const _ as *const usize;
590 let u = Union { b: 0 };
592 // unsafe fn and method calls
596 Union { b: 0 } => (),
599 Struct { field: 0 }.unsafe_method();
604 // unsafe access to a static mut
608 // unsafe ref of packed fields
609 let packed = Packed { a: 0 };
611 let ref a = packed.a;
612 let Packed { ref a } = packed;
613 let Packed { a: ref _a } = packed;
615 // unsafe auto ref of packed field
616 packed.a.calls_autoref();
621 expect_file!["./test_data/highlight_unsafe.html"],
627 fn test_highlight_doc_comment() {
630 //! This is a module to test doc injection.
636 /// let _ = "early doctests should not go boom";
642 /// This is an impl with a code block.
655 pub const bar: bool = true;
657 /// Constructs a new `Foo`.
662 /// # #![allow(unused_mut)]
663 /// let mut foo: Foo = Foo::new();
665 pub const fn new() -> Foo {
669 /// `bar` method on `Foo`.
676 /// let foo = Foo::new();
678 /// // calls bar on foo
679 /// assert!(foo.bar());
681 /// let bar = foo.bar || Foo::bar;
686 /// let multi_line_string = "Foo
693 /// let foobar = Foo::new().bar();
699 pub fn foo(&self) -> bool {
704 /// [`Foo`](Foo) is a struct
705 /// This function is > [`all_the_links`](all_the_links) <
706 /// [`noop`](noop) is a macro below
707 /// [`Item`] is a struct in the module [`module`]
709 /// [`Item`]: module::Item
710 /// [mix_and_match]: ThisShouldntResolve
711 pub fn all_the_links() {}
727 /// let _ = example(&[1, 2, 3]);
732 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
736 #[cfg_attr(feature = "alloc", doc = "```rust")]
737 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
738 /// let _ = example(&alloc::vec![1, 2, 3]);
740 pub fn mix_and_match() {}
743 It is beyond me why you'd use these when you got ///
745 let _ = example(&[1, 2, 3]);
747 [`block_comments2`] tests these with indentation
749 pub fn block_comments() {}
752 Really, I don't get it
754 let _ = example(&[1, 2, 3]);
756 [`block_comments`] tests these without indentation
758 pub fn block_comments2() {}
761 expect_file!["./test_data/highlight_doctest.html"],
767 fn test_extern_crate() {
770 //- /main.rs crate:main deps:std,alloc
772 extern crate alloc as abc;
773 //- /std/lib.rs crate:std
775 //- /alloc/lib.rs crate:alloc
778 expect_file!["./test_data/highlight_extern_crate.html"],
784 fn test_crate_root() {
787 //- minicore: iterators
788 //- /main.rs crate:main deps:foo
792 pub const NINETY_TWO: u8 = 92;
796 pub(crate) fn main() {
797 let baz = iter::repeat(92);
801 pub(in super) const FORTY_TWO: u8 = 42;
804 use super::super::NINETY_TWO;
805 use crate::foooo::Point;
807 pub(in super::super) const TWENTY_NINE: u8 = 29;
810 //- /foo.rs crate:foo
817 pub(super) fn swap(p: crate::Point) -> crate::Point {
818 crate::Point { x: p.y, y: p.x }
822 expect_file!["./test_data/highlight_crate_root.html"],
828 fn test_default_library() {
831 //- minicore: option, iterators
836 let nums = iter::repeat(foo.unwrap());
839 expect_file!["./test_data/highlight_default_library.html"],
845 fn test_associated_function() {
853 pub fn is_static() {}
854 pub fn is_not_static(&self) {}
859 fn t_is_not_static(&self) {}
863 pub fn is_static() {}
864 pub fn is_not_static(&self) {}
867 expect_file!["./test_data/highlight_assoc_functions.html"],
873 fn test_injection() {
876 fn f(ra_fixture: &str) {}
886 expect_file!["./test_data/injection.html"],
891 /// Highlights the code given by the `ra_fixture` argument, renders the
892 /// result as HTML, and compares it with the HTML file given as `snapshot`.
893 /// Note that the `snapshot` file is overwritten by the rendered HTML.
894 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
895 let (analysis, file_id) = fixture::file(ra_fixture);
896 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
897 expect.assert_eq(actual_html)