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 //- /main.rs crate:main deps:foo
14 use inner::{self as inner_mod};
17 #[rustc_builtin_macro]
20 // Needed for function consuming vs normal
28 pub trait FnOnce<Args> {}
31 pub trait FnMut<Args>: FnOnce<Args> {}
34 pub trait Fn<Args>: FnMut<Args> {}
43 trait Bar where Self: {
47 impl Bar for Foo where Self: {
48 fn bar(&self) -> i32 {
54 fn baz(mut self, f: Foo) -> i32 {
62 fn quop(&self) -> i32 {
73 fn baz(self, f: FooCopy) -> u32 {
81 fn quop(&self) -> u32 {
90 static mut STATIC_MUT: i32 = 0;
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 });
174 let Foo { x: z, y } = Foo { x: z, y };
178 let mut foo = Foo { x, y: x };
179 let foo2 = Foo { x, y: x };
184 let mut copy = FooCopy { x };
210 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
212 None => unimplemented!(),
218 async fn learn_and_sing() {
219 let song = learn_song().await;
220 sing_song(song).await;
223 async fn async_main() {
224 let f1 = learn_and_sing();
226 futures::join!(f1, f2);
229 unsafe trait Dangerous {}
230 impl Dangerous for () {}
233 let bob = foo::Person {
235 age: foo::consts::NUMBER,
238 let control_flow = foo::identity(foo::ControlFlow::Continue);
240 if control_flow.should_die() {
245 pub enum Bool { True, False }
248 pub const fn to_primitive(self) -> bool {
249 matches!(self, Self::True)
252 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
254 //- /foo.rs crate:foo
256 pub name: &'static str,
260 pub enum ControlFlow {
266 pub fn should_die(self) -> bool {
267 matches!(self, ControlFlow::Die)
271 pub fn identity<T>(x: T) -> T { x }
274 pub const NUMBER: i64 = 92;
284 expect_file!["./test_data/highlighting.html"],
290 fn test_rainbow_highlighting() {
295 let x = hello.to_string();
296 let y = hello.to_string();
298 let x = "other color please!";
299 let y = x.to_string();
303 let mut hello = "hello";
307 expect_file!["./test_data/rainbow_highlighting.html"],
313 fn benchmark_syntax_highlighting_long_struct() {
314 if skip_slow_tests() {
318 let fixture = bench_fixture::big_struct();
319 let (analysis, file_id) = fixture::file(&fixture);
322 let _pt = bench("syntax highlighting long struct");
327 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
330 assert_eq!(hash, 2001);
334 fn syntax_highlighting_not_quadratic() {
335 if skip_slow_tests() {
339 let mut al = AssertLinear::default();
340 while al.next_round() {
344 let fixture = bench_fixture::big_struct_n(n);
345 let (analysis, file_id) = fixture::file(&fixture);
347 let time = Instant::now();
353 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
355 assert!(hash > n as usize);
357 let elapsed = time.elapsed();
358 al.sample(n as f64, elapsed.as_millis() as f64);
364 fn benchmark_syntax_highlighting_parser() {
365 if skip_slow_tests() {
369 let fixture = bench_fixture::glorious_old_parser();
370 let (analysis, file_id) = fixture::file(&fixture);
373 let _pt = bench("syntax highlighting parser");
378 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
381 assert_eq!(hash, 1632);
386 let (analysis, file_id) = fixture::file(
388 #[derive(Clone, Debug)]
397 let highlights = &analysis
398 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
401 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
405 fn test_flattening() {
408 fn fixture(ra_fixture: &str) {}
414 println!("2 + 2 = {}", 4);
420 expect_file!["./test_data/highlight_injection.html"],
427 let (analysis, file_id) = fixture::file(
434 let _ = analysis.highlight(file_id).unwrap();
438 fn test_string_highlighting() {
439 // The format string detection is based on macro-expansion,
440 // thus, we have to copy the macro definition from `std`
443 macro_rules! println {
445 $crate::io::_print($crate::format_args_nl!($($arg)*));
448 #[rustc_builtin_macro]
449 macro_rules! format_args_nl {
450 ($fmt:expr) => {{ /* compiler built-in */ }};
451 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
455 // from https://doc.rust-lang.org/std/fmt/index.html
456 println!("Hello"); // => "Hello"
457 println!("Hello, {}!", "world"); // => "Hello, world!"
458 println!("The number is {}", 1); // => "The number is 1"
459 println!("{:?}", (3, 4)); // => "(3, 4)"
460 println!("{value}", value=4); // => "4"
461 println!("{} {}", 1, 2); // => "1 2"
462 println!("{:04}", 42); // => "0042" with leading zerosV
463 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
464 println!("{argument}", argument = "test"); // => "test"
465 println!("{name} {}", 1, name = 2); // => "2 1"
466 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
467 println!("{{{}}}", 2); // => "{2}"
468 println!("Hello {:5}!", "x");
469 println!("Hello {:1$}!", "x", 5);
470 println!("Hello {1:0$}!", 5, "x");
471 println!("Hello {:width$}!", "x", width = 5);
472 println!("Hello {:<5}!", "x");
473 println!("Hello {:-<5}!", "x");
474 println!("Hello {:^5}!", "x");
475 println!("Hello {:>5}!", "x");
476 println!("Hello {:+}!", 5);
477 println!("{:#x}!", 27);
478 println!("Hello {:05}!", 5);
479 println!("Hello {:05}!", -5);
480 println!("{:#010x}!", 27);
481 println!("Hello {0} is {1:.5}", "x", 0.01);
482 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
483 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
484 println!("Hello {} is {:.*}", "x", 5, 0.01);
485 println!("Hello {} is {2:.*}", "x", 5, 0.01);
486 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
487 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
488 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
489 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
490 println!("Hello {{}}");
491 println!("{{ Hello");
493 println!(r"Hello, {}!", "world");
496 println!("Hello\nWorld");
497 println!("\u{48}\x65\x6C\x6C\x6F World");
499 println!("{\x41}", A = 92);
500 println!("{ничоси}", ничоси = 92);
502 println!("{:x?} {} ", thingy, n2);
505 expect_file!["./test_data/highlight_strings.html"],
511 fn test_unsafe_highlighting() {
514 unsafe fn unsafe_fn() {}
524 unsafe fn unsafe_method(&self) {}
527 struct TypeForStaticMut {
531 static mut global_mut: TypeForStaticMut = TypeForStaticMut { a: 0 };
538 unsafe trait UnsafeTrait {}
539 unsafe impl UnsafeTrait for Packed {}
541 fn require_unsafe_trait<T: UnsafeTrait>(_: T) {}
544 fn calls_autoref(&self);
547 impl DoTheAutoref for u16 {
548 fn calls_autoref(&self) {}
552 let x = &5 as *const _ as *const usize;
553 let u = Union { b: 0 };
555 // unsafe fn and method calls
559 Union { b: 0 } => (),
562 HasUnsafeFn.unsafe_method();
567 // unsafe access to a static mut
568 let a = global_mut.a;
570 // unsafe ref of packed fields
571 let packed = Packed { a: 0 };
573 let ref a = packed.a;
574 let Packed { ref a } = packed;
575 let Packed { a: ref _a } = packed;
577 // unsafe auto ref of packed field
578 packed.a.calls_autoref();
583 expect_file!["./test_data/highlight_unsafe.html"],
589 fn test_highlight_doc_comment() {
592 //! This is a module to test doc injection.
598 /// let _ = "early doctests should not go boom";
604 /// This is an impl with a code block.
617 pub const bar: bool = true;
619 /// Constructs a new `Foo`.
624 /// # #![allow(unused_mut)]
625 /// let mut foo: Foo = Foo::new();
627 pub const fn new() -> Foo {
631 /// `bar` method on `Foo`.
638 /// let foo = Foo::new();
640 /// // calls bar on foo
641 /// assert!(foo.bar());
643 /// let bar = foo.bar || Foo::bar;
648 /// let multi_line_string = "Foo
655 /// let foobar = Foo::new().bar();
661 pub fn foo(&self) -> bool {
666 /// [`Foo`](Foo) is a struct
667 /// This function is > [`all_the_links`](all_the_links) <
668 /// [`noop`](noop) is a macro below
669 /// [`Item`] is a struct in the module [`module`]
671 /// [`Item`]: module::Item
672 /// [mix_and_match]: ThisShouldntResolve
673 pub fn all_the_links() {}
689 /// let _ = example(&[1, 2, 3]);
694 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
698 #[cfg_attr(feature = "alloc", doc = "```rust")]
699 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
700 /// let _ = example(&alloc::vec![1, 2, 3]);
702 pub fn mix_and_match() {}
705 It is beyond me why you'd use these when you got ///
707 let _ = example(&[1, 2, 3]);
709 [`block_comments2`] tests these with indentation
711 pub fn block_comments() {}
714 Really, I don't get it
716 let _ = example(&[1, 2, 3]);
718 [`block_comments`] tests these without indentation
720 pub fn block_comments2() {}
723 expect_file!["./test_data/highlight_doctest.html"],
729 fn test_extern_crate() {
732 //- /main.rs crate:main deps:std,alloc
734 extern crate alloc as abc;
735 //- /std/lib.rs crate:std
737 //- /alloc/lib.rs crate:alloc
740 expect_file!["./test_data/highlight_extern_crate.html"],
746 fn test_associated_function() {
754 pub fn is_static() {}
755 pub fn is_not_static(&self) {}
760 fn t_is_not_static(&self) {}
764 pub fn is_static() {}
765 pub fn is_not_static(&self) {}
768 expect_file!["./test_data/highlight_assoc_functions.html"],
774 fn test_injection() {
777 fn f(ra_fixture: &str) {}
787 expect_file!["./test_data/injection.html"],
792 /// Highlights the code given by the `ra_fixture` argument, renders the
793 /// result as HTML, and compares it with the HTML file given as `snapshot`.
794 /// Note that the `snapshot` file is overwritten by the rendered HTML.
795 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
796 let (analysis, file_id) = fixture::file(ra_fixture);
797 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
798 expect.assert_eq(actual_html)