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 syntactic_name_ref_highlighting: false,
22 //- proc_macros: identity
23 //- minicore: derive, copy
26 #[proc_macros::identity]
28 /// This is a doc comment
29 // This is a normal comment
30 /// This is a doc comment
32 // This is another normal comment
33 /// This is another doc comment
34 // This is another normal comment
36 // The reason for these being here is to test AttrIds
39 expect_file!["./test_data/highlight_attributes.html"],
48 //- proc_macros: mirror
49 proc_macros::mirror! {
56 ($($tt:tt)*) => {$($tt)*}
65 macro_rules! dont_color_me_braces {
75 /// textually shadow previous definition
82 macro_rules! keyword_frag {
86 macro with_args($i:ident) {
97 println!("Hello, {}!", 92);
98 dont_color_me_braces!();
102 expect_file!["./test_data/highlight_macros.html"],
107 /// If what you want to test feels like a specific entity consider making a new test instead,
108 /// this test fixture here in fact should shrink instead of grow ideally.
110 fn test_highlighting() {
113 //- minicore: derive, copy
114 //- /main.rs crate:main deps:foo
115 use inner::{self as inner_mod};
120 pub trait FnOnce<Args> {}
123 pub trait FnMut<Args>: FnOnce<Args> {}
126 pub trait Fn<Args>: FnMut<Args> {}
134 fn bar(&self) -> i32;
138 fn bar(&self) -> i32 {
144 fn baz(mut self, f: Foo) -> i32 {
152 fn quop(&self) -> i32 {
157 use self::FooCopy::{self as BarCopy};
165 fn baz(self, f: FooCopy) -> u32 {
173 fn quop(&self) -> u32 {
182 fn foo<'a, T>() -> T {
190 fn const_param<const FOO: usize>() -> usize {
191 const_param::<{ FOO }>();
196 fn baz<F: Fn() -> ()>(f: F) {
200 fn foobar() -> impl Copy {}
213 let Foo { x: z, y } = Foo { x: z, y };
217 let mut foo = Foo { x, y: x };
218 let foo2 = Foo { x, y: x };
223 let mut copy = FooCopy { x };
249 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
251 None => unimplemented!(),
257 async fn learn_and_sing() {
258 let song = learn_song().await;
259 sing_song(song).await;
262 async fn async_main() {
263 let f1 = learn_and_sing();
265 futures::join!(f1, f2);
269 let bob = foo::Person {
271 age: foo::consts::NUMBER,
274 let control_flow = foo::identity(foo::ControlFlow::Continue);
276 if control_flow.should_die() {
281 pub enum Bool { True, False }
284 pub const fn to_primitive(self) -> bool {
288 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
297 <T as Baz>::Qux: Bar {}
299 fn gp_shadows_trait<Baz: Bar>() {
303 //- /foo.rs crate:foo
305 pub name: &'static str,
309 pub enum ControlFlow {
315 pub fn should_die(self) -> bool {
316 matches!(self, ControlFlow::Die)
320 pub fn identity<T>(x: T) -> T { x }
323 pub const NUMBER: i64 = 92;
332 expect_file!["./test_data/highlight_general.html"],
338 fn test_lifetime_highlighting() {
344 struct Foo<'a, 'b, 'c> where 'a: 'a, 'static: 'static {
348 impl<'a> Foo<'_, 'a, 'static>
354 expect_file!["./test_data/highlight_lifetimes.html"],
360 fn test_keyword_highlighting() {
375 struct __ where Self:;
378 expect_file!["./test_data/highlight_keywords.html"],
384 fn test_string_highlighting() {
385 // The format string detection is based on macro-expansion,
386 // thus, we have to copy the macro definition from `std`
389 macro_rules! println {
391 $crate::io::_print($crate::format_args_nl!($($arg)*));
394 #[rustc_builtin_macro]
396 macro_rules! format_args {}
397 #[rustc_builtin_macro]
399 macro_rules! const_format_args {}
400 #[rustc_builtin_macro]
402 macro_rules! format_args_nl {}
405 pub macro panic_2015 {
407 $crate::panicking::panic("explicit panic")
409 ($msg:literal $(,)?) => (
410 $crate::panicking::panic($msg)
412 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
413 ($msg:expr $(,)?) => (
414 $crate::panicking::panic_str($msg)
416 // Special-case the single-argument case for const_panic.
417 ("{}", $arg:expr $(,)?) => (
418 $crate::panicking::panic_display(&$arg)
420 ($fmt:expr, $($arg:tt)+) => (
421 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
426 #[rustc_builtin_macro(std_panic)]
428 macro_rules! panic {}
429 #[rustc_builtin_macro]
430 macro_rules! assert {}
431 #[rustc_builtin_macro]
435 () => ($crate::panic!("not yet implemented"));
436 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
440 println!("Hello {{Hello}}");
441 // from https://doc.rust-lang.org/std/fmt/index.html
442 println!("Hello"); // => "Hello"
443 println!("Hello, {}!", "world"); // => "Hello, world!"
444 println!("The number is {}", 1); // => "The number is 1"
445 println!("{:?}", (3, 4)); // => "(3, 4)"
446 println!("{value}", value=4); // => "4"
447 println!("{} {}", 1, 2); // => "1 2"
448 println!("{:04}", 42); // => "0042" with leading zerosV
449 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
450 println!("{argument}", argument = "test"); // => "test"
451 println!("{name} {}", 1, name = 2); // => "2 1"
452 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
453 println!("{{{}}}", 2); // => "{2}"
454 println!("Hello {:5}!", "x");
455 println!("Hello {:1$}!", "x", 5);
456 println!("Hello {1:0$}!", 5, "x");
457 println!("Hello {:width$}!", "x", width = 5);
458 println!("Hello {:<5}!", "x");
459 println!("Hello {:-<5}!", "x");
460 println!("Hello {:^5}!", "x");
461 println!("Hello {:>5}!", "x");
462 println!("Hello {:+}!", 5);
463 println!("{:#x}!", 27);
464 println!("Hello {:05}!", 5);
465 println!("Hello {:05}!", -5);
466 println!("{:#010x}!", 27);
467 println!("Hello {0} is {1:.5}", "x", 0.01);
468 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
469 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
470 println!("Hello {} is {:.*}", "x", 5, 0.01);
471 println!("Hello {} is {2:.*}", "x", 5, 0.01);
472 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
473 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
474 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
475 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
480 println!("Hello {{}}");
481 println!("{{ Hello");
482 println!("Hello }}");
483 println!("{{Hello}}");
484 println!("{{ Hello }}");
485 println!("{{Hello }}");
486 println!("{{ Hello}}");
488 println!(r"Hello, {}!", "world");
491 println!("Hello\nWorld");
492 println!("\u{48}\x65\x6C\x6C\x6F World");
494 let _ = "\x28\x28\x00\x63\n";
495 let _ = b"\x28\x28\x00\x63\n";
497 println!("{\x41}", A = 92);
498 println!("{ничоси}", ничоси = 92);
500 println!("{:x?} {} ", thingy, n2);
502 panic!("more {}", 1);
503 assert!(true, "{}", 1);
504 assert!(true, "{} asdasd", 1);
506 asm!("mov eax, {0}");
507 format_args!(concat!("{}"), "{}");
509 expect_file!["./test_data/highlight_strings.html"],
515 fn test_unsafe_highlighting() {
523 macro_rules! unsafe_deref {
528 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
529 static GLOBAL: Struct = Struct { field: 0 };
530 unsafe fn unsafe_fn() {}
537 struct Struct { field: i32 }
539 unsafe fn unsafe_method(&self) {}
547 unsafe trait UnsafeTrait {}
548 unsafe impl UnsafeTrait for Packed {}
549 impl !UnsafeTrait for () {}
551 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
554 fn calls_autoref(&self);
557 impl DoTheAutoref for u16 {
558 fn calls_autoref(&self) {}
562 let x = &5 as *const _ as *const usize;
563 let u = Union { b: 0 };
566 unsafe { unsafe_deref!() }
571 id! { unsafe_deref!() };
573 // unsafe fn and method calls
577 Union { b: 0 } => (),
580 Struct { field: 0 }.unsafe_method();
585 // unsafe access to a static mut
589 // unsafe ref of packed fields
590 let packed = Packed { a: 0 };
592 let ref a = packed.a;
593 let Packed { ref a } = packed;
594 let Packed { a: ref _a } = packed;
596 // unsafe auto ref of packed field
597 packed.a.calls_autoref();
601 expect_file!["./test_data/highlight_unsafe.html"],
607 fn test_highlight_doc_comment() {
611 //! This is a module to test doc injection.
619 /// let _ = "early doctests should not go boom";
625 /// This is an impl with a code block.
638 pub const bar: bool = true;
640 /// Constructs a new `Foo`.
645 /// # #![allow(unused_mut)]
646 /// let mut foo: Foo = Foo::new();
648 pub const fn new() -> Foo {
652 /// `bar` method on `Foo`.
659 /// let foo = Foo::new();
661 /// // calls bar on foo
662 /// assert!(foo.bar());
664 /// let bar = foo.bar || Foo::bar;
669 /// let multi_line_string = "Foo
676 /// let foobar = Foo::new().bar();
680 /// // code block with tilde.
681 /// let foobar = Foo::new().bar();
686 /// fn foo<T, const X: usize>(arg: i32) {
694 pub fn foo(&self) -> bool {
699 /// [`Foo`](Foo) is a struct
700 /// This function is > [`all_the_links`](all_the_links) <
701 /// [`noop`](noop) is a macro below
702 /// [`Item`] is a struct in the module [`module`]
704 /// [`Item`]: module::Item
705 /// [mix_and_match]: ThisShouldntResolve
706 pub fn all_the_links() {}
713 /// macro_rules! noop { ($expr:expr) => { $expr }}
723 /// let _ = example(&[1, 2, 3]);
728 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
732 #[cfg_attr(feature = "alloc", doc = "```rust")]
733 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
734 /// let _ = example(&alloc::vec![1, 2, 3]);
736 pub fn mix_and_match() {}
739 It is beyond me why you'd use these when you got ///
741 let _ = example(&[1, 2, 3]);
743 [`block_comments2`] tests these with indentation
745 pub fn block_comments() {}
748 Really, I don't get it
750 let _ = example(&[1, 2, 3]);
752 [`block_comments`] tests these without indentation
754 pub fn block_comments2() {}
756 //- /outline_module.rs
757 //! This is an outline module whose purpose is to test that its inline attribute injection does not
758 //! spill into its parent.
763 expect_file!["./test_data/highlight_doctest.html"],
769 fn test_extern_crate() {
772 //- /main.rs crate:main deps:std,alloc
774 extern crate alloc as abc;
775 //- /std/lib.rs crate:std
777 //- /alloc/lib.rs crate:alloc
780 expect_file!["./test_data/highlight_extern_crate.html"],
786 fn test_crate_root() {
789 //- minicore: iterators
790 //- /main.rs crate:main deps:foo
794 pub const NINETY_TWO: u8 = 92;
798 pub(crate) fn main() {
799 let baz = iter::repeat(92);
803 pub(in super) const FORTY_TWO: u8 = 42;
806 use super::super::NINETY_TWO;
807 use crate::foooo::Point;
809 pub(in super::super) const TWENTY_NINE: u8 = 29;
812 //- /foo.rs crate:foo
819 pub(super) fn swap(p: crate::Point) -> crate::Point {
820 crate::Point { x: p.y, y: p.x }
824 expect_file!["./test_data/highlight_crate_root.html"],
830 fn test_default_library() {
833 //- minicore: option, iterators
838 let nums = iter::repeat(foo.unwrap());
841 expect_file!["./test_data/highlight_default_library.html"],
847 fn test_associated_function() {
855 pub fn is_static() {}
856 pub fn is_not_static(&self) {}
861 fn t_is_not_static(&self) {}
865 pub fn is_static() {}
866 pub fn is_not_static(&self) {}
869 expect_file!["./test_data/highlight_assoc_functions.html"],
875 fn test_injection() {
878 fn fixture(ra_fixture: &str) {}
884 println!("2 + 2 = {}", 4);
897 expect_file!["./test_data/highlight_injection.html"],
903 fn test_operators() {
907 1 + 1 - 1 * 1 / 1 % 1 | 1 & 1 ! 1 ^ 1 >> 1 << 1;
921 expect_file!["./test_data/highlight_operators.html"],
927 fn test_mod_hl_injection() {
932 //! This is an intra doc injection test for modules
934 //! This is an intra doc injection test for modules
937 //- /lib.rs crate:foo
938 /// [crate::foo::Struct]
939 /// This is an intra doc injection test for modules
940 /// [crate::foo::Struct]
941 /// This is an intra doc injection test for modules
944 expect_file!["./test_data/highlight_module_docs_inline.html"],
949 //- /lib.rs crate:foo
950 /// [crate::foo::Struct]
951 /// This is an intra doc injection test for modules
952 /// [crate::foo::Struct]
953 /// This is an intra doc injection test for modules
957 //! This is an intra doc injection test for modules
959 //! This is an intra doc injection test for modules
963 expect_file!["./test_data/highlight_module_docs_outline.html"],
970 not(all(unix, target_pointer_width = "64")),
971 ignore = "depends on `DefaultHasher` outputs"
973 fn test_rainbow_highlighting() {
978 let x = hello.to_string();
979 let y = hello.to_string();
981 let x = "other color please!";
982 let y = x.to_string();
986 let mut hello = "hello";
989 expect_file!["./test_data/highlight_rainbow.html"],
996 let (analysis, file_id) = fixture::file(
998 #[derive(Clone, Debug)]
1007 let highlights = &analysis
1010 FileRange { file_id, range: TextRange::at(45.into(), 1.into()) },
1014 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
1018 fn ranges_sorted() {
1019 let (analysis, file_id) = fixture::file(
1022 macro_rules! test {}
1026 let _ = analysis.highlight(HL_CONFIG, file_id).unwrap();
1029 /// Highlights the code given by the `ra_fixture` argument, renders the
1030 /// result as HTML, and compares it with the HTML file given as `snapshot`.
1031 /// Note that the `snapshot` file is overwritten by the rendered HTML.
1032 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
1033 let (analysis, file_id) = fixture::file(ra_fixture.trim());
1034 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
1035 expect.assert_eq(actual_html)
1039 fn benchmark_syntax_highlighting_long_struct() {
1040 if skip_slow_tests() {
1044 let fixture = bench_fixture::big_struct();
1045 let (analysis, file_id) = fixture::file(&fixture);
1048 let _pt = bench("syntax highlighting long struct");
1050 .highlight(HL_CONFIG, file_id)
1053 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1056 assert_eq!(hash, 2001);
1060 fn syntax_highlighting_not_quadratic() {
1061 if skip_slow_tests() {
1065 let mut al = AssertLinear::default();
1066 while al.next_round() {
1070 let fixture = bench_fixture::big_struct_n(n);
1071 let (analysis, file_id) = fixture::file(&fixture);
1073 let time = Instant::now();
1076 .highlight(HL_CONFIG, file_id)
1079 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1081 assert!(hash > n as usize);
1083 let elapsed = time.elapsed();
1084 al.sample(n as f64, elapsed.as_millis() as f64);
1090 fn benchmark_syntax_highlighting_parser() {
1091 if skip_slow_tests() {
1095 let fixture = bench_fixture::glorious_old_parser();
1096 let (analysis, file_id) = fixture::file(&fixture);
1099 let _pt = bench("syntax highlighting parser");
1101 .highlight(HL_CONFIG, file_id)
1104 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
1107 assert_eq!(hash, 1609);