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};
13 //- proc_macros: identity
14 //- minicore: derive, copy
17 #[proc_macros::identity]
19 /// This is a doc comment
20 // This is a normal comment
21 /// This is a doc comment
23 // This is another normal comment
24 /// This is another doc comment
25 // This is another normal comment
27 // The reason for these being here is to test AttrIds
30 expect_file!["./test_data/highlight_attributes.html"],
39 //- proc_macros: mirror
40 proc_macros::mirror! {
47 ($($tt:tt)*) => {$($tt)*}
56 macro_rules! dont_color_me_braces {
66 /// textually shadow previous definition
73 macro_rules! keyword_frag {
77 macro with_args($i:ident) {
88 println!("Hello, {}!", 92);
89 dont_color_me_braces!();
93 expect_file!["./test_data/highlight_macros.html"],
98 /// If what you want to test feels like a specific entity consider making a new test instead,
99 /// this test fixture here in fact should shrink instead of grow ideally.
101 fn test_highlighting() {
104 //- minicore: derive, copy
105 //- /main.rs crate:main deps:foo
106 use inner::{self as inner_mod};
111 pub trait FnOnce<Args> {}
114 pub trait FnMut<Args>: FnOnce<Args> {}
117 pub trait Fn<Args>: FnMut<Args> {}
125 fn bar(&self) -> i32;
129 fn bar(&self) -> i32 {
135 fn baz(mut self, f: Foo) -> i32 {
143 fn quop(&self) -> i32 {
148 use self::FooCopy::{self as BarCopy};
156 fn baz(self, f: FooCopy) -> u32 {
164 fn quop(&self) -> u32 {
173 fn foo<'a, T>() -> T {
181 fn const_param<const FOO: usize>() -> usize {
182 const_param::<{ FOO }>();
187 fn baz<F: Fn() -> ()>(f: F) {
191 fn foobar() -> impl Copy {}
204 let Foo { x: z, y } = Foo { x: z, y };
208 let mut foo = Foo { x, y: x };
209 let foo2 = Foo { x, y: x };
214 let mut copy = FooCopy { x };
240 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
242 None => unimplemented!(),
248 async fn learn_and_sing() {
249 let song = learn_song().await;
250 sing_song(song).await;
253 async fn async_main() {
254 let f1 = learn_and_sing();
256 futures::join!(f1, f2);
260 let bob = foo::Person {
262 age: foo::consts::NUMBER,
265 let control_flow = foo::identity(foo::ControlFlow::Continue);
267 if control_flow.should_die() {
272 pub enum Bool { True, False }
275 pub const fn to_primitive(self) -> bool {
279 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
288 <T as Baz>::Qux: Bar {}
290 fn gp_shadows_trait<Baz: Bar>() {
294 //- /foo.rs crate:foo
296 pub name: &'static str,
300 pub enum ControlFlow {
306 pub fn should_die(self) -> bool {
307 matches!(self, ControlFlow::Die)
311 pub fn identity<T>(x: T) -> T { x }
314 pub const NUMBER: i64 = 92;
323 expect_file!["./test_data/highlight_general.html"],
329 fn test_lifetime_highlighting() {
335 struct Foo<'a, 'b, 'c> where 'a: 'a, 'static: 'static {
339 impl<'a> Foo<'_, 'a, 'static>
345 expect_file!["./test_data/highlight_lifetimes.html"],
351 fn test_keyword_highlighting() {
366 struct __ where Self:;
369 expect_file!["./test_data/highlight_keywords.html"],
375 fn test_string_highlighting() {
376 // The format string detection is based on macro-expansion,
377 // thus, we have to copy the macro definition from `std`
380 macro_rules! println {
382 $crate::io::_print($crate::format_args_nl!($($arg)*));
385 #[rustc_builtin_macro]
387 macro_rules! format_args {}
388 #[rustc_builtin_macro]
390 macro_rules! const_format_args {}
391 #[rustc_builtin_macro]
393 macro_rules! format_args_nl {}
396 pub macro panic_2015 {
398 $crate::panicking::panic("explicit panic")
400 ($msg:literal $(,)?) => (
401 $crate::panicking::panic($msg)
403 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
404 ($msg:expr $(,)?) => (
405 $crate::panicking::panic_str($msg)
407 // Special-case the single-argument case for const_panic.
408 ("{}", $arg:expr $(,)?) => (
409 $crate::panicking::panic_display(&$arg)
411 ($fmt:expr, $($arg:tt)+) => (
412 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
417 #[rustc_builtin_macro(std_panic)]
419 macro_rules! panic {}
420 #[rustc_builtin_macro]
421 macro_rules! assert {}
422 #[rustc_builtin_macro]
426 () => ($crate::panic!("not yet implemented"));
427 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
431 println!("Hello {{Hello}}");
432 // from https://doc.rust-lang.org/std/fmt/index.html
433 println!("Hello"); // => "Hello"
434 println!("Hello, {}!", "world"); // => "Hello, world!"
435 println!("The number is {}", 1); // => "The number is 1"
436 println!("{:?}", (3, 4)); // => "(3, 4)"
437 println!("{value}", value=4); // => "4"
438 println!("{} {}", 1, 2); // => "1 2"
439 println!("{:04}", 42); // => "0042" with leading zerosV
440 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
441 println!("{argument}", argument = "test"); // => "test"
442 println!("{name} {}", 1, name = 2); // => "2 1"
443 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
444 println!("{{{}}}", 2); // => "{2}"
445 println!("Hello {:5}!", "x");
446 println!("Hello {:1$}!", "x", 5);
447 println!("Hello {1:0$}!", 5, "x");
448 println!("Hello {:width$}!", "x", width = 5);
449 println!("Hello {:<5}!", "x");
450 println!("Hello {:-<5}!", "x");
451 println!("Hello {:^5}!", "x");
452 println!("Hello {:>5}!", "x");
453 println!("Hello {:+}!", 5);
454 println!("{:#x}!", 27);
455 println!("Hello {:05}!", 5);
456 println!("Hello {:05}!", -5);
457 println!("{:#010x}!", 27);
458 println!("Hello {0} is {1:.5}", "x", 0.01);
459 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
460 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
461 println!("Hello {} is {:.*}", "x", 5, 0.01);
462 println!("Hello {} is {2:.*}", "x", 5, 0.01);
463 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
464 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
465 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
466 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
471 println!("Hello {{}}");
472 println!("{{ Hello");
473 println!("Hello }}");
474 println!("{{Hello}}");
475 println!("{{ Hello }}");
476 println!("{{Hello }}");
477 println!("{{ Hello}}");
479 println!(r"Hello, {}!", "world");
482 println!("Hello\nWorld");
483 println!("\u{48}\x65\x6C\x6C\x6F World");
485 let _ = "\x28\x28\x00\x63\n";
486 let _ = b"\x28\x28\x00\x63\n";
488 println!("{\x41}", A = 92);
489 println!("{ничоси}", ничоси = 92);
491 println!("{:x?} {} ", thingy, n2);
493 panic!("more {}", 1);
494 assert!(true, "{}", 1);
495 assert!(true, "{} asdasd", 1);
497 asm!("mov eax, {0}");
498 format_args!(concat!("{}"), "{}");
500 expect_file!["./test_data/highlight_strings.html"],
506 fn test_unsafe_highlighting() {
514 macro_rules! unsafe_deref {
519 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
520 static GLOBAL: Struct = Struct { field: 0 };
521 unsafe fn unsafe_fn() {}
528 struct Struct { field: i32 }
530 unsafe fn unsafe_method(&self) {}
538 unsafe trait UnsafeTrait {}
539 unsafe impl UnsafeTrait for Packed {}
540 impl !UnsafeTrait for () {}
542 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
545 fn calls_autoref(&self);
548 impl DoTheAutoref for u16 {
549 fn calls_autoref(&self) {}
553 let x = &5 as *const _ as *const usize;
554 let u = Union { b: 0 };
557 unsafe { unsafe_deref!() }
562 id! { unsafe_deref!() };
564 // unsafe fn and method calls
568 Union { b: 0 } => (),
571 Struct { field: 0 }.unsafe_method();
576 // unsafe access to a static mut
580 // unsafe ref of packed fields
581 let packed = Packed { a: 0 };
583 let ref a = packed.a;
584 let Packed { ref a } = packed;
585 let Packed { a: ref _a } = packed;
587 // unsafe auto ref of packed field
588 packed.a.calls_autoref();
592 expect_file!["./test_data/highlight_unsafe.html"],
598 fn test_highlight_doc_comment() {
602 //! This is a module to test doc injection.
610 /// let _ = "early doctests should not go boom";
616 /// This is an impl with a code block.
629 pub const bar: bool = true;
631 /// Constructs a new `Foo`.
636 /// # #![allow(unused_mut)]
637 /// let mut foo: Foo = Foo::new();
639 pub const fn new() -> Foo {
643 /// `bar` method on `Foo`.
650 /// let foo = Foo::new();
652 /// // calls bar on foo
653 /// assert!(foo.bar());
655 /// let bar = foo.bar || Foo::bar;
660 /// let multi_line_string = "Foo
667 /// let foobar = Foo::new().bar();
671 /// // code block with tilde.
672 /// let foobar = Foo::new().bar();
677 /// fn foo<T, const X: usize>(arg: i32) {
685 pub fn foo(&self) -> bool {
690 /// [`Foo`](Foo) is a struct
691 /// This function is > [`all_the_links`](all_the_links) <
692 /// [`noop`](noop) is a macro below
693 /// [`Item`] is a struct in the module [`module`]
695 /// [`Item`]: module::Item
696 /// [mix_and_match]: ThisShouldntResolve
697 pub fn all_the_links() {}
704 /// macro_rules! noop { ($expr:expr) => { $expr }}
714 /// let _ = example(&[1, 2, 3]);
719 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
723 #[cfg_attr(feature = "alloc", doc = "```rust")]
724 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
725 /// let _ = example(&alloc::vec![1, 2, 3]);
727 pub fn mix_and_match() {}
730 It is beyond me why you'd use these when you got ///
732 let _ = example(&[1, 2, 3]);
734 [`block_comments2`] tests these with indentation
736 pub fn block_comments() {}
739 Really, I don't get it
741 let _ = example(&[1, 2, 3]);
743 [`block_comments`] tests these without indentation
745 pub fn block_comments2() {}
747 //- /outline_module.rs
748 //! This is an outline module whose purpose is to test that its inline attribute injection does not
749 //! spill into its parent.
754 expect_file!["./test_data/highlight_doctest.html"],
760 fn test_extern_crate() {
763 //- /main.rs crate:main deps:std,alloc
765 extern crate alloc as abc;
766 //- /std/lib.rs crate:std
768 //- /alloc/lib.rs crate:alloc
771 expect_file!["./test_data/highlight_extern_crate.html"],
777 fn test_crate_root() {
780 //- minicore: iterators
781 //- /main.rs crate:main deps:foo
785 pub const NINETY_TWO: u8 = 92;
789 pub(crate) fn main() {
790 let baz = iter::repeat(92);
794 pub(in super) const FORTY_TWO: u8 = 42;
797 use super::super::NINETY_TWO;
798 use crate::foooo::Point;
800 pub(in super::super) const TWENTY_NINE: u8 = 29;
803 //- /foo.rs crate:foo
810 pub(super) fn swap(p: crate::Point) -> crate::Point {
811 crate::Point { x: p.y, y: p.x }
815 expect_file!["./test_data/highlight_crate_root.html"],
821 fn test_default_library() {
824 //- minicore: option, iterators
829 let nums = iter::repeat(foo.unwrap());
832 expect_file!["./test_data/highlight_default_library.html"],
838 fn test_associated_function() {
846 pub fn is_static() {}
847 pub fn is_not_static(&self) {}
852 fn t_is_not_static(&self) {}
856 pub fn is_static() {}
857 pub fn is_not_static(&self) {}
860 expect_file!["./test_data/highlight_assoc_functions.html"],
866 fn test_injection() {
869 fn fixture(ra_fixture: &str) {}
875 println!("2 + 2 = {}", 4);
888 expect_file!["./test_data/highlight_injection.html"],
894 fn test_operators() {
898 1 + 1 - 1 * 1 / 1 % 1 | 1 & 1 ! 1 ^ 1 >> 1 << 1;
912 expect_file!["./test_data/highlight_operators.html"],
918 fn test_mod_hl_injection() {
923 //! This is an intra doc injection test for modules
925 //! This is an intra doc injection test for modules
928 //- /lib.rs crate:foo
929 /// [crate::foo::Struct]
930 /// This is an intra doc injection test for modules
931 /// [crate::foo::Struct]
932 /// This is an intra doc injection test for modules
935 expect_file!["./test_data/highlight_module_docs_inline.html"],
940 //- /lib.rs crate:foo
941 /// [crate::foo::Struct]
942 /// This is an intra doc injection test for modules
943 /// [crate::foo::Struct]
944 /// This is an intra doc injection test for modules
948 //! This is an intra doc injection test for modules
950 //! This is an intra doc injection test for modules
954 expect_file!["./test_data/highlight_module_docs_outline.html"],
961 not(all(unix, target_pointer_width = "64")),
962 ignore = "depends on `DefaultHasher` outputs"
964 fn test_rainbow_highlighting() {
969 let x = hello.to_string();
970 let y = hello.to_string();
972 let x = "other color please!";
973 let y = x.to_string();
977 let mut hello = "hello";
980 expect_file!["./test_data/highlight_rainbow.html"],
987 let (analysis, file_id) = fixture::file(
989 #[derive(Clone, Debug)]
998 let highlights = &analysis
999 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
1002 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
1006 fn ranges_sorted() {
1007 let (analysis, file_id) = fixture::file(
1010 macro_rules! test {}
1014 let _ = analysis.highlight(file_id).unwrap();
1017 /// Highlights the code given by the `ra_fixture` argument, renders the
1018 /// result as HTML, and compares it with the HTML file given as `snapshot`.
1019 /// Note that the `snapshot` file is overwritten by the rendered HTML.
1020 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
1021 let (analysis, file_id) = fixture::file(ra_fixture.trim());
1022 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
1023 expect.assert_eq(actual_html)
1027 fn benchmark_syntax_highlighting_long_struct() {
1028 if skip_slow_tests() {
1032 let fixture = bench_fixture::big_struct();
1033 let (analysis, file_id) = fixture::file(&fixture);
1036 let _pt = bench("syntax highlighting long struct");
1041 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1044 assert_eq!(hash, 2001);
1048 fn syntax_highlighting_not_quadratic() {
1049 if skip_slow_tests() {
1053 let mut al = AssertLinear::default();
1054 while al.next_round() {
1058 let fixture = bench_fixture::big_struct_n(n);
1059 let (analysis, file_id) = fixture::file(&fixture);
1061 let time = Instant::now();
1067 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1069 assert!(hash > n as usize);
1071 let elapsed = time.elapsed();
1072 al.sample(n as f64, elapsed.as_millis() as f64);
1078 fn benchmark_syntax_highlighting_parser() {
1079 if skip_slow_tests() {
1083 let fixture = bench_fixture::glorious_old_parser();
1084 let (analysis, file_id) = fixture::file(&fixture);
1087 let _pt = bench("syntax highlighting parser");
1092 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
1095 assert_eq!(hash, 1609);