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"],
38 //- proc_macros: mirror
39 proc_macros::mirror! {
46 ($($tt:tt)*) => {$($tt)*}
55 macro_rules! dont_color_me_braces {
65 macro_rules! keyword_frag {
69 macro with_args($i:ident) {
80 println!("Hello, {}!", 92);
81 dont_color_me_braces!();
85 expect_file!["./test_data/highlight_macros.html"],
90 /// If what you want to test feels like a specific entity consider making a new test instead,
91 /// this test fixture here in fact should shrink instead of grow ideally.
93 fn test_highlighting() {
96 //- minicore: derive, copy
97 //- /main.rs crate:main deps:foo
98 use inner::{self as inner_mod};
103 pub trait FnOnce<Args> {}
106 pub trait FnMut<Args>: FnOnce<Args> {}
109 pub trait Fn<Args>: FnMut<Args> {}
116 trait Bar where Self: {
117 fn bar(&self) -> i32;
120 impl Bar for Foo where Self: {
121 fn bar(&self) -> i32 {
127 fn baz(mut self, f: Foo) -> i32 {
135 fn quop(&self) -> i32 {
140 use self::FooCopy::{self as BarCopy};
148 fn baz(self, f: FooCopy) -> u32 {
156 fn quop(&self) -> u32 {
165 fn foo<'a, T>() -> T {
173 fn const_param<const FOO: usize>() -> usize {
178 fn baz<F: Fn() -> ()>(f: F) {
182 fn foobar() -> impl Copy {}
195 let Foo { x: z, y } = Foo { x: z, y };
199 let mut foo = Foo { x, y: x };
200 let foo2 = Foo { x, y: x };
205 let mut copy = FooCopy { x };
231 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
233 None => unimplemented!(),
239 async fn learn_and_sing() {
240 let song = learn_song().await;
241 sing_song(song).await;
244 async fn async_main() {
245 let f1 = learn_and_sing();
247 futures::join!(f1, f2);
251 let bob = foo::Person {
253 age: foo::consts::NUMBER,
256 let control_flow = foo::identity(foo::ControlFlow::Continue);
258 if control_flow.should_die() {
263 pub enum Bool { True, False }
266 pub const fn to_primitive(self) -> bool {
267 matches!(self, Self::True)
270 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
279 <T as Baz>::Qux: Bar {}
281 //- /foo.rs crate:foo
283 pub name: &'static str,
287 pub enum ControlFlow {
293 pub fn should_die(self) -> bool {
294 matches!(self, ControlFlow::Die)
298 pub fn identity<T>(x: T) -> T { x }
301 pub const NUMBER: i64 = 92;
310 expect_file!["./test_data/highlight_general.html"],
316 fn test_lifetime_highlighting() {
322 struct Foo<'a, 'b, 'c> where 'a: 'a, 'static: 'static {
326 impl<'a> Foo<'_, 'a, 'static>
332 expect_file!["./test_data/highlight_lifetimes.html"],
338 fn test_string_highlighting() {
339 // The format string detection is based on macro-expansion,
340 // thus, we have to copy the macro definition from `std`
343 macro_rules! println {
345 $crate::io::_print($crate::format_args_nl!($($arg)*));
348 #[rustc_builtin_macro]
350 macro_rules! format_args {}
351 #[rustc_builtin_macro]
353 macro_rules! const_format_args {}
354 #[rustc_builtin_macro]
356 macro_rules! format_args_nl {}
359 pub macro panic_2015 {
361 $crate::panicking::panic("explicit panic")
363 ($msg:literal $(,)?) => (
364 $crate::panicking::panic($msg)
366 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
367 ($msg:expr $(,)?) => (
368 $crate::panicking::panic_str($msg)
370 // Special-case the single-argument case for const_panic.
371 ("{}", $arg:expr $(,)?) => (
372 $crate::panicking::panic_display(&$arg)
374 ($fmt:expr, $($arg:tt)+) => (
375 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
380 #[rustc_builtin_macro(std_panic)]
382 macro_rules! panic {}
383 #[rustc_builtin_macro]
384 macro_rules! assert {}
385 #[rustc_builtin_macro]
389 () => ($crate::panic!("not yet implemented"));
390 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
394 // from https://doc.rust-lang.org/std/fmt/index.html
395 println!("Hello"); // => "Hello"
396 println!("Hello, {}!", "world"); // => "Hello, world!"
397 println!("The number is {}", 1); // => "The number is 1"
398 println!("{:?}", (3, 4)); // => "(3, 4)"
399 println!("{value}", value=4); // => "4"
400 println!("{} {}", 1, 2); // => "1 2"
401 println!("{:04}", 42); // => "0042" with leading zerosV
402 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
403 println!("{argument}", argument = "test"); // => "test"
404 println!("{name} {}", 1, name = 2); // => "2 1"
405 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
406 println!("{{{}}}", 2); // => "{2}"
407 println!("Hello {:5}!", "x");
408 println!("Hello {:1$}!", "x", 5);
409 println!("Hello {1:0$}!", 5, "x");
410 println!("Hello {:width$}!", "x", width = 5);
411 println!("Hello {:<5}!", "x");
412 println!("Hello {:-<5}!", "x");
413 println!("Hello {:^5}!", "x");
414 println!("Hello {:>5}!", "x");
415 println!("Hello {:+}!", 5);
416 println!("{:#x}!", 27);
417 println!("Hello {:05}!", 5);
418 println!("Hello {:05}!", -5);
419 println!("{:#010x}!", 27);
420 println!("Hello {0} is {1:.5}", "x", 0.01);
421 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
422 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
423 println!("Hello {} is {:.*}", "x", 5, 0.01);
424 println!("Hello {} is {2:.*}", "x", 5, 0.01);
425 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
426 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
427 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
428 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
429 println!("Hello {{}}");
430 println!("{{ Hello");
432 println!(r"Hello, {}!", "world");
435 println!("Hello\nWorld");
436 println!("\u{48}\x65\x6C\x6C\x6F World");
438 println!("{\x41}", A = 92);
439 println!("{ничоси}", ничоси = 92);
441 println!("{:x?} {} ", thingy, n2);
443 panic!("more {}", 1);
444 assert!(true, "{}", 1);
445 assert!(true, "{} asdasd", 1);
447 asm!("mov eax, {0}");
448 format_args!(concat!("{}"), "{}");
450 expect_file!["./test_data/highlight_strings.html"],
456 fn test_unsafe_highlighting() {
459 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
460 static GLOBAL: Struct = Struct { field: 0 };
461 unsafe fn unsafe_fn() {}
468 struct Struct { field: i32 }
470 unsafe fn unsafe_method(&self) {}
478 unsafe trait UnsafeTrait {}
479 unsafe impl UnsafeTrait for Packed {}
480 impl !UnsafeTrait for () {}
482 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
485 fn calls_autoref(&self);
488 impl DoTheAutoref for u16 {
489 fn calls_autoref(&self) {}
493 let x = &5 as *const _ as *const usize;
494 let u = Union { b: 0 };
496 // unsafe fn and method calls
500 Union { b: 0 } => (),
503 Struct { field: 0 }.unsafe_method();
508 // unsafe access to a static mut
512 // unsafe ref of packed fields
513 let packed = Packed { a: 0 };
515 let ref a = packed.a;
516 let Packed { ref a } = packed;
517 let Packed { a: ref _a } = packed;
519 // unsafe auto ref of packed field
520 packed.a.calls_autoref();
524 expect_file!["./test_data/highlight_unsafe.html"],
530 fn test_highlight_doc_comment() {
534 //! This is a module to test doc injection.
542 /// let _ = "early doctests should not go boom";
548 /// This is an impl with a code block.
561 pub const bar: bool = true;
563 /// Constructs a new `Foo`.
568 /// # #![allow(unused_mut)]
569 /// let mut foo: Foo = Foo::new();
571 pub const fn new() -> Foo {
575 /// `bar` method on `Foo`.
582 /// let foo = Foo::new();
584 /// // calls bar on foo
585 /// assert!(foo.bar());
587 /// let bar = foo.bar || Foo::bar;
592 /// let multi_line_string = "Foo
599 /// let foobar = Foo::new().bar();
605 pub fn foo(&self) -> bool {
610 /// [`Foo`](Foo) is a struct
611 /// This function is > [`all_the_links`](all_the_links) <
612 /// [`noop`](noop) is a macro below
613 /// [`Item`] is a struct in the module [`module`]
615 /// [`Item`]: module::Item
616 /// [mix_and_match]: ThisShouldntResolve
617 pub fn all_the_links() {}
624 /// macro_rules! noop { ($expr:expr) => { $expr }}
634 /// let _ = example(&[1, 2, 3]);
639 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
643 #[cfg_attr(feature = "alloc", doc = "```rust")]
644 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
645 /// let _ = example(&alloc::vec![1, 2, 3]);
647 pub fn mix_and_match() {}
650 It is beyond me why you'd use these when you got ///
652 let _ = example(&[1, 2, 3]);
654 [`block_comments2`] tests these with indentation
656 pub fn block_comments() {}
659 Really, I don't get it
661 let _ = example(&[1, 2, 3]);
663 [`block_comments`] tests these without indentation
665 pub fn block_comments2() {}
667 //- /outline_module.rs
668 //! This is an outline module whose purpose is to test that its inline attribute injection does not
669 //! spill into its parent.
674 expect_file!["./test_data/highlight_doctest.html"],
680 fn test_extern_crate() {
683 //- /main.rs crate:main deps:std,alloc
685 extern crate alloc as abc;
686 //- /std/lib.rs crate:std
688 //- /alloc/lib.rs crate:alloc
691 expect_file!["./test_data/highlight_extern_crate.html"],
697 fn test_crate_root() {
700 //- minicore: iterators
701 //- /main.rs crate:main deps:foo
705 pub const NINETY_TWO: u8 = 92;
709 pub(crate) fn main() {
710 let baz = iter::repeat(92);
714 pub(in super) const FORTY_TWO: u8 = 42;
717 use super::super::NINETY_TWO;
718 use crate::foooo::Point;
720 pub(in super::super) const TWENTY_NINE: u8 = 29;
723 //- /foo.rs crate:foo
730 pub(super) fn swap(p: crate::Point) -> crate::Point {
731 crate::Point { x: p.y, y: p.x }
735 expect_file!["./test_data/highlight_crate_root.html"],
741 fn test_default_library() {
744 //- minicore: option, iterators
749 let nums = iter::repeat(foo.unwrap());
752 expect_file!["./test_data/highlight_default_library.html"],
758 fn test_associated_function() {
766 pub fn is_static() {}
767 pub fn is_not_static(&self) {}
772 fn t_is_not_static(&self) {}
776 pub fn is_static() {}
777 pub fn is_not_static(&self) {}
780 expect_file!["./test_data/highlight_assoc_functions.html"],
786 fn test_injection() {
789 fn fixture(ra_fixture: &str) {}
795 println!("2 + 2 = {}", 4);
808 expect_file!["./test_data/highlight_injection.html"],
814 fn test_rainbow_highlighting() {
819 let x = hello.to_string();
820 let y = hello.to_string();
822 let x = "other color please!";
823 let y = x.to_string();
827 let mut hello = "hello";
830 expect_file!["./test_data/highlight_rainbow.html"],
837 let (analysis, file_id) = fixture::file(
839 #[derive(Clone, Debug)]
848 let highlights = &analysis
849 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
852 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
857 let (analysis, file_id) = fixture::file(
864 let _ = analysis.highlight(file_id).unwrap();
867 /// Highlights the code given by the `ra_fixture` argument, renders the
868 /// result as HTML, and compares it with the HTML file given as `snapshot`.
869 /// Note that the `snapshot` file is overwritten by the rendered HTML.
870 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
871 let (analysis, file_id) = fixture::file(ra_fixture.trim());
872 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
873 expect.assert_eq(actual_html)
877 fn benchmark_syntax_highlighting_long_struct() {
878 if skip_slow_tests() {
882 let fixture = bench_fixture::big_struct();
883 let (analysis, file_id) = fixture::file(&fixture);
886 let _pt = bench("syntax highlighting long struct");
891 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
894 assert_eq!(hash, 2001);
898 fn syntax_highlighting_not_quadratic() {
899 if skip_slow_tests() {
903 let mut al = AssertLinear::default();
904 while al.next_round() {
908 let fixture = bench_fixture::big_struct_n(n);
909 let (analysis, file_id) = fixture::file(&fixture);
911 let time = Instant::now();
917 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
919 assert!(hash > n as usize);
921 let elapsed = time.elapsed();
922 al.sample(n as f64, elapsed.as_millis() as f64);
928 fn benchmark_syntax_highlighting_parser() {
929 if skip_slow_tests() {
933 let fixture = bench_fixture::glorious_old_parser();
934 let (analysis, file_id) = fixture::file(&fixture);
937 let _pt = bench("syntax highlighting parser");
942 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
945 assert_eq!(hash, 1616);