### Example installation output Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/setup.md Expected output format showing the path to the installed rust-analyzer binary. ```text Installing Installed package `rust-analyzer v0.0.0 ()` (executable `rust-analyzer.exe`) ``` -------------------------------- ### Struct Constructor Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html Example usage for the Foo constructor. ```rust # #![allow(unused_mut)] let mut foo: Foo = Foo::new(); ``` -------------------------------- ### Build and install only the LSP server Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/vs_code.md Compile and install only the language server component from source. ```bash cargo xtask install --server ``` -------------------------------- ### Build and install from source Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/vs_code.md Clone the repository and use the xtask script to build and install both the server and the VS Code plugin. ```bash git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer cargo xtask install ``` -------------------------------- ### Foo Method Examples Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html Various examples demonstrating method usage, multi-line comments, and string literals. ```rust use x::y; let foo = Foo::new(); // calls bar on foo assert!(foo.bar()); let bar = foo.bar || Foo::bar; /* multi-line comment */ let multi_line_string = "Foo bar\n "; ``` ```rust let foobar = Foo::new().bar(); ``` ```rust // code block with tilde. let foobar = Foo::new().bar(); ``` ```rust // functions fn foo(arg: i32) { let x: T = X; } ``` ```sh echo 1 ``` -------------------------------- ### Install rust-analyzer on Linux Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/rust_analyzer_binary.md Installs the rust-analyzer binary to ~/.local/bin. Ensure the URL is correct for your system architecture. ```bash mkdir -p ~/.local/bin curl -L https://github.com/rust-lang/rust-analyzer/releases/latest/download/rust-analyzer-x86_64-unknown-linux-gnu.gz | gunzip -c - > ~/.local/bin/rust-analyzer chmod +x ~/.local/bin/rust-analyzer ``` -------------------------------- ### Installing proc-macro Server with xtask Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/proc-macro-srv-cli/README.md Recommended method to install the proc-macro server for local testing purposes using the xtask command. ```bash # Recommended: use the xtask command cargo xtask install --proc-macro-server ``` -------------------------------- ### Install rust-analyzer locally Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/setup.md Use the xtask command to build and install the language server binary for a specific editor instance. ```sh # Install only the language server cargo xtask install --server \ --code-bin code-insiders \ # Target a specific editor (code, code-exploration, code-insiders, codium, or code-oss) --dev-rel # Build in release mode with debug info level 2 ``` -------------------------------- ### Install mdbook and Serve Documentation Locally Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/README.md Installs the mdbook tool and serves the documentation site locally. Changes to documentation files will trigger automatic rebuilds. ```bash cargo install mdbook cargo xtask codegen cd docs/book mdbook serve ``` -------------------------------- ### Install TypeScript dependencies Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/debugging.md Navigate to the extension directory and install dependencies using npm. ```bash cd editors/code npm ci ``` -------------------------------- ### Discover Command Output - Progress Event Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Example of a progress event output by the discover command in JSONL format. ```json {"kind":"progress","message":"generating rust-project.json"} ``` -------------------------------- ### Install rust-analyzer on macOS with Homebrew Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/rust_analyzer_binary.md Installs rust-analyzer using Homebrew on macOS. ```bash brew install rust-analyzer ``` -------------------------------- ### Discover Command Output - Finished Event Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Example of a finished event output by the discover command, indicating successful project data generation. ```json { "kind": "finished", "buildfile": "rust-analyzer/BUCK", "project": { "sysroot": "foo", "crates": [] } } ``` -------------------------------- ### On Enter Request Example (Before) Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Demonstrates the code context for the `experimental/onEnter` request, triggered by pressing the Enter key. This example shows a comment line. ```rust fn main() { // Some /*cursor here*/ docs let x = 92; } ``` -------------------------------- ### Configuration Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/xtask/test_data/expected.md This JSON snippet demonstrates a basic configuration setting. It is typically used for setting up tools or features. ```json {"foo":"bar"} ``` -------------------------------- ### Install rust-analyzer on Arch Linux Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/rust_analyzer_binary.md Installs rust-analyzer using pacman on Arch Linux. This installs the version built from the latest tagged source. ```bash pacman -S rust-analyzer ``` -------------------------------- ### Install rust-analyzer from Source Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/rust_analyzer_binary.md Installs rust-analyzer from source using cargo xtask. Requires the latest stable Rust toolchain. ```bash git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer cargo xtask install --server ``` -------------------------------- ### Example for Hover Range Selection Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Illustrates using a `Range` in `HoverParams` to get hover information for a selected expression. ```rust fn main() { let expression = $01 + 2 * 3$0; } ``` -------------------------------- ### Install rustc-josh-sync tool Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/README.md Install the synchronization tool for managing subtree changes between rust-analyzer and rust-lang/rust repositories. ```bash cargo install --locked --git https://github.com/rust-lang/josh-sync ``` -------------------------------- ### Install vim-lsp plugin Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/other_editors.md Add the plugin to your .vimrc file. ```vim Plug 'prabirshrestha/vim-lsp' ``` -------------------------------- ### Discover Command Path Invocation Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Example of how rust-analyzer uses the path invocation to find and generate a rust-project.json. ```shell rust-project develop-json '{ "path": "myproject/src/main.rs" }' ``` -------------------------------- ### Discover Command Buildfile Invocation Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Example of how rust-analyzer uses a build file invocation to update an existing workspace configuration. ```shell rust-project develop-json '{ "buildfile": "myproject/BUCK" }' ``` -------------------------------- ### Impl Block Documentation Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html Documentation example within an implementation block. ```rust fn foo() { } ``` -------------------------------- ### Install rust-analyzer Client Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/README.md After fixing the VS Code extension, use `cargo xtask install --client` to install the updated client. This command ensures the latest changes are applied to the extension. ```bash cargo xtask install --client ``` -------------------------------- ### Minimal Bug Reproduction Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/troubleshooting.md A template for creating a minimal reproducible example for bug reports. Includes cloning a repo, checking out a specific commit, and running analysis stats. ```bash git clone https://github.com/username/repo.git && cd repo && git switch --detach commit-hash rust-analyzer --version rust-analyzer dd12184e4 2021-05-08 dev rust-analyzer analysis-stats . ``` -------------------------------- ### Workspace Configuration Discovery Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Configure a command to dynamically obtain workspace configuration. This is an alternative to manually generating rust-project.json. ```json { "command": [ "rust-project", "develop-json", "{arg}" ], "progressLabel": "buck2/rust-project", "filesToWatch": [ "BUCK" ] } ``` -------------------------------- ### Early Struct Documentation Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html Documentation example placed before a struct definition. ```rust let _ = "early doctests should not go boom"; ``` -------------------------------- ### Mix and Match Documentation Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html Examples demonstrating conditional documentation attributes and mixed content. ```rust let _ = example(&[1, 2, 3]); ``` ```rust loop {} ``` ```rust let _ = example(&alloc::vec![1, 2, 3]); ``` -------------------------------- ### Join Lines Example (Before) Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Shows the code state before the `experimental/joinLines` request is applied. The server will process this to join the lines. ```rust fn main() { /*cursor here*/let x = { 92 }; } ``` -------------------------------- ### Install npm Dependencies and Lint Code Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/README.md Navigate to the `editors/code` directory and run `npm ci` to install dependencies, followed by `npm run lint` to check for code style issues. This is part of the process for changing files under `editors/code`. ```bash cd editors/code npm ci npm run lint ``` -------------------------------- ### Rust Module and Visibility Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_crate_root.html Demonstrates module nesting, crate-level imports, and scoped visibility modifiers for constants. ```rust extern crate foo; use core::iter; pub const NINETY_TWO: u8 = 92; use foo as foooo; pub(crate) fn main() { let baz = iter::repeat(92); } mod bar { pub(in super) const FORTY_TWO: u8 = 42; mod baz { use super::super::NINETY_TWO; use crate::foooo::Point; pub(in super::super) const TWENTY_NINE: u8 = 29; } } ``` -------------------------------- ### Install VS Code extension via CLI Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/vs_code.md Use the command line to install a downloaded VSIX file for the rust-analyzer extension. ```bash code --install-extension /path/to/rust-analyzer.vsix ``` -------------------------------- ### Rebuild and reinstall server Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/setup.md Commands to verify the project and update the local installation after making code changes. ```sh cargo check cargo xtask install --server --code-bin code-insiders --dev-rel ``` -------------------------------- ### Macro Formatting and Assertions Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html Examples of using println!, panic!, assert!, and custom macros with various formatting arguments. ```rust println!("{\x41}", A = 92); println!("{ничоси}", ничоси = 92); println!("{:x?} {} ", thingy, n2); panic!("{}", 0); panic!("more {}", 1); assert!(true, "{}", 1); assert!(true, "{} asdasd", 1); toho!("{}fmt", 0); ``` -------------------------------- ### Block Comment Documentation Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html Examples using block comments for documentation. ```rust let _ = example(&[1, 2, 3]); ``` ```rust let _ = example(&[1, 2, 3]); ``` -------------------------------- ### Example for experimental/openCargoToml Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Demonstrates the usage of the `experimental/openCargoToml` request, showing a cursor position within a Cargo.toml file. ```rust // Cargo.toml [package] // src/main.rs /* cursor here*/ ``` -------------------------------- ### Parent Module Navigation Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Illustrates the context for the `experimental/parentModule` request, which helps the client navigate to the parent module declaration. ```rust // src/main.rs mod foo; // src/foo.rs /* cursor here*/ ``` -------------------------------- ### Join Lines Example (After) Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Illustrates the result after the `experimental/joinLines` request, where the curly braces are removed and the lines are joined. ```rust fn main() { let x = 92; } ``` -------------------------------- ### Character Literals and Formatting Examples Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html Demonstrates various character literal types and extensive usage of the println! macro for string formatting. ```rust fn main() { let a = '\n'; let a = '\t'; let a = '\e'; // invalid escape let a = 'e'; let a = ' '; let a = '\u{48}'; let a = '\u{4823}'; let a = '\x65'; let a = '\x00'; let a = b'\xFF'; println!("Hello {{Hello}}"); // from https://doc.rust-lang.org/std/fmt/index.html println!("Hello"); // => "Hello" println!("Hello, {}!", "world"); // => "Hello, world!" println!("The number is {}", 1); // => "The number is 1" println!("{:?}", (3, 4)); // => "(3, 4)" println!("{value}", value=4); // => "4" println!("{} {}", 1, 2); // => "1 2" println!("{:04}", 42); // => "0042" with leading zerosV println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" println!("{argument}", argument = "test"); // => "test" println!("{name} {}", 1, name = 2); // => "2 1" println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" println!("{{{}}}", 2); // => "{2}" println!("Hello {:5}!", "x"); println!("Hello {:1$}!", "x", 5); println!("Hello {1:0$}!", 5, "x"); println!("Hello {:width$}!", "x", width = 5); println!("Hello {:<5}!", "x"); println!("Hello {:-<5}!", "x"); println!("Hello {:^5}!", "x"); println!("Hello {:>5}!", "x"); println!("Hello {:+}!", 5); println!("{:#x}!", 27); println!("Hello {:05}!", 5); println!("Hello {:05}!", -5); println!("{:#010x}!", 27); println!("Hello {0} is {1:.5}", "x", 0.01); println!("Hello {1} is {2:.0$}", 5, "x", 0.01); println!("Hello {0} is {2:.1$}", "x", 5, 0.01); println!("Hello {} is {:.*}", "x", 5, 0.01); println!("Hello {} is {2:.*}", "x", 5, 0.01); println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); let _ = "{}" } ``` -------------------------------- ### Hierarchical Profiler Output Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/architecture.md Example output from the `hprof` profiler, showing time spent in different functions. Enabled with `RA_PROFILE='*>50'`. ```text 85ms - handle_completion 68ms - import_on_the_fly 67ms - import_assets::search_for_relative_paths 0ms - crate_def_map:wait (804 calls) 0ms - find_path (16 calls) 2ms - find_similar_imports (1 calls) 0ms - generic_params_query (334 calls) 59ms - trait_solve_query (186 calls) 0ms - Semantics::analyze_impl (1 calls) 1ms - render_resolution (8 calls) 0ms - Semantics::analyze_impl (5 calls) ``` -------------------------------- ### Add rust-analyzer via rustup Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/rust_analyzer_binary.md Installs rust-analyzer as a component using rustup. ```bash rustup component add rust-analyzer ``` -------------------------------- ### Structural Search Replace Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Provides an example of an SSR query transforming `foo($a, $b)` into `($a).foo($b)`, demonstrating a basic syntax tree-based code transformation. ```string SSR with query `foo($a, $b) ==>> ($a).foo($b)` will transform, eg `foo(y + 5, z)` into `(y + 5).foo(z)`. ``` -------------------------------- ### Discover Argument Substitution Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Illustrates the substitution of the {arg} placeholder in the discover command with a JSON-serialized enum representing either a path or a buildfile. ```rust #[derive(PartialEq, Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum DiscoverArgument { Path(AbsPathBuf), Buildfile(AbsPathBuf), } ``` -------------------------------- ### Example of Hover Actions UI Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Illustrates how command link groups are displayed in the UI, with and without titles. ```plaintext +-----------------------------+ | Hover content | | | +-----------------------------+ | _Action1_ | _Action2_ | +-----------------------------+ | TITLE _Action1_ | _Action2_ | +-----------------------------+ ... ``` -------------------------------- ### Running proc-macro-srv-cli with Required Environment Variable Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/proc-macro-srv-cli/README.md Example of how to run the proc-macro-srv-cli binary, demonstrating the necessity of setting the `RUST_ANALYZER_INTERNALS_DO_NOT_USE` environment variable. ```bash RUST_ANALYZER_INTERNALS_DO_NOT_USE=1 rust-analyzer-proc-macro-srv --version ``` -------------------------------- ### Module Doc Injection Test Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html A basic module-level documentation example. ```rust fn test() {} ``` -------------------------------- ### Configure Runnable for Tests Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/non_cargo_based_projects.md Example JSON configuration for a test runnable within the rust-project.json file. ```json { "program": "buck", "args": [ "test", "{label}", "--", "{test_id}", "--print-passing-details" ], "cwd": "/home/user/repo-root/", "kind": "testOne" } ``` -------------------------------- ### Example Usage of Matching Brace Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Illustrates a scenario where the 'experimental/matchingBrace' request might be used in a Rust code snippet. ```rust fn main() { let x: Vec<()>/*cursor here*/ = vec![]; } ``` -------------------------------- ### Install Rust Standard Library Source Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/installation.md Use this command to add the Rust standard library source code, which is required by rust-analyzer. Ensure you are using a compatible toolchain. ```bash rustup component add rust-src ``` -------------------------------- ### On Enter Request Example (After) Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Shows the snippet returned by the `experimental/onEnter` request, demonstrating comment continuation and automatic indentation. The `$0` indicates the final cursor position. ```rust fn main() { // Some // $0 docs let x = 92; } ``` -------------------------------- ### Rust Syntax and Keyword Usage Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_keywords_2015.html Examples of module imports, macro definitions, and various Rust keywords including edition-dependent and reserved identifiers. ```rust extern crate self; use crate; use self; mod __ { use super::*; } macro_rules! void { ($($tt:tt)*) => {discard!($($tt:tt)*)} } struct __ where Self:; fn __(_: Self) {} void!(Self); // edition dependent void!(try async await gen); // edition and context dependent void!(dyn); // builtin custom syntax void!(builtin offset_of format_args asm); // contextual void!(macro_rules, union, default, raw, auto, yeet); // reserved void!(abstract become box do final macro override priv typeof unsized virtual yield); void!('static 'self 'unsafe) ``` -------------------------------- ### Custom Macro Definitions Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html Examples of defining macros using macro_rules! and the experimental macro keyword for panic handling and string formatting. ```rust macro_rules! println { ($($arg:tt)*) => ({ $crate::io::_print(format_args_nl!($($arg)*)); }) } mod panic { pub macro panic_2015 { () => ( panic("explicit panic") ), ($msg:literal $(,)?) => ( panic($msg) ), // Use `panic_str` instead of `panic_display::<&str>` for non_fmt_panic lint. ($msg:expr $(,)?) => ( panic_str($msg) ), // Special-case the single-argument case for const_panic. ("{}", $arg:expr $(,)?) => ( panic_display(&$arg) ), ($fmt:expr, $($arg:tt)+) => ( panic_fmt(const_format_args!($fmt, $($arg)+)) ), } } macro_rules! toho { () => ($crate::panic!("not yet implemented")); ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", format_args!($($arg)+))); } macro_rules! reuse_twice { ($literal:literal) => {{stringify!($literal); format_args!($literal)}}; } ``` -------------------------------- ### Rust Mutable Reference Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_issue_19357.html Demonstrates the creation of a mutable raw pointer in Rust. This syntax is typically used in unsafe blocks or for specific low-level operations. ```rust fn main() { let x = &raw mut 5; } ``` -------------------------------- ### Define Rust Fixture with Function and Placeholder Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_injection.html This example demonstrates defining a fixture with a function and a placeholder `$0` which is often used for cursor positioning or code insertion points in testing scenarios. ```rust fixture(r" fn foo() { foo($0{ 92 }$0) }" ); ``` -------------------------------- ### Configure Kakoune for rust-analyzer Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/other_editors.md This Kakoune script enables LSP for Rust files, sets up auto-formatting on save, and configures inlay hints. Ensure `kak-lsp` is installed and configured. ```shell eval %sh{kak-lsp --kakoune -s $kak_session} # Not needed if you load it with plug.kak. hook global WinSetOption filetype=rust %{ # Enable LSP lsp-enable-window # Auto-formatting on save hook window BufWritePre .* lsp-formatting-sync # Configure inlay hints (only on save) hook window -group rust-inlay-hints BufWritePost .* rust-analyzer-inlay-hints hook -once -always window WinSetOption filetype=.* %{ remove-hooks window rust-inlay-hints } } ``` -------------------------------- ### Set up release environment Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/README.md Ensure rust-analyzer, rust-analyzer.github.io, and rust-lang/rust repositories are checked out in the same directory. The 'rust-analyzer' remote must be named 'upstream'. ```bash ./rust-analyzer ./rust-analyzer.github.io ./rust-rust-analyzer # Note the name! ``` -------------------------------- ### Building proc-macro-srv-cli with `in-rust-tree` Feature Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/proc-macro-srv-cli/README.md Instructions for building the proc-macro-srv-cli binary with the necessary `in-rust-tree` feature, using either a nightly toolchain or stable with `RUSTC_BOOTSTRAP=1`. ```bash # Using nightly toolchain cargo build -p proc-macro-srv-cli --features in-rust-tree ``` ```bash # Or with RUSTC_BOOTSTRAP on stable RUSTC_BOOTSTRAP=1 cargo build -p proc-macro-srv-cli --features in-rust-tree ``` -------------------------------- ### Check rust-analyzer Version Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/troubleshooting.md Verify the installed rust-analyzer version. Update if the version is older than a week. ```bash rust-analyzer --version ``` -------------------------------- ### Numeric Literal Tokenization Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/parser/test_data/lexer/ok/numbers.txt Examples of integer and floating-point literals including various bases, underscores, and suffixes. ```text INT_NUMBER "0" WHITESPACE " " INT_NUMBER "00" WHITESPACE " " INT_NUMBER "0_" WHITESPACE " " FLOAT_NUMBER "0." WHITESPACE " " INT_NUMBER "0z" WHITESPACE "\n" INT_NUMBER "01790" WHITESPACE " " INT_NUMBER "0b1790" WHITESPACE " " INT_NUMBER "0o1790" WHITESPACE " " INT_NUMBER "0x1790aAbBcCdDeEfF" WHITESPACE " " INT_NUMBER "001279" WHITESPACE " " INT_NUMBER "0_1279" WHITESPACE " " FLOAT_NUMBER "0.1279" WHITESPACE " " FLOAT_NUMBER "0e1279" WHITESPACE " " FLOAT_NUMBER "0E1279" WHITESPACE "\n" INT_NUMBER "0" DOT "." DOT "." INT_NUMBER "2" WHITESPACE "\n" INT_NUMBER "0" DOT "." IDENT "foo" L_PAREN "(" R_PAREN ")" WHITESPACE "\n" FLOAT_NUMBER "0e+1" WHITESPACE "\n" INT_NUMBER "0" DOT "." IDENT "e" PLUS "+" INT_NUMBER "1" WHITESPACE "\n" FLOAT_NUMBER "0.0E-2" WHITESPACE "\n" FLOAT_NUMBER "0___0.10000____0000e+111__" WHITESPACE "\n" INT_NUMBER "1i64" WHITESPACE " " FLOAT_NUMBER "92.0f32" WHITESPACE " " INT_NUMBER "11__s" WHITESPACE "\n" ``` -------------------------------- ### Demonstrate format_args macro usage Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_strings_disabled.html Shows the usage of the format_args macro with standard and invalid escape sequences. ```rust fn main() { format_args!("foo\nbar"); format_args!("foo\invalid"); } ``` -------------------------------- ### Run the release xtask Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/README.md Execute the main release xtask after setting the GITHUB_TOKEN environment variable. This command automates checkout, pushing, packaging, and release creation. ```bash cargo xtask release ``` -------------------------------- ### Rust Hello World Program Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_comments_disabled.html A basic Rust program that prints 'Hello, world!' to the console. Includes regular and documentation comments. ```rust // This is a regular comment /// This is a doc comment fn main() { // Another comment println!("Hello, world!"); } ``` -------------------------------- ### Variable declaration and string conversion in Rust Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_rainbow.html Demonstrates basic variable assignment and string conversion methods. ```rust fn main() { let hello = "hello"; let x = hello.to_string(); let y = hello.to_string(); let x = "other color please!"; let y = x.to_string(); } ``` -------------------------------- ### Update Nightly Rust Toolchain Source: https://github.com/rust-lang/rust-analyzer/blob/master/xtask/test_data/expected.md This bash command updates the nightly version of the Rust toolchain. Ensure you have rustup installed. ```bash rustup update nightly ``` -------------------------------- ### Configure rust-analyzer server path Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/setup.md JSON configuration for VS Code User Settings to point to the local development binary. ```json { "rust-analyzer.server.path": "" } ``` -------------------------------- ### Initialize and Query LineIndex Source: https://github.com/rust-lang/rust-analyzer/blob/master/lib/line-index/README.md Demonstrates creating a LineIndex instance from a string and performing coordinate conversions. ```rust use line_index::LineIndex; let line_index = LineIndex::new("This is a\nmulti-line\ntext."); line_index.line_col(3.into()); // LineCol { line: 0, col: 3 } line_index.line_col(13.into()); // LineCol { line: 1, col: 3 } line_index.offset(LineCol { line: 2, col: 3 }); // Some (24) ``` -------------------------------- ### Example of Source Code with Comments Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/syntax.md Illustrates how non-doc comments are heuristically attached as children to nodes, such as function nodes, during parsing. ```rust // non doc comment fn foo() {} ``` -------------------------------- ### Run Flycheck Parameters Interface Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Defines parameters for the runFlycheck notification, specifying the text document for which to start flycheck processes. ```typescript interface RunFlycheckParams { /// The text document whose cargo workspace flycheck process should be started. /// If the document is null or does not belong to a cargo workspace all flycheck processes will be started. textDocument: lc.TextDocumentIdentifier | null; } ``` -------------------------------- ### TestState Type Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Defines the possible states for a test, including 'passed', 'failed' (with an error message), 'started', 'enqueued', and 'skipped'. ```typescript type TestState = { tag: "passed" } | { tag: "failed"; // The standard error of the test, containing the panic message. Clients should // render it similar to a terminal, and e.g. handle ansi colors. message: string; } | { tag: "started" } | { tag: "enqueued" } | { tag: "skipped" }; ``` -------------------------------- ### Configure Extra Arguments for Runnables Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Provide additional arguments to be passed to cargo for runnables such as tests or binaries. For example, '--release'. ```json [] ``` -------------------------------- ### Example of SnippetTextEdit Usage Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/lsp-extensions.md Demonstrates how a 'derive' code action transforms a struct definition by inserting a snippet with a placeholder for derive attributes. ```rust struct S; #[derive($0)] struct S; ``` -------------------------------- ### Plain Text Listing Example Source: https://github.com/rust-lang/rust-analyzer/blob/master/xtask/test_data/expected.md This is a plain text listing, often used for displaying output or messages that do not require specific formatting. ```plaintext This is a plain listing. ``` -------------------------------- ### Inline Assembly Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html Demonstrates the use of core::arch::asm! for low-level register manipulation. ```rust let i: u64 = 3; let o: u64; core::arch::asm!( "mov {0}, {1}", "add {0}, 5", out(reg) o, in(reg) i, ); ``` -------------------------------- ### Configure rust-analyzer in Neovim Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/other_editors.md Uses the Neovim 0.11+ API to pass server settings and register autocommands for inlay hints and completion. ```lua lua << EOF -- You can pass LSP settings to the server: vim.lsp.config("rust_analyzer", { settings = { ["rust-analyzer"] = { imports = { granularity = { group = "module", }, prefix = "self", }, cargo = { buildScripts = { enable = true, }, }, procMacro = { enable = true }, }, }, }) -- You can enable different LSP features vim.api.nvim_create_autocmd("LspAttach", { callback = function(ev) local client = assert(vim.lsp.get_client_by_id(ev.data.client_id)) -- Inlay hints display inferred types, etc. if client:supports_method("inlayHint/resolve") then vim.lsp.inlay_hint.enable(true, { bufnr = ev.buf }) end -- Completion can be invoked via ctrl+x ctrl+o. It displays a list of -- names inferred from the context (e.g. method names, variables, etc.) if client:supports_method("textDocument/completion") then vim.lsp.completion.enable(true, client.id, ev.buf, {}) end end, }) EOF ``` -------------------------------- ### Style inline code comments as sentences Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/style.md Inline comments should be written as proper sentences starting with a capital letter and ending with a period. ```rust // GOOD // Only simple single segment paths are allowed. MergeBehavior::Last => { tree.use_tree_list().is_none() && tree.path().map(path_len) <= Some(1) } // BAD // only simple single segment paths are allowed MergeBehavior::Last => { tree.use_tree_list().is_none() && tree.path().map(path_len) <= Some(1) } ``` -------------------------------- ### Build with debug assertions Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/contributing/debugging.md Command to build the release binary with debug assertions enabled. ```bash RUSTFLAGS='--cfg debug_assertions' cargo build --release ``` -------------------------------- ### Enable Full Function Signature Completions Source: https://github.com/rust-lang/rust-analyzer/blob/master/docs/book/src/configuration_generated.md Shows full function or method signatures in completion documentation. ```rust rust-analyzer.completion.fullFunctionSignatures.enable ``` -------------------------------- ### Implement a Trait for a Struct in Rust Source: https://github.com/rust-lang/rust-analyzer/blob/master/crates/ide/src/syntax_highlighting/test_data/highlight_assoc_functions.html This example shows how to implement the trait `t` for the struct `foo`, providing concrete implementations for the trait's methods. ```rust impl t for foo { pub fn is_static() {} pub fn is_not_static(&self) {} } ```