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, HighlightConfig, HlTag, TextRange};
9 const HL_CONFIG: HighlightConfig = HighlightConfig {
12 specialize_punctuation: true,
13 specialize_operator: true,
15 inject_doc_comment: true,
17 syntactic_name_ref_highlighting: false,
24 //- proc_macros: identity
25 //- minicore: derive, copy
28 #[proc_macros::identity]
30 /// This is a doc comment
31 // This is a normal comment
32 /// This is a doc comment
34 // This is another normal comment
35 /// This is another doc comment
36 // This is another normal comment
38 // The reason for these being here is to test AttrIds
41 expect_file!["./test_data/highlight_attributes.html"],
50 //- proc_macros: mirror
51 proc_macros::mirror! {
58 ($($tt:tt)*) => {$($tt)*}
67 macro_rules! dont_color_me_braces {
77 /// textually shadow previous definition
84 macro_rules! keyword_frag {
88 macro with_args($i:ident) {
99 println!("Hello, {}!", 92);
100 dont_color_me_braces!();
104 expect_file!["./test_data/highlight_macros.html"],
109 /// If what you want to test feels like a specific entity consider making a new test instead,
110 /// this test fixture here in fact should shrink instead of grow ideally.
112 fn test_highlighting() {
115 //- minicore: derive, copy
116 //- /main.rs crate:main deps:foo
117 use inner::{self as inner_mod};
122 pub trait FnOnce<Args> {}
125 pub trait FnMut<Args>: FnOnce<Args> {}
128 pub trait Fn<Args>: FnMut<Args> {}
136 fn bar(&self) -> i32;
140 fn bar(&self) -> i32 {
146 fn baz(mut self, f: Foo) -> i32 {
154 fn quop(&self) -> i32 {
159 use self::FooCopy::{self as BarCopy};
167 fn baz(self, f: FooCopy) -> u32 {
175 fn quop(&self) -> u32 {
184 fn foo<'a, T>() -> T {
192 fn const_param<const FOO: usize>() -> usize {
193 const_param::<{ FOO }>();
198 fn baz<F: Fn() -> ()>(f: F) {
202 fn foobar() -> impl Copy {}
215 let Foo { x: z, y } = Foo { x: z, y };
219 let mut foo = Foo { x, y: x };
220 let foo2 = Foo { x, y: x };
225 let mut copy = FooCopy { x };
251 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
253 None => unimplemented!(),
259 async fn learn_and_sing() {
260 let song = learn_song().await;
261 sing_song(song).await;
264 async fn async_main() {
265 let f1 = learn_and_sing();
267 futures::join!(f1, f2);
271 let bob = foo::Person {
273 age: foo::consts::NUMBER,
276 let control_flow = foo::identity(foo::ControlFlow::Continue);
278 if control_flow.should_die() {
283 pub enum Bool { True, False }
286 pub const fn to_primitive(self) -> bool {
290 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
299 <T as Baz>::Qux: Bar {}
301 fn gp_shadows_trait<Baz: Bar>() {
305 //- /foo.rs crate:foo
307 pub name: &'static str,
311 pub enum ControlFlow {
317 pub fn should_die(self) -> bool {
318 matches!(self, ControlFlow::Die)
322 pub fn identity<T>(x: T) -> T { x }
325 pub const NUMBER: i64 = 92;
334 expect_file!["./test_data/highlight_general.html"],
340 fn test_lifetime_highlighting() {
346 struct Foo<'a, 'b, 'c> where 'a: 'a, 'static: 'static {
350 impl<'a> Foo<'_, 'a, 'static>
356 expect_file!["./test_data/highlight_lifetimes.html"],
362 fn test_keyword_highlighting() {
377 struct __ where Self:;
380 expect_file!["./test_data/highlight_keywords.html"],
386 fn test_string_highlighting() {
387 // The format string detection is based on macro-expansion,
388 // thus, we have to copy the macro definition from `std`
391 macro_rules! println {
393 $crate::io::_print($crate::format_args_nl!($($arg)*));
396 #[rustc_builtin_macro]
398 macro_rules! format_args {}
399 #[rustc_builtin_macro]
401 macro_rules! const_format_args {}
402 #[rustc_builtin_macro]
404 macro_rules! format_args_nl {}
407 pub macro panic_2015 {
409 $crate::panicking::panic("explicit panic")
411 ($msg:literal $(,)?) => (
412 $crate::panicking::panic($msg)
414 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
415 ($msg:expr $(,)?) => (
416 $crate::panicking::panic_str($msg)
418 // Special-case the single-argument case for const_panic.
419 ("{}", $arg:expr $(,)?) => (
420 $crate::panicking::panic_display(&$arg)
422 ($fmt:expr, $($arg:tt)+) => (
423 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
428 #[rustc_builtin_macro(std_panic)]
430 macro_rules! panic {}
431 #[rustc_builtin_macro]
432 macro_rules! assert {}
433 #[rustc_builtin_macro]
437 () => ($crate::panic!("not yet implemented"));
438 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
442 println!("Hello {{Hello}}");
443 // from https://doc.rust-lang.org/std/fmt/index.html
444 println!("Hello"); // => "Hello"
445 println!("Hello, {}!", "world"); // => "Hello, world!"
446 println!("The number is {}", 1); // => "The number is 1"
447 println!("{:?}", (3, 4)); // => "(3, 4)"
448 println!("{value}", value=4); // => "4"
449 println!("{} {}", 1, 2); // => "1 2"
450 println!("{:04}", 42); // => "0042" with leading zerosV
451 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
452 println!("{argument}", argument = "test"); // => "test"
453 println!("{name} {}", 1, name = 2); // => "2 1"
454 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
455 println!("{{{}}}", 2); // => "{2}"
456 println!("Hello {:5}!", "x");
457 println!("Hello {:1$}!", "x", 5);
458 println!("Hello {1:0$}!", 5, "x");
459 println!("Hello {:width$}!", "x", width = 5);
460 println!("Hello {:<5}!", "x");
461 println!("Hello {:-<5}!", "x");
462 println!("Hello {:^5}!", "x");
463 println!("Hello {:>5}!", "x");
464 println!("Hello {:+}!", 5);
465 println!("{:#x}!", 27);
466 println!("Hello {:05}!", 5);
467 println!("Hello {:05}!", -5);
468 println!("{:#010x}!", 27);
469 println!("Hello {0} is {1:.5}", "x", 0.01);
470 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
471 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
472 println!("Hello {} is {:.*}", "x", 5, 0.01);
473 println!("Hello {} is {2:.*}", "x", 5, 0.01);
474 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
475 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
476 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
477 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
482 println!("Hello {{}}");
483 println!("{{ Hello");
484 println!("Hello }}");
485 println!("{{Hello}}");
486 println!("{{ Hello }}");
487 println!("{{Hello }}");
488 println!("{{ Hello}}");
490 println!(r"Hello, {}!", "world");
493 println!("Hello\nWorld");
494 println!("\u{48}\x65\x6C\x6C\x6F World");
496 let _ = "\x28\x28\x00\x63\n";
497 let _ = b"\x28\x28\x00\x63\n";
499 println!("{\x41}", A = 92);
500 println!("{ничоси}", ничоси = 92);
502 println!("{:x?} {} ", thingy, n2);
504 panic!("more {}", 1);
505 assert!(true, "{}", 1);
506 assert!(true, "{} asdasd", 1);
508 asm!("mov eax, {0}");
509 format_args!(concat!("{}"), "{}");
511 expect_file!["./test_data/highlight_strings.html"],
517 fn test_unsafe_highlighting() {
525 macro_rules! unsafe_deref {
530 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
531 static GLOBAL: Struct = Struct { field: 0 };
532 unsafe fn unsafe_fn() {}
539 struct Struct { field: i32 }
541 unsafe fn unsafe_method(&self) {}
549 unsafe trait UnsafeTrait {}
550 unsafe impl UnsafeTrait for Packed {}
551 impl !UnsafeTrait for () {}
553 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
556 fn calls_autoref(&self);
559 impl DoTheAutoref for u16 {
560 fn calls_autoref(&self) {}
564 let x = &5 as *const _ as *const usize;
565 let u = Union { b: 0 };
568 unsafe { unsafe_deref!() }
573 id! { unsafe_deref!() };
575 // unsafe fn and method calls
579 Union { b: 0 } => (),
582 Struct { field: 0 }.unsafe_method();
587 // unsafe access to a static mut
591 // unsafe ref of packed fields
592 let packed = Packed { a: 0 };
594 let ref a = packed.a;
595 let Packed { ref a } = packed;
596 let Packed { a: ref _a } = packed;
598 // unsafe auto ref of packed field
599 packed.a.calls_autoref();
603 expect_file!["./test_data/highlight_unsafe.html"],
609 fn test_highlight_doc_comment() {
613 //! This is a module to test doc injection.
621 /// let _ = "early doctests should not go boom";
627 /// This is an impl of [`Foo`] with a code block.
640 pub const bar: bool = true;
642 /// Constructs a new `Foo`.
647 /// # #![allow(unused_mut)]
648 /// let mut foo: Foo = Foo::new();
650 pub const fn new() -> Foo {
654 /// `bar` method on `Foo`.
661 /// let foo = Foo::new();
663 /// // calls bar on foo
664 /// assert!(foo.bar());
666 /// let bar = foo.bar || Foo::bar;
671 /// let multi_line_string = "Foo
678 /// let foobar = Foo::new().bar();
682 /// // code block with tilde.
683 /// let foobar = Foo::new().bar();
688 /// fn foo<T, const X: usize>(arg: i32) {
696 pub fn foo(&self) -> bool {
701 /// [`Foo`](Foo) is a struct
702 /// This function is > [`all_the_links`](all_the_links) <
703 /// [`noop`](noop) is a macro below
704 /// [`Item`] is a struct in the module [`module`]
706 /// [`Item`]: module::Item
707 /// [mix_and_match]: ThisShouldntResolve
708 pub fn all_the_links() {}
715 /// macro_rules! noop { ($expr:expr) => { $expr }}
725 /// let _ = example(&[1, 2, 3]);
730 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
734 #[cfg_attr(feature = "alloc", doc = "```rust")]
735 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
736 /// let _ = example(&alloc::vec![1, 2, 3]);
738 pub fn mix_and_match() {}
741 It is beyond me why you'd use these when you got ///
743 let _ = example(&[1, 2, 3]);
745 [`block_comments2`] tests these with indentation
747 pub fn block_comments() {}
750 Really, I don't get it
752 let _ = example(&[1, 2, 3]);
754 [`block_comments`] tests these without indentation
756 pub fn block_comments2() {}
758 //- /outline_module.rs
759 //! This is an outline module whose purpose is to test that its inline attribute injection does not
760 //! spill into its parent.
765 expect_file!["./test_data/highlight_doctest.html"],
771 fn test_extern_crate() {
774 //- /main.rs crate:main deps:std,alloc
776 extern crate alloc as abc;
777 //- /std/lib.rs crate:std
779 //- /alloc/lib.rs crate:alloc
782 expect_file!["./test_data/highlight_extern_crate.html"],
788 fn test_crate_root() {
791 //- minicore: iterators
792 //- /main.rs crate:main deps:foo
796 pub const NINETY_TWO: u8 = 92;
800 pub(crate) fn main() {
801 let baz = iter::repeat(92);
805 pub(in super) const FORTY_TWO: u8 = 42;
808 use super::super::NINETY_TWO;
809 use crate::foooo::Point;
811 pub(in super::super) const TWENTY_NINE: u8 = 29;
814 //- /foo.rs crate:foo
821 pub(super) fn swap(p: crate::Point) -> crate::Point {
822 crate::Point { x: p.y, y: p.x }
826 expect_file!["./test_data/highlight_crate_root.html"],
832 fn test_default_library() {
835 //- minicore: option, iterators
840 let nums = iter::repeat(foo.unwrap());
843 expect_file!["./test_data/highlight_default_library.html"],
849 fn test_associated_function() {
857 pub fn is_static() {}
858 pub fn is_not_static(&self) {}
863 fn t_is_not_static(&self) {}
867 pub fn is_static() {}
868 pub fn is_not_static(&self) {}
871 expect_file!["./test_data/highlight_assoc_functions.html"],
877 fn test_injection() {
880 fn fixture(ra_fixture: &str) {}
886 println!("2 + 2 = {}", 4);
899 expect_file!["./test_data/highlight_injection.html"],
905 fn test_operators() {
909 1 + 1 - 1 * 1 / 1 % 1 | 1 & 1 ! 1 ^ 1 >> 1 << 1;
923 expect_file!["./test_data/highlight_operators.html"],
929 fn test_mod_hl_injection() {
934 //! This is an intra doc injection test for modules
936 //! This is an intra doc injection test for modules
939 //- /lib.rs crate:foo
940 /// [crate::foo::Struct]
941 /// This is an intra doc injection test for modules
942 /// [crate::foo::Struct]
943 /// This is an intra doc injection test for modules
946 expect_file!["./test_data/highlight_module_docs_inline.html"],
951 //- /lib.rs crate:foo
952 /// [crate::foo::Struct]
953 /// This is an intra doc injection test for modules
954 /// [crate::foo::Struct]
955 /// This is an intra doc injection test for modules
959 //! This is an intra doc injection test for modules
961 //! This is an intra doc injection test for modules
965 expect_file!["./test_data/highlight_module_docs_outline.html"],
972 not(all(unix, target_pointer_width = "64")),
973 ignore = "depends on `DefaultHasher` outputs"
975 fn test_rainbow_highlighting() {
980 let x = hello.to_string();
981 let y = hello.to_string();
983 let x = "other color please!";
984 let y = x.to_string();
988 let mut hello = "hello";
991 expect_file!["./test_data/highlight_rainbow.html"],
998 let (analysis, file_id) = fixture::file(
1000 #[derive(Clone, Debug)]
1009 let highlights = &analysis
1012 FileRange { file_id, range: TextRange::at(45.into(), 1.into()) },
1016 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
1020 fn ranges_sorted() {
1021 let (analysis, file_id) = fixture::file(
1024 macro_rules! test {}
1028 let _ = analysis.highlight(HL_CONFIG, file_id).unwrap();
1031 /// Highlights the code given by the `ra_fixture` argument, renders the
1032 /// result as HTML, and compares it with the HTML file given as `snapshot`.
1033 /// Note that the `snapshot` file is overwritten by the rendered HTML.
1034 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
1035 let (analysis, file_id) = fixture::file(ra_fixture.trim());
1036 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
1037 expect.assert_eq(actual_html)
1041 fn benchmark_syntax_highlighting_long_struct() {
1042 if skip_slow_tests() {
1046 let fixture = bench_fixture::big_struct();
1047 let (analysis, file_id) = fixture::file(&fixture);
1050 let _pt = bench("syntax highlighting long struct");
1052 .highlight(HL_CONFIG, file_id)
1055 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1058 assert_eq!(hash, 2001);
1062 fn syntax_highlighting_not_quadratic() {
1063 if skip_slow_tests() {
1067 let mut al = AssertLinear::default();
1068 while al.next_round() {
1072 let fixture = bench_fixture::big_struct_n(n);
1073 let (analysis, file_id) = fixture::file(&fixture);
1075 let time = Instant::now();
1078 .highlight(HL_CONFIG, file_id)
1081 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1083 assert!(hash > n as usize);
1085 let elapsed = time.elapsed();
1086 al.sample(n as f64, elapsed.as_millis() as f64);
1092 fn benchmark_syntax_highlighting_parser() {
1093 if skip_slow_tests() {
1097 let fixture = bench_fixture::glorious_old_parser();
1098 let (analysis, file_id) = fixture::file(&fixture);
1101 let _pt = bench("syntax highlighting parser");
1103 .highlight(HL_CONFIG, file_id)
1106 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
1109 assert_eq!(hash, 1609);