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 {
69 fn baz(self, f: FooCopy) -> u32 {
77 fn quop(&self) -> u32 {
86 fn foo<'a, T>() -> T {
94 fn const_param<const FOO: usize>() -> usize {
99 fn baz<F: Fn() -> ()>(f: F) {
103 fn foobar() -> impl Copy {}
109 macro_rules! def_fn {
110 ($($tt:tt)*) => {$($tt)*}
119 macro_rules! dont_color_me_braces {
129 macro_rules! keyword_frag {
130 ($type:ty) => ($type)
133 macro with_args($i:ident) {
145 println!("Hello, {}!", 92);
146 dont_color_me_braces!();
148 let mut vec = Vec::new();
151 vec.push(Foo { x, y: 1 });
165 let Foo { x: z, y } = Foo { x: z, y };
169 let mut foo = Foo { x, y: x };
170 let foo2 = Foo { x, y: x };
175 let mut copy = FooCopy { x };
201 fn and<U>(self, other: Option<U>) -> Option<(T, U)> {
203 None => unimplemented!(),
209 async fn learn_and_sing() {
210 let song = learn_song().await;
211 sing_song(song).await;
214 async fn async_main() {
215 let f1 = learn_and_sing();
217 futures::join!(f1, f2);
221 let bob = foo::Person {
223 age: foo::consts::NUMBER,
226 let control_flow = foo::identity(foo::ControlFlow::Continue);
228 if control_flow.should_die() {
233 pub enum Bool { True, False }
236 pub const fn to_primitive(self) -> bool {
237 matches!(self, Self::True)
240 const USAGE_OF_BOOL:bool = Bool::True.to_primitive();
249 <T as Baz>::Qux: Bar {}
251 //- /foo.rs crate:foo
253 pub name: &'static str,
257 pub enum ControlFlow {
263 pub fn should_die(self) -> bool {
264 matches!(self, ControlFlow::Die)
268 pub fn identity<T>(x: T) -> T { x }
271 pub const NUMBER: i64 = 92;
281 expect_file!["./test_data/highlighting.html"],
287 fn test_rainbow_highlighting() {
292 let x = hello.to_string();
293 let y = hello.to_string();
295 let x = "other color please!";
296 let y = x.to_string();
300 let mut hello = "hello";
304 expect_file!["./test_data/rainbow_highlighting.html"],
310 fn benchmark_syntax_highlighting_long_struct() {
311 if skip_slow_tests() {
315 let fixture = bench_fixture::big_struct();
316 let (analysis, file_id) = fixture::file(&fixture);
319 let _pt = bench("syntax highlighting long struct");
324 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
327 assert_eq!(hash, 2001);
331 fn syntax_highlighting_not_quadratic() {
332 if skip_slow_tests() {
336 let mut al = AssertLinear::default();
337 while al.next_round() {
341 let fixture = bench_fixture::big_struct_n(n);
342 let (analysis, file_id) = fixture::file(&fixture);
344 let time = Instant::now();
350 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
352 assert!(hash > n as usize);
354 let elapsed = time.elapsed();
355 al.sample(n as f64, elapsed.as_millis() as f64);
361 fn benchmark_syntax_highlighting_parser() {
362 if skip_slow_tests() {
366 let fixture = bench_fixture::glorious_old_parser();
367 let (analysis, file_id) = fixture::file(&fixture);
370 let _pt = bench("syntax highlighting parser");
375 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
378 assert_eq!(hash, 1616);
383 let (analysis, file_id) = fixture::file(
385 #[derive(Clone, Debug)]
394 let highlights = &analysis
395 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
398 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
402 fn test_flattening() {
405 fn fixture(ra_fixture: &str) {}
411 println!("2 + 2 = {}", 4);
417 expect_file!["./test_data/highlight_injection.html"],
424 let (analysis, file_id) = fixture::file(
431 let _ = analysis.highlight(file_id).unwrap();
435 fn test_string_highlighting() {
436 // The format string detection is based on macro-expansion,
437 // thus, we have to copy the macro definition from `std`
440 macro_rules! println {
442 $crate::io::_print($crate::format_args_nl!($($arg)*));
445 #[rustc_builtin_macro]
447 macro_rules! format_args {}
448 #[rustc_builtin_macro]
450 macro_rules! const_format_args {}
451 #[rustc_builtin_macro]
453 macro_rules! format_args_nl {}
456 pub macro panic_2015 {
458 $crate::panicking::panic("explicit panic")
460 ($msg:literal $(,)?) => (
461 $crate::panicking::panic($msg)
463 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
464 ($msg:expr $(,)?) => (
465 $crate::panicking::panic_str($msg)
467 // Special-case the single-argument case for const_panic.
468 ("{}", $arg:expr $(,)?) => (
469 $crate::panicking::panic_display(&$arg)
471 ($fmt:expr, $($arg:tt)+) => (
472 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
477 #[rustc_builtin_macro(std_panic)]
479 macro_rules! panic {}
480 #[rustc_builtin_macro]
481 macro_rules! assert {}
482 #[rustc_builtin_macro]
486 () => ($crate::panic!("not yet implemented"));
487 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
491 // from https://doc.rust-lang.org/std/fmt/index.html
492 println!("Hello"); // => "Hello"
493 println!("Hello, {}!", "world"); // => "Hello, world!"
494 println!("The number is {}", 1); // => "The number is 1"
495 println!("{:?}", (3, 4)); // => "(3, 4)"
496 println!("{value}", value=4); // => "4"
497 println!("{} {}", 1, 2); // => "1 2"
498 println!("{:04}", 42); // => "0042" with leading zerosV
499 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
500 println!("{argument}", argument = "test"); // => "test"
501 println!("{name} {}", 1, name = 2); // => "2 1"
502 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
503 println!("{{{}}}", 2); // => "{2}"
504 println!("Hello {:5}!", "x");
505 println!("Hello {:1$}!", "x", 5);
506 println!("Hello {1:0$}!", 5, "x");
507 println!("Hello {:width$}!", "x", width = 5);
508 println!("Hello {:<5}!", "x");
509 println!("Hello {:-<5}!", "x");
510 println!("Hello {:^5}!", "x");
511 println!("Hello {:>5}!", "x");
512 println!("Hello {:+}!", 5);
513 println!("{:#x}!", 27);
514 println!("Hello {:05}!", 5);
515 println!("Hello {:05}!", -5);
516 println!("{:#010x}!", 27);
517 println!("Hello {0} is {1:.5}", "x", 0.01);
518 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
519 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
520 println!("Hello {} is {:.*}", "x", 5, 0.01);
521 println!("Hello {} is {2:.*}", "x", 5, 0.01);
522 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
523 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
524 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
525 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
526 println!("Hello {{}}");
527 println!("{{ Hello");
529 println!(r"Hello, {}!", "world");
532 println!("Hello\nWorld");
533 println!("\u{48}\x65\x6C\x6C\x6F World");
535 println!("{\x41}", A = 92);
536 println!("{ничоси}", ничоси = 92);
538 println!("{:x?} {} ", thingy, n2);
540 panic!("more {}", 1);
541 assert!(true, "{}", 1);
542 assert!(true, "{} asdasd", 1);
544 asm!("mov eax, {0}");
545 format_args!(concat!("{}"), "{}");
548 expect_file!["./test_data/highlight_strings.html"],
554 fn test_unsafe_highlighting() {
557 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
558 static GLOBAL: Struct = Struct { field: 0 };
559 unsafe fn unsafe_fn() {}
566 struct Struct { field: i32 }
568 unsafe fn unsafe_method(&self) {}
576 unsafe trait UnsafeTrait {}
577 unsafe impl UnsafeTrait for Packed {}
578 impl !UnsafeTrait for () {}
580 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
583 fn calls_autoref(&self);
586 impl DoTheAutoref for u16 {
587 fn calls_autoref(&self) {}
591 let x = &5 as *const _ as *const usize;
592 let u = Union { b: 0 };
594 // unsafe fn and method calls
598 Union { b: 0 } => (),
601 Struct { field: 0 }.unsafe_method();
606 // unsafe access to a static mut
610 // unsafe ref of packed fields
611 let packed = Packed { a: 0 };
613 let ref a = packed.a;
614 let Packed { ref a } = packed;
615 let Packed { a: ref _a } = packed;
617 // unsafe auto ref of packed field
618 packed.a.calls_autoref();
623 expect_file!["./test_data/highlight_unsafe.html"],
629 fn test_highlight_doc_comment() {
632 //! This is a module to test doc injection.
638 /// let _ = "early doctests should not go boom";
644 /// This is an impl with a code block.
657 pub const bar: bool = true;
659 /// Constructs a new `Foo`.
664 /// # #![allow(unused_mut)]
665 /// let mut foo: Foo = Foo::new();
667 pub const fn new() -> Foo {
671 /// `bar` method on `Foo`.
678 /// let foo = Foo::new();
680 /// // calls bar on foo
681 /// assert!(foo.bar());
683 /// let bar = foo.bar || Foo::bar;
688 /// let multi_line_string = "Foo
695 /// let foobar = Foo::new().bar();
701 pub fn foo(&self) -> bool {
706 /// [`Foo`](Foo) is a struct
707 /// This function is > [`all_the_links`](all_the_links) <
708 /// [`noop`](noop) is a macro below
709 /// [`Item`] is a struct in the module [`module`]
711 /// [`Item`]: module::Item
712 /// [mix_and_match]: ThisShouldntResolve
713 pub fn all_the_links() {}
720 /// macro_rules! noop { ($expr:expr) => { $expr }}
730 /// let _ = example(&[1, 2, 3]);
735 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
739 #[cfg_attr(feature = "alloc", doc = "```rust")]
740 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
741 /// let _ = example(&alloc::vec![1, 2, 3]);
743 pub fn mix_and_match() {}
746 It is beyond me why you'd use these when you got ///
748 let _ = example(&[1, 2, 3]);
750 [`block_comments2`] tests these with indentation
752 pub fn block_comments() {}
755 Really, I don't get it
757 let _ = example(&[1, 2, 3]);
759 [`block_comments`] tests these without indentation
761 pub fn block_comments2() {}
764 expect_file!["./test_data/highlight_doctest.html"],
770 fn test_extern_crate() {
773 //- /main.rs crate:main deps:std,alloc
775 extern crate alloc as abc;
776 //- /std/lib.rs crate:std
778 //- /alloc/lib.rs crate:alloc
781 expect_file!["./test_data/highlight_extern_crate.html"],
787 fn test_crate_root() {
790 //- minicore: iterators
791 //- /main.rs crate:main deps:foo
795 pub const NINETY_TWO: u8 = 92;
799 pub(crate) fn main() {
800 let baz = iter::repeat(92);
804 pub(in super) const FORTY_TWO: u8 = 42;
807 use super::super::NINETY_TWO;
808 use crate::foooo::Point;
810 pub(in super::super) const TWENTY_NINE: u8 = 29;
813 //- /foo.rs crate:foo
820 pub(super) fn swap(p: crate::Point) -> crate::Point {
821 crate::Point { x: p.y, y: p.x }
825 expect_file!["./test_data/highlight_crate_root.html"],
831 fn test_default_library() {
834 //- minicore: option, iterators
839 let nums = iter::repeat(foo.unwrap());
842 expect_file!["./test_data/highlight_default_library.html"],
848 fn test_associated_function() {
856 pub fn is_static() {}
857 pub fn is_not_static(&self) {}
862 fn t_is_not_static(&self) {}
866 pub fn is_static() {}
867 pub fn is_not_static(&self) {}
870 expect_file!["./test_data/highlight_assoc_functions.html"],
876 fn test_injection() {
879 fn f(ra_fixture: &str) {}
889 expect_file!["./test_data/injection.html"],
894 /// Highlights the code given by the `ra_fixture` argument, renders the
895 /// result as HTML, and compares it with the HTML file given as `snapshot`.
896 /// Note that the `snapshot` file is overwritten by the rendered HTML.
897 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
898 let (analysis, file_id) = fixture::file(ra_fixture);
899 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
900 expect.assert_eq(actual_html)