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 //- minicore: derive, copy
15 //- /main.rs crate:main deps:foo
16 use inner::{self as inner_mod};
20 #[proc_macros::identity]
23 pub trait FnOnce<Args> {}
26 pub trait FnMut<Args>: FnOnce<Args> {}
29 pub trait Fn<Args>: FnMut<Args> {}
32 proc_macros::mirror! {
39 trait Bar where Self: {
43 impl Bar for Foo where Self: {
44 fn bar(&self) -> i32 {
50 fn baz(mut self, f: Foo) -> i32 {
58 fn quop(&self) -> i32 {
63 use self::FooCopy::{self as BarCopy};
70 fn baz(self, f: FooCopy) -> u32 {
78 fn quop(&self) -> u32 {
87 fn foo<'a, T>() -> T {
95 fn const_param<const FOO: usize>() -> usize {
100 fn baz<F: Fn() -> ()>(f: F) {
104 fn foobar() -> impl Copy {}
110 macro_rules! def_fn {
111 ($($tt:tt)*) => {$($tt)*}
120 macro_rules! dont_color_me_braces {
130 macro_rules! keyword_frag {
131 ($type:ty) => ($type)
134 macro with_args($i:ident) {
146 println!("Hello, {}!", 92);
147 dont_color_me_braces!();
149 let mut vec = Vec::new();
152 vec.push(Foo { x, y: 1 });
166 let Foo { x: z, y } = Foo { x: z, y };
170 let mut foo = Foo { x, y: x };
171 let foo2 = Foo { x, y: x };
176 let mut copy = FooCopy { x };
202 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
204 None => unimplemented!(),
210 async fn learn_and_sing() {
211 let song = learn_song().await;
212 sing_song(song).await;
215 async fn async_main() {
216 let f1 = learn_and_sing();
218 futures::join!(f1, f2);
222 let bob = foo::Person {
224 age: foo::consts::NUMBER,
227 let control_flow = foo::identity(foo::ControlFlow::Continue);
229 if control_flow.should_die() {
234 pub enum Bool { True, False }
237 pub const fn to_primitive(self) -> bool {
238 matches!(self, Self::True)
241 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
250 <T as Baz>::Qux: Bar {}
252 //- /foo.rs crate:foo
254 pub name: &'static str,
258 pub enum ControlFlow {
264 pub fn should_die(self) -> bool {
265 matches!(self, ControlFlow::Die)
269 pub fn identity<T>(x: T) -> T { x }
272 pub const NUMBER: i64 = 92;
282 expect_file!["./test_data/highlighting.html"],
288 fn test_rainbow_highlighting() {
293 let x = hello.to_string();
294 let y = hello.to_string();
296 let x = "other color please!";
297 let y = x.to_string();
301 let mut hello = "hello";
305 expect_file!["./test_data/rainbow_highlighting.html"],
311 fn benchmark_syntax_highlighting_long_struct() {
312 if skip_slow_tests() {
316 let fixture = bench_fixture::big_struct();
317 let (analysis, file_id) = fixture::file(&fixture);
320 let _pt = bench("syntax highlighting long struct");
325 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
328 assert_eq!(hash, 2001);
332 fn syntax_highlighting_not_quadratic() {
333 if skip_slow_tests() {
337 let mut al = AssertLinear::default();
338 while al.next_round() {
342 let fixture = bench_fixture::big_struct_n(n);
343 let (analysis, file_id) = fixture::file(&fixture);
345 let time = Instant::now();
351 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
353 assert!(hash > n as usize);
355 let elapsed = time.elapsed();
356 al.sample(n as f64, elapsed.as_millis() as f64);
362 fn benchmark_syntax_highlighting_parser() {
363 if skip_slow_tests() {
367 let fixture = bench_fixture::glorious_old_parser();
368 let (analysis, file_id) = fixture::file(&fixture);
371 let _pt = bench("syntax highlighting parser");
376 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
379 assert_eq!(hash, 1616);
384 let (analysis, file_id) = fixture::file(
386 #[derive(Clone, Debug)]
395 let highlights = &analysis
396 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
399 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
403 fn test_flattening() {
406 fn fixture(ra_fixture: &str) {}
412 println!("2 + 2 = {}", 4);
418 expect_file!["./test_data/highlight_injection.html"],
425 let (analysis, file_id) = fixture::file(
432 let _ = analysis.highlight(file_id).unwrap();
436 fn test_string_highlighting() {
437 // The format string detection is based on macro-expansion,
438 // thus, we have to copy the macro definition from `std`
441 macro_rules! println {
443 $crate::io::_print($crate::format_args_nl!($($arg)*));
446 #[rustc_builtin_macro]
448 macro_rules! format_args {}
449 #[rustc_builtin_macro]
451 macro_rules! const_format_args {}
452 #[rustc_builtin_macro]
454 macro_rules! format_args_nl {}
457 pub macro panic_2015 {
459 $crate::panicking::panic("explicit panic")
461 ($msg:literal $(,)?) => (
462 $crate::panicking::panic($msg)
464 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
465 ($msg:expr $(,)?) => (
466 $crate::panicking::panic_str($msg)
468 // Special-case the single-argument case for const_panic.
469 ("{}", $arg:expr $(,)?) => (
470 $crate::panicking::panic_display(&$arg)
472 ($fmt:expr, $($arg:tt)+) => (
473 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
478 #[rustc_builtin_macro(std_panic)]
480 macro_rules! panic {}
481 #[rustc_builtin_macro]
482 macro_rules! assert {}
483 #[rustc_builtin_macro]
487 () => ($crate::panic!("not yet implemented"));
488 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
492 // from https://doc.rust-lang.org/std/fmt/index.html
493 println!("Hello"); // => "Hello"
494 println!("Hello, {}!", "world"); // => "Hello, world!"
495 println!("The number is {}", 1); // => "The number is 1"
496 println!("{:?}", (3, 4)); // => "(3, 4)"
497 println!("{value}", value=4); // => "4"
498 println!("{} {}", 1, 2); // => "1 2"
499 println!("{:04}", 42); // => "0042" with leading zerosV
500 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
501 println!("{argument}", argument = "test"); // => "test"
502 println!("{name} {}", 1, name = 2); // => "2 1"
503 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
504 println!("{{{}}}", 2); // => "{2}"
505 println!("Hello {:5}!", "x");
506 println!("Hello {:1$}!", "x", 5);
507 println!("Hello {1:0$}!", 5, "x");
508 println!("Hello {:width$}!", "x", width = 5);
509 println!("Hello {:<5}!", "x");
510 println!("Hello {:-<5}!", "x");
511 println!("Hello {:^5}!", "x");
512 println!("Hello {:>5}!", "x");
513 println!("Hello {:+}!", 5);
514 println!("{:#x}!", 27);
515 println!("Hello {:05}!", 5);
516 println!("Hello {:05}!", -5);
517 println!("{:#010x}!", 27);
518 println!("Hello {0} is {1:.5}", "x", 0.01);
519 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
520 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
521 println!("Hello {} is {:.*}", "x", 5, 0.01);
522 println!("Hello {} is {2:.*}", "x", 5, 0.01);
523 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
524 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
525 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
526 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
527 println!("Hello {{}}");
528 println!("{{ Hello");
530 println!(r"Hello, {}!", "world");
533 println!("Hello\nWorld");
534 println!("\u{48}\x65\x6C\x6C\x6F World");
536 println!("{\x41}", A = 92);
537 println!("{ничоси}", ничоси = 92);
539 println!("{:x?} {} ", thingy, n2);
541 panic!("more {}", 1);
542 assert!(true, "{}", 1);
543 assert!(true, "{} asdasd", 1);
545 asm!("mov eax, {0}");
546 format_args!(concat!("{}"), "{}");
549 expect_file!["./test_data/highlight_strings.html"],
555 fn test_unsafe_highlighting() {
558 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
559 static GLOBAL: Struct = Struct { field: 0 };
560 unsafe fn unsafe_fn() {}
567 struct Struct { field: i32 }
569 unsafe fn unsafe_method(&self) {}
577 unsafe trait UnsafeTrait {}
578 unsafe impl UnsafeTrait for Packed {}
579 impl !UnsafeTrait for () {}
581 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
584 fn calls_autoref(&self);
587 impl DoTheAutoref for u16 {
588 fn calls_autoref(&self) {}
592 let x = &5 as *const _ as *const usize;
593 let u = Union { b: 0 };
595 // unsafe fn and method calls
599 Union { b: 0 } => (),
602 Struct { field: 0 }.unsafe_method();
607 // unsafe access to a static mut
611 // unsafe ref of packed fields
612 let packed = Packed { a: 0 };
614 let ref a = packed.a;
615 let Packed { ref a } = packed;
616 let Packed { a: ref _a } = packed;
618 // unsafe auto ref of packed field
619 packed.a.calls_autoref();
624 expect_file!["./test_data/highlight_unsafe.html"],
630 fn test_highlight_doc_comment() {
633 //! This is a module to test doc injection.
639 /// let _ = "early doctests should not go boom";
645 /// This is an impl with a code block.
658 pub const bar: bool = true;
660 /// Constructs a new `Foo`.
665 /// # #![allow(unused_mut)]
666 /// let mut foo: Foo = Foo::new();
668 pub const fn new() -> Foo {
672 /// `bar` method on `Foo`.
679 /// let foo = Foo::new();
681 /// // calls bar on foo
682 /// assert!(foo.bar());
684 /// let bar = foo.bar || Foo::bar;
689 /// let multi_line_string = "Foo
696 /// let foobar = Foo::new().bar();
702 pub fn foo(&self) -> bool {
707 /// [`Foo`](Foo) is a struct
708 /// This function is > [`all_the_links`](all_the_links) <
709 /// [`noop`](noop) is a macro below
710 /// [`Item`] is a struct in the module [`module`]
712 /// [`Item`]: module::Item
713 /// [mix_and_match]: ThisShouldntResolve
714 pub fn all_the_links() {}
721 /// macro_rules! noop { ($expr:expr) => { $expr }}
731 /// let _ = example(&[1, 2, 3]);
736 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
740 #[cfg_attr(feature = "alloc", doc = "```rust")]
741 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
742 /// let _ = example(&alloc::vec![1, 2, 3]);
744 pub fn mix_and_match() {}
747 It is beyond me why you'd use these when you got ///
749 let _ = example(&[1, 2, 3]);
751 [`block_comments2`] tests these with indentation
753 pub fn block_comments() {}
756 Really, I don't get it
758 let _ = example(&[1, 2, 3]);
760 [`block_comments`] tests these without indentation
762 pub fn block_comments2() {}
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 f(ra_fixture: &str) {}
890 expect_file!["./test_data/injection.html"],
895 /// Highlights the code given by the `ra_fixture` argument, renders the
896 /// result as HTML, and compares it with the HTML file given as `snapshot`.
897 /// Note that the `snapshot` file is overwritten by the rendered HTML.
898 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
899 let (analysis, file_id) = fixture::file(ra_fixture);
900 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
901 expect.assert_eq(actual_html)