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
14 //- /main.rs crate:main deps:foo
15 use inner::{self as inner_mod};
18 #[rustc_builtin_macro]
21 // Needed for function consuming vs normal
27 #[proc_macros::identity]
30 pub trait FnOnce<Args> {}
33 pub trait FnMut<Args>: FnOnce<Args> {}
36 pub trait Fn<Args>: FnMut<Args> {}
45 trait Bar where Self: {
49 impl Bar for Foo where Self: {
50 fn bar(&self) -> i32 {
56 fn baz(mut self, f: Foo) -> i32 {
64 fn quop(&self) -> i32 {
75 fn baz(self, f: FooCopy) -> u32 {
83 fn quop(&self) -> u32 {
92 fn foo<'a, T>() -> T {
100 fn const_param<const FOO: usize>() -> usize {
105 fn baz<F: Fn() -> ()>(f: F) {
109 fn foobar() -> impl Copy {}
115 macro_rules! def_fn {
116 ($($tt:tt)*) => {$($tt)*}
125 macro_rules! dont_color_me_braces {
135 macro_rules! keyword_frag {
136 ($type:ty) => ($type)
139 macro with_args($i:ident) {
151 println!("Hello, {}!", 92);
152 dont_color_me_braces!();
154 let mut vec = Vec::new();
157 vec.push(Foo { x, y: 1 });
171 let Foo { x: z, y } = Foo { x: z, y };
175 let mut foo = Foo { x, y: x };
176 let foo2 = Foo { x, y: x };
181 let mut copy = FooCopy { x };
207 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
209 None => unimplemented!(),
215 async fn learn_and_sing() {
216 let song = learn_song().await;
217 sing_song(song).await;
220 async fn async_main() {
221 let f1 = learn_and_sing();
223 futures::join!(f1, f2);
227 let bob = foo::Person {
229 age: foo::consts::NUMBER,
232 let control_flow = foo::identity(foo::ControlFlow::Continue);
234 if control_flow.should_die() {
239 pub enum Bool { True, False }
242 pub const fn to_primitive(self) -> bool {
243 matches!(self, Self::True)
246 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
248 //- /foo.rs crate:foo
250 pub name: &'static str,
254 pub enum ControlFlow {
260 pub fn should_die(self) -> bool {
261 matches!(self, ControlFlow::Die)
265 pub fn identity<T>(x: T) -> T { x }
268 pub const NUMBER: i64 = 92;
278 expect_file!["./test_data/highlighting.html"],
284 fn test_rainbow_highlighting() {
289 let x = hello.to_string();
290 let y = hello.to_string();
292 let x = "other color please!";
293 let y = x.to_string();
297 let mut hello = "hello";
301 expect_file!["./test_data/rainbow_highlighting.html"],
307 fn benchmark_syntax_highlighting_long_struct() {
308 if skip_slow_tests() {
312 let fixture = bench_fixture::big_struct();
313 let (analysis, file_id) = fixture::file(&fixture);
316 let _pt = bench("syntax highlighting long struct");
321 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
324 assert_eq!(hash, 2001);
328 fn syntax_highlighting_not_quadratic() {
329 if skip_slow_tests() {
333 let mut al = AssertLinear::default();
334 while al.next_round() {
338 let fixture = bench_fixture::big_struct_n(n);
339 let (analysis, file_id) = fixture::file(&fixture);
341 let time = Instant::now();
347 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
349 assert!(hash > n as usize);
351 let elapsed = time.elapsed();
352 al.sample(n as f64, elapsed.as_millis() as f64);
358 fn benchmark_syntax_highlighting_parser() {
359 if skip_slow_tests() {
363 let fixture = bench_fixture::glorious_old_parser();
364 let (analysis, file_id) = fixture::file(&fixture);
367 let _pt = bench("syntax highlighting parser");
372 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
375 assert_eq!(hash, 1616);
380 let (analysis, file_id) = fixture::file(
382 #[derive(Clone, Debug)]
391 let highlights = &analysis
392 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
395 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
399 fn test_flattening() {
402 fn fixture(ra_fixture: &str) {}
408 println!("2 + 2 = {}", 4);
414 expect_file!["./test_data/highlight_injection.html"],
421 let (analysis, file_id) = fixture::file(
428 let _ = analysis.highlight(file_id).unwrap();
432 fn test_string_highlighting() {
433 // The format string detection is based on macro-expansion,
434 // thus, we have to copy the macro definition from `std`
437 macro_rules! println {
439 $crate::io::_print($crate::format_args_nl!($($arg)*));
442 #[rustc_builtin_macro]
443 macro_rules! format_args_nl {
444 ($fmt:expr) => {{ /* compiler built-in */ }};
445 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
449 // from https://doc.rust-lang.org/std/fmt/index.html
450 println!("Hello"); // => "Hello"
451 println!("Hello, {}!", "world"); // => "Hello, world!"
452 println!("The number is {}", 1); // => "The number is 1"
453 println!("{:?}", (3, 4)); // => "(3, 4)"
454 println!("{value}", value=4); // => "4"
455 println!("{} {}", 1, 2); // => "1 2"
456 println!("{:04}", 42); // => "0042" with leading zerosV
457 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
458 println!("{argument}", argument = "test"); // => "test"
459 println!("{name} {}", 1, name = 2); // => "2 1"
460 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
461 println!("{{{}}}", 2); // => "{2}"
462 println!("Hello {:5}!", "x");
463 println!("Hello {:1$}!", "x", 5);
464 println!("Hello {1:0$}!", 5, "x");
465 println!("Hello {:width$}!", "x", width = 5);
466 println!("Hello {:<5}!", "x");
467 println!("Hello {:-<5}!", "x");
468 println!("Hello {:^5}!", "x");
469 println!("Hello {:>5}!", "x");
470 println!("Hello {:+}!", 5);
471 println!("{:#x}!", 27);
472 println!("Hello {:05}!", 5);
473 println!("Hello {:05}!", -5);
474 println!("{:#010x}!", 27);
475 println!("Hello {0} is {1:.5}", "x", 0.01);
476 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
477 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
478 println!("Hello {} is {:.*}", "x", 5, 0.01);
479 println!("Hello {} is {2:.*}", "x", 5, 0.01);
480 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
481 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
482 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
483 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
484 println!("Hello {{}}");
485 println!("{{ Hello");
487 println!(r"Hello, {}!", "world");
490 println!("Hello\nWorld");
491 println!("\u{48}\x65\x6C\x6C\x6F World");
493 println!("{\x41}", A = 92);
494 println!("{ничоси}", ничоси = 92);
496 println!("{:x?} {} ", thingy, n2);
499 expect_file!["./test_data/highlight_strings.html"],
505 fn test_unsafe_highlighting() {
508 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
509 static GLOBAL: Struct = Struct { field: 0 };
510 unsafe fn unsafe_fn() {}
517 struct Struct { field: i32 }
519 unsafe fn unsafe_method(&self) {}
527 unsafe trait UnsafeTrait {}
528 unsafe impl UnsafeTrait for Packed {}
529 impl !UnsafeTrait for () {}
531 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
534 fn calls_autoref(&self);
537 impl DoTheAutoref for u16 {
538 fn calls_autoref(&self) {}
542 let x = &5 as *const _ as *const usize;
543 let u = Union { b: 0 };
545 // unsafe fn and method calls
549 Union { b: 0 } => (),
552 Struct { field: 0 }.unsafe_method();
557 // unsafe access to a static mut
561 // unsafe ref of packed fields
562 let packed = Packed { a: 0 };
564 let ref a = packed.a;
565 let Packed { ref a } = packed;
566 let Packed { a: ref _a } = packed;
568 // unsafe auto ref of packed field
569 packed.a.calls_autoref();
574 expect_file!["./test_data/highlight_unsafe.html"],
580 fn test_highlight_doc_comment() {
583 //! This is a module to test doc injection.
589 /// let _ = "early doctests should not go boom";
595 /// This is an impl with a code block.
608 pub const bar: bool = true;
610 /// Constructs a new `Foo`.
615 /// # #![allow(unused_mut)]
616 /// let mut foo: Foo = Foo::new();
618 pub const fn new() -> Foo {
622 /// `bar` method on `Foo`.
629 /// let foo = Foo::new();
631 /// // calls bar on foo
632 /// assert!(foo.bar());
634 /// let bar = foo.bar || Foo::bar;
639 /// let multi_line_string = "Foo
646 /// let foobar = Foo::new().bar();
652 pub fn foo(&self) -> bool {
657 /// [`Foo`](Foo) is a struct
658 /// This function is > [`all_the_links`](all_the_links) <
659 /// [`noop`](noop) is a macro below
660 /// [`Item`] is a struct in the module [`module`]
662 /// [`Item`]: module::Item
663 /// [mix_and_match]: ThisShouldntResolve
664 pub fn all_the_links() {}
680 /// let _ = example(&[1, 2, 3]);
685 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
689 #[cfg_attr(feature = "alloc", doc = "```rust")]
690 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
691 /// let _ = example(&alloc::vec![1, 2, 3]);
693 pub fn mix_and_match() {}
696 It is beyond me why you'd use these when you got ///
698 let _ = example(&[1, 2, 3]);
700 [`block_comments2`] tests these with indentation
702 pub fn block_comments() {}
705 Really, I don't get it
707 let _ = example(&[1, 2, 3]);
709 [`block_comments`] tests these without indentation
711 pub fn block_comments2() {}
714 expect_file!["./test_data/highlight_doctest.html"],
720 fn test_extern_crate() {
723 //- /main.rs crate:main deps:std,alloc
725 extern crate alloc as abc;
726 //- /std/lib.rs crate:std
728 //- /alloc/lib.rs crate:alloc
731 expect_file!["./test_data/highlight_extern_crate.html"],
737 fn test_associated_function() {
745 pub fn is_static() {}
746 pub fn is_not_static(&self) {}
751 fn t_is_not_static(&self) {}
755 pub fn is_static() {}
756 pub fn is_not_static(&self) {}
759 expect_file!["./test_data/highlight_assoc_functions.html"],
765 fn test_injection() {
768 fn f(ra_fixture: &str) {}
778 expect_file!["./test_data/injection.html"],
783 /// Highlights the code given by the `ra_fixture` argument, renders the
784 /// result as HTML, and compares it with the HTML file given as `snapshot`.
785 /// Note that the `snapshot` file is overwritten by the rendered HTML.
786 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
787 let (analysis, file_id) = fixture::file(ra_fixture);
788 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
789 expect.assert_eq(actual_html)