### Setup Rust Build Environment Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/quickstart.md Sets up the build configuration for the Rust compiler using the 'x' wrapper script. This command creates default settings necessary for building and testing. ```sh ./x setup ``` -------------------------------- ### Clone Rust Repository Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/quickstart.md Clones the official Rust repository from GitHub and navigates into the directory. This is the first step to start working on the compiler. ```sh git clone https://github.com/rust-lang/rust.git cd rust ``` -------------------------------- ### Install mdbook and Extensions for Building Rustc Dev Guide Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/README.md Installs mdbook, mdbook-linkcheck2, and mdbook-mermaid using cargo, which are necessary tools for building a local static HTML site for the rustc dev guide. ```bash cargo install mdbook mdbook-linkcheck2 mdbook-mermaid ``` -------------------------------- ### Link Custom Rust Toolchain Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/quickstart.md Links a newly built compiler toolchain to be usable with rustup. This allows you to easily switch to and test your custom-built compiler. ```sh rustup toolchain link stage1 build/host/stage1 ``` -------------------------------- ### Test Rust Compiler with a File Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/quickstart.md Compiles a single Rust file using the custom toolchain linked via rustup. This is a basic test to ensure the compiler works as expected. ```sh rustc +stage1 testfile.rs ``` -------------------------------- ### Link Rust Toolchain and Install Nightly (Bash) Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/offload/installation.md Links a locally built Rust toolchain for offloading features and installs the nightly toolchain to enable unstable options, allowing the use of advanced `std::offload` capabilities. ```Bash rustup toolchain link offload build/host/stage1 rustup toolchain install nightly ``` -------------------------------- ### Rust GPU Kernel Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/offload/usage.md This Rust code snippet demonstrates the setup for a GPU kernel, including necessary feature flags, no_std configuration, and platform-specific conditional compilation for Linux. It includes a panic handler, a main function for execution on Linux, and the definition of the GPU kernel itself. ```rust #![feature(abi_gpu_kernel)] #![feature(rustc_attrs)] #![feature(core_intrinsics)] #![no_std] #[cfg(target_os = "linux")] extern crate libc; #[cfg(target_os = "linux")] use libc::c_char; #[cfg(target_os = "linux")] use core::mem; #[panic_handler] fn panic(_: &core::panic::PanicInfo) -> ! { loop {} } #[cfg(target_os = "linux")] #[unsafe(no_mangle)] #[inline(never)] fn main() { let array_c: *mut [f64; 256] = unsafe { libc::calloc(256, (mem::size_of::()) as libc::size_t) as *mut [f64; 256] }; let output = c"The first element is zero %f\n"; let output2 = c"The first element is NOT zero %f\n"; let output3 = c"The second element is %f\n"; unsafe { let val: *const c_char = if (*array_c)[0] < 0.1 { output.as_ptr() } else { output2.as_ptr() }; libc::printf(val, (*array_c)[0]); } unsafe { kernel(array_c); } core::hint::black_box(&array_c); unsafe { let val: *const c_char = if (*array_c)[0] < 0.1 { output.as_ptr() } else { output2.as_ptr() }; libc::printf(val, (*array_c)[0]); libc::printf(output3.as_ptr(), (*array_c)[1]); } } #[inline(never)] unsafe fn kernel(x: *mut [f64; 256]) { core::intrinsics::offload(_kernel_1, [256, 1, 1], [32, 1, 1], (x,)) } #[cfg(target_os = "linux")] unsafe extern "C" { pub fn kernel_1(array_b: *mut [f64; 256]); } #[cfg(not(target_os = "linux"))] #[unsafe(no_mangle)] #[inline(never)] #[rustc_offload_kernel] pub extern "gpu-kernel" fn kernel_1(x: *mut [f64; 256]) { unsafe { (*x)[0] = 21.0 }; } ``` -------------------------------- ### Run Rust Compiler UI Tests Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/quickstart.md Executes the UI tests for the Rust compiler, which involve compiling specific test files and checking their output. This is a common command after making compiler changes. ```sh ./x test tests/ui ``` -------------------------------- ### Build LLVM from Source (CMake/Ninja) Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/offload/installation.md Clones the LLVM monorepo, creates a build directory, and configures the build using CMake with specific flags for target architectures (host, AMDGPU, NVPTX), enabling assertions, and including projects like clang and lld. It then builds and installs the configured LLVM. ```Bash git clone git@github.com:llvm/llvm-project cd llvm-project mkdir build cd build cmake -G Ninja ../llvm -DLLVM_TARGETS_TO_BUILD="host,AMDGPU,NVPTX" -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_ENABLE_PROJECTS="clang;lld" -DLLVM_ENABLE_RUNTIMES="offload,openmp" -DLLVM_ENABLE_PLUGINS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=. ninja ninja install ``` -------------------------------- ### Rust: Compiling a Crate with Query Context Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/queries/query-evaluation-model-in-detail.md Demonstrates the initial setup for compiling a crate, including creating a query context (`TyCtxt`) and invoking the 'type_check_crate' query. ```rust fn compile_crate() { let cli_options = ...; let hir_map = ...; // Create the query context `tcx` let tcx = TyCtxt::new(cli_options, hir_map); // Do type checking by invoking the type check query tcx.type_check_crate(); } ``` -------------------------------- ### Build and Open Rustc Dev Guide Locally Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/README.md Builds a local static HTML version of the rustc dev guide and opens it in the default web browser. The generated files are located in the `book/html` directory. ```bash mdbook build --open ``` -------------------------------- ### Build Rust Compiler and Standard Library Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/quickstart.md Builds the Rust compiler, standard library, and associated tools. The './x build' command is used instead of 'cargo' directly. You can also use './x check' to only check the code. ```sh ./x build ``` -------------------------------- ### Rust Inferred Generic Arguments (`_`) Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/ambig-unambig-ty-and-consts.md Demonstrates the usage of inferred generic arguments ('_') in Rust code. This example shows how an unused generic argument with an inferred type is declared. ```rust struct Foo; fn foo() { let _unused: Foo<_>; } ``` -------------------------------- ### Rust Generic Function Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/traits/lowering-to-logic.md A simple generic Rust function `foo` that calls another generic function `bar`. This example demonstrates the scenario where type-checking requires abstracting over type parameters. ```rust fn foo>() { bar::() } fn bar>() { } ``` -------------------------------- ### Rust Test Documentation Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/tests/best-practices.md Provides an example of a Rust test with comprehensive documentation comments. It includes a brief summary, remarks on related issues or external APIs, and links to relevant resources like GitHub issues and man pages. This helps other contributors understand the test's purpose and context. ```rust //! Brief summary of what the test is exercising. //! Example: Regression test for #123456: make sure coverage attribute don't ICE //! when applied to non-items. //! //! Optional: Remarks on related tests/issues, external APIs/tools, crash //! mechanism, how it's fixed, FIXMEs, limitations, etc. //! Example: This test is like `tests/attrs/linkage.rs`, but this test is //! specifically checking `#[coverage]` which exercises a different code //! path. The ICE was triggered during attribute validation when we tried //! to construct a `def_path_str` but only emitted the diagnostic when the //! platform is windows, causing an ICE on unix. //! //! Links to relevant issues and discussions. Examples below: //! Regression test for . //! See also . //! See discussion at . //! See [`clone(2)`]. //! //! [`clone(2)`]: https://man7.org/linux/man-pages/man2/clone.2.html //@ ignore-windows // Reason: (why is this test ignored for windows? why not specifically // windows-gnu or windows-msvc?) // Optional: Summary of test cases: What positive cases are checked? // What negative cases are checked? Any specific quirks? fn main() { #[coverage] //~^ ERROR coverage attribute can only be applied to function items. let _ = { // Comment highlighting something that deserves reader attention. fn foo() {} }; } ``` -------------------------------- ### De Bruijn Index Example in Rust (Conceptual) Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/appendix/background.md Illustrates a conceptual usage of de Bruijn indices for representing variables within nested closures. This example is for demonstration and not directly used in the Rustc implementation. ```rust |x| { f(x) // de Bruijn index of `x` is 1 because `x` is bound 1 level up |y| { g(x, y) // index of `x` is 2 because it is bound 2 levels up // index of `y` is 1 because it is bound 1 level up } } ``` -------------------------------- ### Rust Function Example for Universe Scope Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/borrow_check/region_inference/placeholders_and_universes.md Illustrates a Rust function `bar` with lifetime and type parameters, demonstrating how they contribute to the root universe. This is a foundational example for understanding scope in the Rust compiler's universe model. ```rust struct Foo { } fn bar<'a, T>(t: &'a T) { ... } ``` -------------------------------- ### Record Stage 2 Rustc Compiler Build Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/profiling/wpa_profiling.md Start WPR recording, then build the stage 2 Rust compiler. This captures system statistics, including CPU and VirtualAlloc usage, needed for performance analysis. ```bash x build --stage=2 -i library ``` -------------------------------- ### Rust: Track Caller Example with println! Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/backend/implicit-caller-location.md A basic Rust example demonstrating the use of the `#[track_caller]` attribute to print the caller's location. This snippet showcases how `std::panic::Location::caller()` is used within a tracked function. ```rust #![feature(track_caller)] use std::panic::Location; #[track_caller] fn print_caller() { println!("called from {}", Location::caller()); } fn main() { print_caller(); } ``` -------------------------------- ### Example LLVM IR function call (LLVM IR) Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/autodiff/debugging.md An example of an LLVM IR function call, specifically demonstrating `__enzyme_fwddiff`. This snippet shows how to identify the mangled function name needed for the `llvm-extract` tool in the minimization step. ```llvm-ir define double @enzyme_opt_helper_0(ptr %0, i64 %1, double %2) { %4 = call double (...) @__enzyme_fwddiff(ptr @_zn2ad3_f217h3b3b1800bd39fde3e, metadata !"enzyme_const", ptr %0, metadata !"enzyme_const", i64 %1, metadata !"enzyme_dup", double %2, double %2) ret double %4 } ``` -------------------------------- ### Rust: Cyclic Query Provider Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/queries/query-evaluation-model-in-detail.md Provides an example of a query provider that creates a cyclic invocation by calling itself with the same key, leading to infinite recursion. ```rust fn cyclic_query_provider(tcx, key) -> u32 { // Invoke the same query with the same key again tcx.cyclic_query(key) } ``` -------------------------------- ### UI Test Example - Rust Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/tests/adding.md An example of a UI test for rustc, demonstrating how to write a Rust source file that will be compiled and checked for specific error messages or compiler behavior. It includes directives like `@edition` to control the compilation environment. ```rust // Provide diagnostics when the user writes `await` in a non-`async` function. //@ edition:2018 async fn foo() {} fn bar() { foo().await } fn main() {} ``` -------------------------------- ### Example Error Message for LLVM IR Minimization Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/autodiff/debugging.md An example of a detailed error message from opt, which is useful for creating a precise grep filter in the minimization script. The specificity of this message helps ensure that llvm-reduce targets the correct error condition. ```text opt: /home/manuel/prog/rust/src/llvm-project/llvm/lib/ir/instructions.cpp:686: void llvm::callinst::init(llvm::functiontype*, llvm::value*, llvm::arrayref, llvm::arrayref >, const llvm::twine&): assertion `(args.size() == fty->getnumparams() || (fty->isvararg() && args.size() > fty->getnumparams())) && "calling a function with bad signature!"' failed. ``` -------------------------------- ### Rust Macro Expansion Order Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/macro-expansion.md Illustrates the expansion order hierarchy in Rust macros. The example shows how a macro `foo!` expands and calls another macro `println!`, defining the hierarchy of expansions from the outermost to the innermost tokens. ```rust macro_rules! foo { () => { println!(); } } fn main() { foo!(); } ``` -------------------------------- ### Configure and Build Rustc from Source (Bash) Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/offload/installation.md Clones the Rust repository, configures the build with specific options like shared LLVM linking and nightly channel, and then builds the compiler. This is necessary for using advanced features like std::offload. ```Bash git clone git@github.com:rust-lang/rust cd rust ./configure --enable-llvm-link-shared --release-channel=nightly --enable-llvm-assertions --enable-llvm-offload --enable-llvm-enzyme --enable-clang --enable-lld --enable-option-checking --enable-ninja --disable-docs ./x build --stage 1 library ``` -------------------------------- ### Placeholder for Stabilized Code Example Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/stabilization_report_template.md This is a placeholder within the 'What is stabilized' section. It indicates where a short Rust code example demonstrating the stabilized behavior should be inserted. Currently, it contains a `todo!()` macro, signifying that the actual code snippet needs to be provided. ```rust todo!() ``` -------------------------------- ### Instantiating a Canonical Query in Rust Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/traits/canonicalization.md Demonstrates how to instantiate a canonical query by creating a fresh inference context and applying a substitution to replace canonical variables with fresh inference variables. The output is a fully instantiated query ready for solving. ```text for { ?0: Foo<'?1, ?2> } ``` ```text S = [?A, '?B, ?C] ``` ```text ?A: Foo<'?B, ?C> ``` -------------------------------- ### Rust Code Definitions for Turbofishing Examples Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/early_late_parameters.md Provides the necessary Rust code definitions for functions, structs, traits, and their implementations used in the turbofishing examples. These definitions include various combinations of early and late bound lifetime parameters. ```rust fn free_function<'a: 'a, 'b>(_: &'a (), _: &'b ()) {} struct Foo; trait Trait: Sized { fn trait_method<'a: 'a, 'b>(self, _: &'a (), _: &'b ()); fn trait_function<'a: 'a, 'b>(_: &'a (), _: &'b ()); } impl Trait for Foo { fn trait_method<'a: 'a, 'b>(self, _: &'a (), _: &'b ()) {} fn trait_function<'a: 'a, 'b>(_: &'a (), _: &'b ()) {} } impl Foo { fn inherent_method<'a: 'a, 'b>(self, _: &'a (), _: &'b ()) {} fn inherent_function<'a: 'a, 'b>(_: &'a (), _: &'b ()) {} } ``` -------------------------------- ### Rust Macros By Example (MBE) Syntax Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/macro-expansion.md Shows the syntax for defining Macros By Example (MBE) in Rust using `macro_rules!`. This allows for pattern matching on token streams to generate code. ```rust macro_rules! printer { (print $mvar:ident) => { println!("{}", $mvar); }; (print twice $mvar:ident) => { println!("{}", $mvar); println!("{}", $mvar); }; } ``` -------------------------------- ### Compiler Configuration using bootstrap.toml Source: https://context7.com/rust-lang/rustc-dev-guide/llms.txt Example TOML configuration for `bootstrap.toml`, used to set up the Rust compiler build environment. It shows how to specify build targets, enable debug assertions and verbose tests, configure incremental compilation, and set up target-specific configurations like the WASI SDK sysroot. ```toml # bootstrap.toml - compiler build configuration [build] # Build for multiple targets target = ["x86_64-unknown-linux-gnu", "wasm32-wasip1"] [rust] # Enable debug assertions debug-assertions = true # Verbose test output verbose-tests = true # Enable incremental compilation incremental = true [llvm] # Use system LLVM instead of building (faster) download-ci-llvm = true [target.wasm32-wasip1] # WASI SDK sysroot for wasm target wasi-root = "/path/to/wasi-sdk/share/wasi-sysroot" ``` -------------------------------- ### Get Parameter Environment (Rust Snippet) Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/const-eval/interpret.md Shows how to obtain the parameter environment required for constant evaluation. This is a necessary step before invoking the const evaluation functions. ```rust let param_env = tcx.param_env(length_def_id); ``` -------------------------------- ### Install Rust from Source - Bash Source: https://github.com/rust-lang/rustc-dev-guide/blob/main/src/building/build-install-distribution-artifacts.md Installs the Rust compiler and configured tools by building from source. This command-line operation can be influenced by environment variables like DESTDIR for custom installation paths. ```bash ./x install ```