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> {}
117 fn bar(&self) -> i32;
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 {
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_keyword_highlighting() {
353 struct __ where Self:;
356 expect_file!["./test_data/highlight_keywords.html"],
362 fn test_string_highlighting() {
363 // The format string detection is based on macro-expansion,
364 // thus, we have to copy the macro definition from `std`
367 macro_rules! println {
369 $crate::io::_print($crate::format_args_nl!($($arg)*));
372 #[rustc_builtin_macro]
374 macro_rules! format_args {}
375 #[rustc_builtin_macro]
377 macro_rules! const_format_args {}
378 #[rustc_builtin_macro]
380 macro_rules! format_args_nl {}
383 pub macro panic_2015 {
385 $crate::panicking::panic("explicit panic")
387 ($msg:literal $(,)?) => (
388 $crate::panicking::panic($msg)
390 // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint.
391 ($msg:expr $(,)?) => (
392 $crate::panicking::panic_str($msg)
394 // Special-case the single-argument case for const_panic.
395 ("{}", $arg:expr $(,)?) => (
396 $crate::panicking::panic_display(&$arg)
398 ($fmt:expr, $($arg:tt)+) => (
399 $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
404 #[rustc_builtin_macro(std_panic)]
406 macro_rules! panic {}
407 #[rustc_builtin_macro]
408 macro_rules! assert {}
409 #[rustc_builtin_macro]
413 () => ($crate::panic!("not yet implemented"));
414 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
418 // from https://doc.rust-lang.org/std/fmt/index.html
419 println!("Hello"); // => "Hello"
420 println!("Hello, {}!", "world"); // => "Hello, world!"
421 println!("The number is {}", 1); // => "The number is 1"
422 println!("{:?}", (3, 4)); // => "(3, 4)"
423 println!("{value}", value=4); // => "4"
424 println!("{} {}", 1, 2); // => "1 2"
425 println!("{:04}", 42); // => "0042" with leading zerosV
426 println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
427 println!("{argument}", argument = "test"); // => "test"
428 println!("{name} {}", 1, name = 2); // => "2 1"
429 println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"
430 println!("{{{}}}", 2); // => "{2}"
431 println!("Hello {:5}!", "x");
432 println!("Hello {:1$}!", "x", 5);
433 println!("Hello {1:0$}!", 5, "x");
434 println!("Hello {:width$}!", "x", width = 5);
435 println!("Hello {:<5}!", "x");
436 println!("Hello {:-<5}!", "x");
437 println!("Hello {:^5}!", "x");
438 println!("Hello {:>5}!", "x");
439 println!("Hello {:+}!", 5);
440 println!("{:#x}!", 27);
441 println!("Hello {:05}!", 5);
442 println!("Hello {:05}!", -5);
443 println!("{:#010x}!", 27);
444 println!("Hello {0} is {1:.5}", "x", 0.01);
445 println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
446 println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
447 println!("Hello {} is {:.*}", "x", 5, 0.01);
448 println!("Hello {} is {2:.*}", "x", 5, 0.01);
449 println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
450 println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
451 println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
452 println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56");
453 println!("Hello {{}}");
454 println!("{{ Hello");
456 println!(r"Hello, {}!", "world");
459 println!("Hello\nWorld");
460 println!("\u{48}\x65\x6C\x6C\x6F World");
462 let _ = "\x28\x28\x00\x63\n";
463 let _ = b"\x28\x28\x00\x63\n";
465 println!("{\x41}", A = 92);
466 println!("{ничоси}", ничоси = 92);
468 println!("{:x?} {} ", thingy, n2);
470 panic!("more {}", 1);
471 assert!(true, "{}", 1);
472 assert!(true, "{} asdasd", 1);
474 asm!("mov eax, {0}");
475 format_args!(concat!("{}"), "{}");
477 expect_file!["./test_data/highlight_strings.html"],
483 fn test_unsafe_highlighting() {
491 macro_rules! unsafe_deref {
496 static mut MUT_GLOBAL: Struct = Struct { field: 0 };
497 static GLOBAL: Struct = Struct { field: 0 };
498 unsafe fn unsafe_fn() {}
505 struct Struct { field: i32 }
507 unsafe fn unsafe_method(&self) {}
515 unsafe trait UnsafeTrait {}
516 unsafe impl UnsafeTrait for Packed {}
517 impl !UnsafeTrait for () {}
519 fn unsafe_trait_bound<T: UnsafeTrait>(_: T) {}
522 fn calls_autoref(&self);
525 impl DoTheAutoref for u16 {
526 fn calls_autoref(&self) {}
530 let x = &5 as *const _ as *const usize;
531 let u = Union { b: 0 };
534 unsafe { unsafe_deref!() }
539 id! { unsafe_deref!() };
541 // unsafe fn and method calls
545 Union { b: 0 } => (),
548 Struct { field: 0 }.unsafe_method();
553 // unsafe access to a static mut
557 // unsafe ref of packed fields
558 let packed = Packed { a: 0 };
560 let ref a = packed.a;
561 let Packed { ref a } = packed;
562 let Packed { a: ref _a } = packed;
564 // unsafe auto ref of packed field
565 packed.a.calls_autoref();
569 expect_file!["./test_data/highlight_unsafe.html"],
575 fn test_highlight_doc_comment() {
579 //! This is a module to test doc injection.
587 /// let _ = "early doctests should not go boom";
593 /// This is an impl with a code block.
606 pub const bar: bool = true;
608 /// Constructs a new `Foo`.
613 /// # #![allow(unused_mut)]
614 /// let mut foo: Foo = Foo::new();
616 pub const fn new() -> Foo {
620 /// `bar` method on `Foo`.
627 /// let foo = Foo::new();
629 /// // calls bar on foo
630 /// assert!(foo.bar());
632 /// let bar = foo.bar || Foo::bar;
637 /// let multi_line_string = "Foo
644 /// let foobar = Foo::new().bar();
648 /// // code block with tilde.
649 /// let foobar = Foo::new().bar();
654 /// fn foo<T, const X: usize>(arg: i32) {
662 pub fn foo(&self) -> bool {
667 /// [`Foo`](Foo) is a struct
668 /// This function is > [`all_the_links`](all_the_links) <
669 /// [`noop`](noop) is a macro below
670 /// [`Item`] is a struct in the module [`module`]
672 /// [`Item`]: module::Item
673 /// [mix_and_match]: ThisShouldntResolve
674 pub fn all_the_links() {}
681 /// macro_rules! noop { ($expr:expr) => { $expr }}
691 /// let _ = example(&[1, 2, 3]);
696 #[cfg_attr(not(feature = "false"), doc = "loop {}")]
700 #[cfg_attr(feature = "alloc", doc = "```rust")]
701 #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
702 /// let _ = example(&alloc::vec![1, 2, 3]);
704 pub fn mix_and_match() {}
707 It is beyond me why you'd use these when you got ///
709 let _ = example(&[1, 2, 3]);
711 [`block_comments2`] tests these with indentation
713 pub fn block_comments() {}
716 Really, I don't get it
718 let _ = example(&[1, 2, 3]);
720 [`block_comments`] tests these without indentation
722 pub fn block_comments2() {}
724 //- /outline_module.rs
725 //! This is an outline module whose purpose is to test that its inline attribute injection does not
726 //! spill into its parent.
731 expect_file!["./test_data/highlight_doctest.html"],
737 fn test_extern_crate() {
740 //- /main.rs crate:main deps:std,alloc
742 extern crate alloc as abc;
743 //- /std/lib.rs crate:std
745 //- /alloc/lib.rs crate:alloc
748 expect_file!["./test_data/highlight_extern_crate.html"],
754 fn test_crate_root() {
757 //- minicore: iterators
758 //- /main.rs crate:main deps:foo
762 pub const NINETY_TWO: u8 = 92;
766 pub(crate) fn main() {
767 let baz = iter::repeat(92);
771 pub(in super) const FORTY_TWO: u8 = 42;
774 use super::super::NINETY_TWO;
775 use crate::foooo::Point;
777 pub(in super::super) const TWENTY_NINE: u8 = 29;
780 //- /foo.rs crate:foo
787 pub(super) fn swap(p: crate::Point) -> crate::Point {
788 crate::Point { x: p.y, y: p.x }
792 expect_file!["./test_data/highlight_crate_root.html"],
798 fn test_default_library() {
801 //- minicore: option, iterators
806 let nums = iter::repeat(foo.unwrap());
809 expect_file!["./test_data/highlight_default_library.html"],
815 fn test_associated_function() {
823 pub fn is_static() {}
824 pub fn is_not_static(&self) {}
829 fn t_is_not_static(&self) {}
833 pub fn is_static() {}
834 pub fn is_not_static(&self) {}
837 expect_file!["./test_data/highlight_assoc_functions.html"],
843 fn test_injection() {
846 fn fixture(ra_fixture: &str) {}
852 println!("2 + 2 = {}", 4);
865 expect_file!["./test_data/highlight_injection.html"],
871 fn test_operators() {
875 1 + 1 - 1 * 1 / 1 % 1 | 1 & 1 ! 1 ^ 1 >> 1 << 1;
889 expect_file!["./test_data/highlight_operators.html"],
895 fn test_rainbow_highlighting() {
900 let x = hello.to_string();
901 let y = hello.to_string();
903 let x = "other color please!";
904 let y = x.to_string();
908 let mut hello = "hello";
911 expect_file!["./test_data/highlight_rainbow.html"],
918 let (analysis, file_id) = fixture::file(
920 #[derive(Clone, Debug)]
929 let highlights = &analysis
930 .highlight_range(FileRange { file_id, range: TextRange::at(45.into(), 1.into()) })
933 assert_eq!(&highlights[0].highlight.to_string(), "field.declaration.public");
938 let (analysis, file_id) = fixture::file(
945 let _ = analysis.highlight(file_id).unwrap();
948 /// Highlights the code given by the `ra_fixture` argument, renders the
949 /// result as HTML, and compares it with the HTML file given as `snapshot`.
950 /// Note that the `snapshot` file is overwritten by the rendered HTML.
951 fn check_highlighting(ra_fixture: &str, expect: ExpectFile, rainbow: bool) {
952 let (analysis, file_id) = fixture::file(ra_fixture.trim());
953 let actual_html = &analysis.highlight_as_html(file_id, rainbow).unwrap();
954 expect.assert_eq(actual_html)
958 fn benchmark_syntax_highlighting_long_struct() {
959 if skip_slow_tests() {
963 let fixture = bench_fixture::big_struct();
964 let (analysis, file_id) = fixture::file(&fixture);
967 let _pt = bench("syntax highlighting long struct");
972 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
975 assert_eq!(hash, 2001);
979 fn syntax_highlighting_not_quadratic() {
980 if skip_slow_tests() {
984 let mut al = AssertLinear::default();
985 while al.next_round() {
989 let fixture = bench_fixture::big_struct_n(n);
990 let (analysis, file_id) = fixture::file(&fixture);
992 let time = Instant::now();
998 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Struct))
1000 assert!(hash > n as usize);
1002 let elapsed = time.elapsed();
1003 al.sample(n as f64, elapsed.as_millis() as f64);
1009 fn benchmark_syntax_highlighting_parser() {
1010 if skip_slow_tests() {
1014 let fixture = bench_fixture::glorious_old_parser();
1015 let (analysis, file_id) = fixture::file(&fixture);
1018 let _pt = bench("syntax highlighting parser");
1023 .filter(|it| it.highlight.tag == HlTag::Symbol(SymbolKind::Function))
1026 assert_eq!(hash, 1609);