### Game Initialization Source: https://jordanbray.github.io/chess/chess/struct.Game.html Provides methods to create a new Game instance, either with the default starting position or a custom board setup. ```APIDOC ## POST /api/game/new ### Description Create a new `Game` with the initial position. ### Method POST ### Endpoint /api/game/new ### Request Body None ### Response #### Success Response (200) - **game** (Game) - A new Game object initialized to the default chess starting position. #### Response Example ```json { "game": { "current_position": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" } } ``` ## POST /api/game/new_with_board ### Description Create a new `Game` with a specific starting position. ### Method POST ### Endpoint /api/game/new_with_board ### Parameters #### Request Body - **board** (Board) - Required - The starting board configuration. ### Request Example ```json { "board": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" } ``` ### Response #### Success Response (200) - **game** (Game) - A new Game object initialized with the provided board configuration. #### Response Example ```json { "game": { "current_position": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" } } ``` ## POST /api/game/new_from_fen ### Description Create a new `Game` object from a FEN string. This method is deprecated and `Game::from_str` is recommended. ### Method POST ### Endpoint /api/game/new_from_fen ### Parameters #### Request Body - **fen** (string) - Required - The FEN string representing the board state. ### Request Example ```json { "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" } ``` ### Response #### Success Response (200) - **game** (Game) - A new Game object initialized from the FEN string, or null if the FEN is invalid. #### Response Example ```json { "game": { "current_position": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" } } ``` ``` -------------------------------- ### Rust Documentation Search Syntax Examples Source: https://jordanbray.github.io/chess/libc/fn.cfmakeraw.html Examples demonstrating how to use type prefixes, search by function signature, and combine multiple search terms in the Rust documentation search. ```text fn: ``` ```text vec -> usize ``` ```text * -> vec ``` ```text str,u8 ``` ```text String,struct:Vec,test ``` ```text "string" ``` ```text vec::Vec ``` -------------------------------- ### Procedural Macro Example Source: https://jordanbray.github.io/chess/syn/fn.parse.html An example demonstrating how to use syn::parse within a procedural macro to parse input tokens into a syntax tree. ```APIDOC ## Procedural Macro Example ### Description This example shows a `proc_macro_derive` that uses `syn::parse` to parse the input `TokenStream` into a `DeriveInput` abstract syntax tree (AST). ### Method `#[proc_macro_derive(MyMacro)]` ### Endpoint N/A (This is a procedural macro definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (`TokenStream`) - Required - The token stream provided by the Rust compiler to the procedural macro. ### Request Example ```rust extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::DeriveInput; #[proc_macro_derive(MyMacro)] pub fn my_macro(input: TokenStream) -> TokenStream { // Parse the tokens into a syntax tree let ast: DeriveInput = syn::parse(input).unwrap(); // Build the output, possibly using quasi-quotation let expanded = quote! { /* ... */ }; // Convert into a token stream and return it expanded.into() } ``` ### Response #### Success Response (200) - **TokenStream** - The generated token stream that will be compiled into the user's code. #### Response Example ```rust // The expanded token stream is returned expanded.into() ``` ``` -------------------------------- ### Syn Visit Trait Example Source: https://jordanbray.github.io/chess/src/syn/lib.rs.html Demonstrates how to implement the `Visit` trait to traverse a syntax tree and collect information. This example specifically finds all freestanding functions. ```rust use quote::quote; use syn::visit::{self, Visit}; use syn::{File, ItemFn}; struct FnVisitor; impl<'ast> Visit<'ast> for FnVisitor { fn visit_item_fn(&mut self, node: &'ast ItemFn) { println!("Function with name={}", node.sig.ident); // Delegate to the default impl to visit any nested functions. visit::visit_item_fn(self, node); } } fn main() { let code = quote! { pub fn f() { fn g() {} } }; let syntax_tree: File = syn::parse2(code).unwrap(); FnVisitor.visit_file(&syntax_tree); } ``` -------------------------------- ### Board Initialization Source: https://jordanbray.github.io/chess/chess/struct.Board.html Initializes a new Board to the default starting position. ```APIDOC ## POST /api/board/default ### Description Constructs the initial chess position. ### Method POST ### Endpoint /api/board/default ### Response #### Success Response (200) - **board** (Board) - The board initialized to the default starting position. ``` -------------------------------- ### Create an Empty Chess Board Source: https://jordanbray.github.io/chess/src/chess/board.rs.html Initializes a `Board` with all pieces removed and no castling rights. This provides a blank slate for custom board setups, not the standard starting position. ```rust impl Board { /// Construct a new `Board` that is completely empty. /// Note: This does NOT give you the initial position. Just a blank slate. fn new() -> Board { Board { pieces: [EMPTY; NUM_PIECES], color_combined: [EMPTY; NUM_COLORS], combined: EMPTY, side_to_move: Color::White, castle_rights: [CastleRights::NoRights; NUM_COLORS], pinned: EMPTY, checkers: EMPTY, hash: 0, en_passant: None, } } ``` -------------------------------- ### IdentExt::parse_any Example Source: https://jordanbray.github.io/chess/syn/ext/trait.IdentExt.html Example demonstrating how to use Ident::parse_any to parse macro input that allows Rust keywords as identifiers. ```APIDOC ## Example: parse_dsl ```rust use syn::{Error, Ident, Result, Token}; use syn::ext::IdentExt; use syn::parse::ParseStream; mod kw { syn::custom_keyword!(name); } // Parses input that looks like `name = NAME` where `NAME` can be // any identifier. // // Examples: // // name = anything // name = impl fn parse_dsl(input: ParseStream) -> Result { input.parse::()?; input.parse::()?; let name = input.call(Ident::parse_any)?; Ok(name) } ``` ``` -------------------------------- ### Creating and Using Identifiers Source: https://jordanbray.github.io/chess/syn/struct.Ident.html Examples demonstrating how to create and use `syn::Ident` instances. ```APIDOC ## Examples ### Creating a new ident A new ident can be created from a string using the `Ident::new` function. A span must be provided explicitly which governs the name resolution behavior of the resulting identifier. ```rust use proc_macro2::{Ident, Span}; fn main() { let call_ident = Ident::new("calligraphy", Span::call_site()); println!("{}", call_ident); } ``` ### Interpolating an ident into a token stream An ident can be interpolated into a token stream using the `quote!` macro. ```rust use proc_macro2::{Ident, Span}; use quote::quote; fn main() { let ident = Ident::new("demo", Span::call_site()); // Create a variable binding whose name is this ident. let expanded = quote! { let #ident = 10; }; // Create a variable binding with a slightly different name. let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site()); let expanded = quote! { let #temp_ident = 10; }; } ``` ### Examining an ident as a string A string representation of the ident is available through the `to_string()` method. ```rust // Examine the ident as a string. let ident_string = ident.to_string(); if ident_string.len() > 60 { println!("Very long identifier: {}", ident_string) } ``` ``` -------------------------------- ### Example: Parsing a Unit Struct Source: https://jordanbray.github.io/chess/syn/parse/struct.ParseBuffer.html An example demonstrating how to implement the `Parse` trait for a custom struct `UnitStruct` using `ParseBuffer` methods. ```APIDOC ## Example: Parsing a Unit Struct ```rust use syn::{Attribute, Ident, Result, Token}; use syn::parse::{Parse, ParseStream}; // Parses a unit struct with attributes. // // #[path = "s.tmpl"] // struct S; struct UnitStruct { attrs: Vec, struct_token: Token![struct], name: Ident, semi_token: Token![;], } impl Parse for UnitStruct { fn parse(input: ParseStream) -> Result { Ok(UnitStruct { attrs: input.call(Attribute::parse_outer)?, struct_token: input.parse()?, name: input.parse()?, semi_token: input.parse()?, }) } } ``` ``` -------------------------------- ### Rust Procedural Macro Example with Syn Source: https://jordanbray.github.io/chess/src/syn/lib.rs.html This example demonstrates a typical derive macro using Syn and quote. It parses input tokens into a DeriveInput syntax tree, builds output tokens using quote!, and returns them to the compiler. Requires 'syn' and 'quote' dependencies. ```rust extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; #[proc_macro_derive(MyMacro)] pub fn my_macro(input: TokenStream) -> TokenStream { // Parse the input tokens into a syntax tree let input = parse_macro_input!(input as DeriveInput); // Build the output, possibly using quasi-quotation let expanded = quote! { // ... }; // Hand the output tokens back to the compiler TokenStream::from(expanded) } ``` -------------------------------- ### Example Implementation of ToTokens for Path Source: https://jordanbray.github.io/chess/quote/to_tokens/trait.ToTokens.html An example demonstrating how to implement the ToTokens trait for a custom `Path` struct, which represents Rust paths. ```APIDOC ## Example Implementation for Path ### Description Example implementation for a struct representing Rust paths like `std::cmp::PartialEq`: ### Code ```rust use proc_macro2::{TokenTree, Spacing, Span, Punct, TokenStream}; use quote::{TokenStreamExt, ToTokens}; pub struct Path { pub global: bool, pub segments: Vec, } impl ToTokens for Path { fn to_tokens(&self, tokens: &mut TokenStream) { for (i, segment) in self.segments.iter().enumerate() { if i > 0 || self.global { // Double colon `::` tokens.append(Punct::new(':', Spacing::Joint)); tokens.append(Punct::new(':', Spacing::Alone)); } segment.to_tokens(tokens); } } } ``` ``` -------------------------------- ### Example: Implementing a Trait with synstructure Source: https://jordanbray.github.io/chess/src/synstructure/lib.rs.html Demonstrates how to use `synstructure` to generate an `impl` block for a trait. This example filters variants and asserts the generated code matches the expected output, including the `const` wrapper and `extern crate` declaration. ```rust # use synstructure::* let di: syn::DeriveInput = syn::parse_quote! { enum A { B(T), C(Option), } }; let mut s = Structure::new(&di); s.filter_variants(|v| v.ast().ident != "B"); assert_eq!( s.unbound_impl(quote!(krate::Trait), quote!{ fn a() {} }).to_string(), quote!{ #[allow(non_upper_case_globals)] #[doc(hidden)] const _DERIVE_krate_Trait_FOR_A: () = { extern crate krate; impl krate::Trait for A { fn a() {} } }; }.to_string() ); ``` -------------------------------- ### Example Implementation of ToTokens for Path Struct Source: https://jordanbray.github.io/chess/quote/to_tokens/trait.ToTokens.html Provides an example implementation of the ToTokens trait for a custom `Path` struct, demonstrating how to append tokens for Rust path segments and separators. ```rust use proc_macro2::{TokenTree, Spacing, Span, Punct, TokenStream}; use quote::{TokenStreamExt, ToTokens}; pub struct Path { pub global: bool, pub segments: Vec, } impl ToTokens for Path { fn to_tokens(&self, tokens: &mut TokenStream) { for (i, segment) in self.segments.iter().enumerate() { if i > 0 || self.global { // Double colon `::` tokens.append(Punct::new(':', Spacing::Joint)); tokens.append(Punct::new(':', Spacing::Alone)); } segment.to_tokens(tokens); } } } ``` -------------------------------- ### Procedural Macro Example Source: https://jordanbray.github.io/chess/quote/macro.quote.html Example of a basic procedural macro using quote! to derive a trait. Ensure to parse input and generate the appropriate implementation. ```rust extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; #[proc_macro_derive(HeapSize)] pub fn derive_heap_size(input: TokenStream) -> TokenStream { // Parse the input and figure out what implementation to generate... let name = /* ... */; let expr = /* ... */; let expanded = quote! { // The generated impl. impl heapsize::HeapSize for #name { fn heap_size_of_children(&self) -> usize { #expr } } }; // Hand the output tokens back to the compiler. TokenStream::from(expanded) } ``` -------------------------------- ### Conditional Compilation Example with cfg-if Source: https://jordanbray.github.io/chess/src/cfg_if/lib.rs.html Demonstrates how to use the cfg-if macro to conditionally compile code based on different #[cfg] attributes. This example shows a common pattern for providing platform-specific or feature-specific implementations. ```Rust #![no_std] #![doc(html_root_url = "https://docs.rs/cfg-if")] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] /// The main macro provided by this crate. See crate documentation for more /// information. #[macro_export] macro_rules! cfg_if { // match if/else chains with a final `else` ($( if #[cfg($($meta:meta),*)] { $($tokens:tt)* } ) else * else { $($tokens2:tt)* }) => { $crate::cfg_if! { @__items () ; $( ( ($($meta),*) ($($tokens)*) ), )* ( () ($($tokens2)*) ), } }; // match if/else chains lacking a final `else` ( if #[cfg($($i_met:meta),*)] { $($i_tokens:tt)* } $( else if #[cfg($($e_met:meta),*)] { $($e_tokens:tt)* } )* ) => { $crate::cfg_if! { @__items () ; ( ($($i_met),*) ($($i_tokens)*) ), $( ( ($($e_met),*) ($($e_tokens)*) ), )* ( () () ), } }; // Internal and recursive macro to emit all the items // // Collects all the negated cfgs in a list at the beginning and after the // semicolon is all the remaining items (@__items ($($not:meta,)*) ; ) => {}; (@__items ($($not:meta,)*) ; ( ($($m:meta),*) ($($tokens:tt)*) ), $($rest:tt)*) => { // Emit all items within one block, applying an appropriate #[cfg]. The // #[cfg] will require all `$m` matchers specified and must also negate // all previous matchers. #[cfg(all($($m,)* not(any($($not),*))))] $crate::cfg_if! { @__identity $($tokens)* } // Recurse to emit all other items in `$rest`, and when we do so add all // our `$m` matchers to the list of `$not` matchers as future emissions // will have to negate everything we just matched as well. $crate::cfg_if! { @__items ($($not,)* $($m,)*) ; $($rest)* } }; // Internal macro to make __apply work out right for different match types, // because of how macros matching/expand stuff. (@__identity $($tokens:tt)*) => { $($tokens)* }; } ``` -------------------------------- ### Get Start Location of a Span Source: https://jordanbray.github.io/chess/src/proc_macro2/lib.rs.html Retrieves the starting line and column of a span. Requires the "span-locations" feature to be enabled. ```rust #[cfg(span_locations)] pub fn start(&self) -> LineColumn { let imp::LineColumn { line, column } = self.inner.start(); LineColumn { line, column } } ``` -------------------------------- ### BoardBuilder::setup() Source: https://jordanbray.github.io/chess/chess/struct.BoardBuilder.html Sets up a board with pre-loaded pieces, side to move, castle rights, and en passant information. ```APIDOC ## `setup()` ### Description Set up a board with everything pre-loaded. ### Method `pub fn setup<'a>( pieces: impl IntoIterator, side_to_move: Color, white_castle_rights: CastleRights, black_castle_rights: CastleRights, en_passant: Option ) -> BoardBuilder` ### Example ```rust use chess::{BoardBuilder, Board, Square, Color, Piece, CastleRights}; use std::convert::TryInto; let board: Board = BoardBuilder::setup( &[ (Square::A1, Piece::King, Color::White), (Square::H8, Piece::King, Color::Black) ], Color::Black, CastleRights::NoRights, CastleRights::NoRights, None) .try_into()?; ``` ``` -------------------------------- ### Span: Start Line and Column Source: https://jordanbray.github.io/chess/src/proc_macro2/fallback.rs.html Gets the starting line and column number for a Span. Requires span locations to be enabled and uses the SourceMap to find file information. ```rust #[cfg(span_locations)] pub fn start(&self) -> LineColumn { SOURCE_MAP.with(|cm| { let cm = cm.borrow(); let fi = cm.fileinfo(*self); fi.offset_line_column(self.lo as usize) }) } ``` -------------------------------- ### Get Symbol Address - Frame Source: https://jordanbray.github.io/chess/backtrace/struct.Frame.html Returns the starting symbol address of the function for this frame. This attempts to rewind the instruction pointer to the function's start. It can be useful if `backtrace::resolve` fails with the `ip` value. ```rust pub fn symbol_address(&self) -> *mut c_void ``` -------------------------------- ### libc::posix_spawn_file_actions_init Function Source: https://jordanbray.github.io/chess/libc/fn.posix_spawn_file_actions_init.html Documentation for the C function posix_spawn_file_actions_init. ```APIDOC ## Function libc::posix_spawn_file_actions_init ### Description Initializes a `posix_spawn_file_actions_t` object. ### Method `pub unsafe extern "C" fn` ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (0) Returns 0 on success. #### Response Example N/A ``` -------------------------------- ### Setup BoardBuilder with Specifics Source: https://jordanbray.github.io/chess/chess/struct.BoardBuilder.html Set up a BoardBuilder with pre-loaded pieces, side to move, castle rights, and en passant square. This method is useful for initializing a board state from a known configuration. ```rust use chess::{BoardBuilder, Board, Square, Color, Piece, CastleRights}; use std::convert::TryInto; let board: Board = BoardBuilder::setup( &[ (Square::A1, Piece::King, Color::White), (Square::H8, Piece::King, Color::Black) ], Color::Black, CastleRights::NoRights, CastleRights::NoRights, None) .try_into()?; ``` -------------------------------- ### QSelf Example: Path without Trait Source: https://jordanbray.github.io/chess/syn/struct.QSelf.html Shows a simpler qualified path where the 'as_token' is absent, and 'position' indicates the start of the associated item. ```rust >::AssociatedItem ^~~~~~ ^ ty position = 0 ``` -------------------------------- ### Rust Documentation Search Syntax Examples Source: https://jordanbray.github.io/chess/libc/constant.RT_SCOPE_SITE.html Illustrates various search syntaxes for Rust documentation, including type prefixes, type signatures, multiple queries, exact name matching, and path-based searching. ```text ? Show this help dialog ``` ```text S Focus the search field ``` ```text ↑ Move up in search results ``` ```text ↓ Move down in search results ``` ```text ↹ Switch tab ``` ```text ⏎ Go to active search result ``` ```text + Expand all sections ``` ```text - Collapse all sections ``` ```text fn: to restrict the search to a given type. ``` ```text vec -> usize or * -> vec to search functions by type signature ``` ```text str,u8 or String,struct:Vec,test to search multiple things at once ``` ```text "string" to look for items with an exact name ``` ```text vec::Vec to look for items inside another one by searching for a path ``` -------------------------------- ### Get Symbol Address of Frame Source: https://jordanbray.github.io/chess/src/backtrace/backtrace/mod.rs.html Returns the starting symbol address for the frame's function. This can be useful if `backtrace::resolve` fails on the `ip`. ```rust pub fn symbol_address(&self) -> *mut c_void { self.inner.symbol_address() } ``` -------------------------------- ### Get System Load Average (C function signature) Source: https://jordanbray.github.io/chess/libc/fn.getloadavg.html This is the C function signature for `getloadavg`. It retrieves the system load average. Ensure proper C interop setup when using this in Rust. ```rust pub unsafe extern "C" fn getloadavg( loadavg: *mut c_double, nelem: c_int ) -> c_int ``` -------------------------------- ### SyncFailure Example Source: https://jordanbray.github.io/chess/failure/struct.SyncFailure.html Example demonstrating the usage of SyncFailure to handle non-Sync errors. ```APIDOC ## Example Usage of SyncFailure ```rust extern crate failure; use failure::{Error, SyncFailure}; use std::cell::RefCell; #[derive(Debug)] struct NonSyncError { // RefCells are non-Sync, so structs containing them will be // non-Sync as well. count: RefCell, } // implement Display/Error for NonSyncError... fn returns_error() -> Result<(), NonSyncError> { // Do stuff unimplemented!() } fn my_function() -> Result<(), Error> { // without the map_err here, we end up with a compile error // complaining that NonSyncError doesn't implement Sync. returns_error().map_err(SyncFailure::new)?; // Do more stuff Ok(()) } ``` ``` -------------------------------- ### Show Help Dialog Source: https://jordanbray.github.io/chess/libc/fn.rewind.html Press the '?' key to display the help dialog, which lists available keyboard shortcuts for navigating the documentation. ```text ? Show this help dialog ``` -------------------------------- ### Constant for Get Operations Source: https://jordanbray.github.io/chess/libc/constant.CTRL_CMD_GETOPS.html Defines a constant integer value used for get operations in the C library. ```rust pub const CTRL_CMD_GETOPS: c_int = 6; ``` -------------------------------- ### MoveGen Initialization Source: https://jordanbray.github.io/chess/chess/struct.MoveGen.html Demonstrates how to create a new MoveGen instance for legal moves. ```APIDOC ## `pub fn new_legal(board: &Board) -> MoveGen` ### Description Create a new `MoveGen` structure, only generating legal moves. ### Method `pub fn new_legal` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use chess::MoveGen; use chess::Board; let board = Board::default(); let mut iterable = MoveGen::new_legal(&board); ``` ### Response #### Success Response (200) `MoveGen` instance #### Response Example (Instance of MoveGen) ``` -------------------------------- ### Example: Parsing a Marker Trait Source: https://jordanbray.github.io/chess/syn/parse/struct.ParseBuffer.html An example showcasing the use of `peek` and other `ParseBuffer` methods to parse a `MarkerTrait` definition. ```APIDOC ## Example: Parsing a Marker Trait ```rust use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; // Parses a trait definition containing no associated items. // // trait Marker<'de, T>: A + B<'de> where Box: Clone {} struct MarkerTrait { trait_token: Token![trait], ident: Ident, generics: Generics, colon_token: Option, supertraits: Punctuated, brace_token: token::Brace, } impl Parse for MarkerTrait { fn parse(input: ParseStream) -> Result { let trait_token: Token![trait] = input.parse()?; let ident: Ident = input.parse()?; let mut generics: Generics = input.parse()?; let colon_token: Option = input.parse()?; let mut supertraits = Punctuated::new(); if colon_token.is_some() { loop { supertraits.push_value(input.parse()?); if input.peek(Token![where]) || input.peek(token::Brace) { break; } supertraits.push_punct(input.parse()?); } } generics.where_clause = input.parse()?; let content; let empty_brace_token = braced!(content in input); Ok(MarkerTrait { trait_token, ident, generics, colon_token, supertraits, brace_token: empty_brace_token, }) } } ``` ``` -------------------------------- ### Cloning and Copying Source: https://jordanbray.github.io/chess/chess/struct.BitBoard.html Documentation for cloning and copying `BitBoard` instances. ```APIDOC ## Cloning and Copying ### `impl Clone for BitBoard` Allows `BitBoard` instances to be cloned. #### `fn clone(&self) -> BitBoard` Returns a copy of the value. #### `fn clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. ### `impl Copy for BitBoard` Indicates that `BitBoard` is a `Copy` type, meaning it can be duplicated simply by copying bits. ``` -------------------------------- ### Rust Function Signature Example Source: https://jordanbray.github.io/chess/libc/fn.pthread_mutex_unlock.html This is an example of a C function signature for `pthread_mutex_unlock` as it might appear in Rust documentation. ```rust pub unsafe extern "C" fn pthread_mutex_unlock( lock: *mut pthread_mutex_t ) -> c_int ``` -------------------------------- ### is_ident_start Function Source: https://jordanbray.github.io/chess/src/proc_macro2/fallback.rs.html Checks if a character is a valid start character for an identifier, including Unicode XID start characters. ```rust fn is_ident_start(c: char) -> bool { ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == "_" || (c > '\x7f' && UnicodeXID::is_xid_start(c)) } ``` -------------------------------- ### IdentExt::unraw Example Source: https://jordanbray.github.io/chess/syn/ext/trait.IdentExt.html Example demonstrating the use of Ident::unraw to strip raw identifier markers for interoperation with other languages. ```APIDOC ## Example: ident_for_getter ```rust use proc_macro2::Span; use syn::Ident; use syn::ext::IdentExt; fn ident_for_getter(variable: &Ident) -> Ident { let getter = format!("__pyo3_get_{}", variable.unraw()); Ident::new(&getter, Span::call_site()) } ``` ``` -------------------------------- ### Example Visitor for Freestanding Functions Source: https://jordanbray.github.io/chess/syn/visit/index.html Demonstrates a visitor that prints the names of all freestanding functions, including nested ones. Requires the 'full' and 'visit' features for Syn. ```rust // [dependencies] // quote = "1.0" // syn = { version = "1.0", features = ["full", "visit"] } use quote::quote; use syn::visit::{self, Visit}; use syn::{File, ItemFn}; struct FnVisitor; impl<'ast> Visit<'ast> for FnVisitor { fn visit_item_fn(&mut self, node: &'ast ItemFn) { println!("Function with name={}", node.sig.ident); // Delegate to the default impl to visit any nested functions. visit::visit_item_fn(self, node); } } fn main() { let code = quote! { pub fn f() { fn g() {} } }; let syntax_tree: File = syn::parse2(code).unwrap(); FnVisitor.visit_file(&syntax_tree); } ``` -------------------------------- ### Example: Using Error::from_boxed_compat Source: https://jordanbray.github.io/chess/failure/struct.Error.html Demonstrates how to use `Error::from_boxed_compat` to handle errors from library functions that return `Box`. ```rust use std::error::Error as StdError; use failure::Error; fn app_fn() -> Result { let x = library_fn().map_err(Error::from_boxed_compat)?; Ok(x * 2) } fn library_fn() -> Result> { Ok(92) } ``` -------------------------------- ### Crate Features and Installation Source: https://jordanbray.github.io/chess/src/unicode_xid/lib.rs.html Information on how to enable features for the unicode-xid crate and how to add it as a dependency to your project. ```APIDOC ## Features - **`no_std`**: Supports `no_std` environments by using equivalent functions from `core` instead of `std`. ## Installation To use this package in your project, add the following to your `Cargo.toml`: ```toml [dependencies] unicode-xid = "0.0.4" ``` ``` -------------------------------- ### Game Initialization Source: https://jordanbray.github.io/chess/src/chess/game.rs.html Provides methods for creating new game instances, either from a default board or a FEN string. ```APIDOC ## Game::new_with_board ### Description Creates a new `Game` object initialized with a specific board state. ### Method Associated function (constructor) ### Endpoint N/A (Rust function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use chess::{Board, Game}; let initial_board = Board::default(); let game = Game::new_with_board(initial_board); ``` ### Response #### Success Response (200) - **Game** (Game) - A new `Game` object. #### Response Example ```rust // Game object is returned ``` ## Game::new_from_fen ### Description Creates a new `Game` object from a given FEN (Forsyth-Edwards Notation) string. This method is deprecated and `Game::from_str` is recommended. ### Method Associated function (constructor) ### Endpoint N/A (Rust function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use chess::Game; let fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; let game_option = Game::new_from_fen(fen); let invalid_fen = "Invalid FEN"; let invalid_game_option = Game::new_from_fen(invalid_fen); ``` ### Response #### Success Response (200) - **Option** (Option) - An `Option` containing a `Game` object if the FEN string is valid, otherwise `None`. #### Response Example ```rust // Some(Game) for valid FEN, None for invalid FEN ``` ``` -------------------------------- ### Get the underlying cause of the Error (Deprecated) Source: https://jordanbray.github.io/chess/failure/struct.Error.html Deprecated method to get a reference to the underlying cause of the Error. Use `as_fail()` instead. ```rust pub fn cause(&self) -> &dyn Fail ``` -------------------------------- ### Rust Documentation Search Examples Source: https://jordanbray.github.io/chess/libc/constant.SYS_vserver.html Illustrates various search query formats for Rust documentation. Use these to refine your searches by type, signature, or exact name. ```text ? ``` ```text S ``` ```text ↑ ``` ```text ↓ ``` ```text ↹ ``` ```text ⏎ ``` ```text + ``` ```text - ``` ```text fn: ``` ```text vec -> usize ``` ```text * -> vec ``` ```text str,u8 ``` ```text String,struct:Vec,test ``` ```text "string" ``` ```text vec::Vec ``` -------------------------------- ### BoardBuilder::new() Source: https://jordanbray.github.io/chess/chess/struct.BoardBuilder.html Constructs a new, empty BoardBuilder with default settings. ```APIDOC ## `new()` ### Description Construct a new, empty, BoardBuilder. * No pieces are on the board * `CastleRights` are empty for both sides * `en_passant` is not set * `side_to_move` is Color::White ### Method `pub fn new() -> BoardBuilder` ### Example ```rust use chess::{BoardBuilder, Board, Square, Color, Piece}; use std::convert::TryInto; let board: Board = BoardBuilder::new() .piece(Square::A1, Piece::King, Color::White) .piece(Square::A8, Piece::King, Color::Black) .try_into()?; ``` ``` -------------------------------- ### Usage Example for decl_attribute Source: https://jordanbray.github.io/chess/synstructure/macro.decl_attribute.html This example shows how to define an inner attribute function and then use decl_attribute to wrap it with a custom attribute named 'interesting'. ```rust fn attribute_interesting( _attr: proc_macro2::TokenStream, _structure: synstructure::Structure, ) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_attribute!([interesting] => attribute_interesting); ``` -------------------------------- ### Create New Game Instance Source: https://jordanbray.github.io/chess/chess/struct.Game.html Initializes a new `Game` object representing the standard starting chess position. Asserts that the initial position is the default board. ```rust use chess::{Game, Board}; let game = Game::new(); assert_eq!(game.current_position(), Board::default()); ``` -------------------------------- ### Check if a character is a valid identifier start Source: https://jordanbray.github.io/chess/src/unicode_xid/lib.rs.html Demonstrates how to use the `is_xid_start` method from the `UnicodeXID` trait to check if a character is a valid start for an identifier. ```rust extern crate unicode_xid; use unicode_xid::UnicodeXID; fn main() { let ch = 'a'; println!("Is {} a valid start of an identifier? {}", ch, UnicodeXID::is_xid_start(ch)); } ``` -------------------------------- ### Rust Example: Using compat() for Error Compatibility Source: https://jordanbray.github.io/chess/failure/trait.ResultExt.html Demonstrates how to use the compat() method to wrap an error in Compat, making it compatible with older error handling APIs expecting std::error::Error. ```rust use std::error::Error; struct CustomError; impl Error for CustomError { fn description(&self) -> &str { "My custom error message" } fn cause(&self) -> Option<&Error> { None } } let x = (|| -> Result<(), failure::Error> { Err(CustomError).compat()? // Using compat() here })().with_context(|e| { format!("An error occured: {}", e) }).unwrap_err(); let x = format!("{}", x); assert_eq!(x, "An error occured: My custom error message"); ``` -------------------------------- ### Rust Function Signature Example Source: https://jordanbray.github.io/chess/syn/visit/fn.visit_expr_lit.html Example of a Rust function signature for visiting an expression literal. This is part of the syn crate's visitor pattern. ```rust pub fn visit_expr_lit<'ast, V: ?Sized>(v: &mut V, node: &'ast ExprLit) where V: Visit<'ast>, ``` -------------------------------- ### Example Usage of syn::Macro Source: https://jordanbray.github.io/chess/syn/struct.Macro.html Demonstrates how to parse macro arguments and extract the format string from a macro invocation. ```APIDOC ## Example Usage of syn::Macro This example shows how to define a `Parse` implementation for a custom struct `FormatArgs` and use the `parse_body` method of `syn::Macro` to extract specific information, like a format string literal. ### Code Example ```rust use syn::{parse_quote, Expr, ExprLit, Ident, Lit, LitStr, Macro, Token}; use syn::ext::IdentExt; use syn::parse::{Error, Parse, ParseStream, Result}; use syn::punctuated::Punctuated; // The arguments expected by libcore's format_args macro, and as a // result most other formatting and printing macros like println. // // println!("{} is {number:.prec$}", "x", prec=5, number=0.01) struct FormatArgs { format_string: Expr, positional_args: Vec, named_args: Vec<(Ident, Expr)>, } impl Parse for FormatArgs { fn parse(input: ParseStream) -> Result { let format_string: Expr; let mut positional_args = Vec::new(); let mut named_args = Vec::new(); format_string = input.parse()?; while !input.is_empty() { input.parse::()?; if input.is_empty() { break; } if input.peek(Ident::peek_any) && input.peek2(Token![=]) { while !input.is_empty() { let name: Ident = input.call(Ident::parse_any)?; input.parse::()?; let value: Expr = input.parse()?; named_args.push((name, value)); if input.is_empty() { break; } input.parse::()?; } break; } positional_args.push(input.parse()?); } Ok(FormatArgs { format_string, positional_args, named_args, }) } } // Extract the first argument, the format string literal, from an // invocation of a formatting or printing macro. fn get_format_string(m: &Macro) -> Result { let args: FormatArgs = m.parse_body()?; match args.format_string { Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) => Ok(lit), other => { // First argument was not a string literal expression. // Maybe something like: println!(concat!(...), ...) Err(Error::new_spanned(other, "format string must be a string literal")) } } } fn main() { let invocation = parse_quote! { println!("{:?}", Instant::now()) }; let lit = get_format_string(&invocation).unwrap(); assert_eq!(lit.value(), "{{:?}}"); } ``` ``` -------------------------------- ### Initialize New Chess Game Source: https://jordanbray.github.io/chess/src/chess/game.rs.html Creates a new `Game` instance initialized to the standard starting chess position. Asserts that the initial game state matches the default board. ```rust impl Game { /// Create a new `Game` with the initial position. /// /// ``` /// use chess::{Game, Board}; /// /// let game = Game::new(); /// assert_eq!(game.current_position(), Board::default()); /// ``` pub fn new() -> Game { Game { start_pos: Board::default(), moves: vec![], } } ``` -------------------------------- ### Rust Search Syntax Examples Source: https://jordanbray.github.io/chess/libc/fn.aio_cancel.html Demonstrates various ways to refine searches in Rust documentation. Use prefixes like 'fn:' to filter by type, or specify type signatures for function searches. ```rust ? Show this help dialog ``` ```rust S Focus the search field ``` ```rust ↑ Move up in search results ``` ```rust ↓ Move down in search results ``` ```rust ↹ Switch tab ``` ```rust ⏎ Go to active search result ``` ```rust + Expand all sections ``` ```rust - Collapse all sections ``` ```rust Prefix searches with a type followed by a colon (e.g., `fn:`) ``` ```rust Search functions by type signature (e.g., `vec -> usize` or `* -> vec`) ``` ```rust Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`) ``` ```rust You can look for items with an exact name by putting double quotes around your request: `"string"` ``` ```rust Look for items inside another one by searching for a path: `vec::Vec` ``` -------------------------------- ### Rust Function Signature Example Source: https://jordanbray.github.io/chess/libc/fn.strdup.html This is an example of a Rust function signature for `strdup` from the C standard library, indicating its unsafe and external C calling convention. ```rust pub unsafe extern "C" fn strdup(cs: *const c_char) -> *mut c_char ``` -------------------------------- ### Initialize Board and Generate Legal Moves Source: https://jordanbray.github.io/chess/src/chess/movegen/movegen.rs.html Initializes a chess board from a FEN string and generates all legal moves for the current position. Requires `BoardBuilder` and `MoveGen`. ```rust BoardBuilder::from_str("rnbqkbnr/ppp2pp1/4p3/3N4/3PpPp1/8/PPP3PP/R1B1KBNR b KQkq f3 0 1") .unwrap() .try_into() .unwrap(); let _ = MoveGen::new_legal(&board); ``` -------------------------------- ### Trim Start Matches Helper Function Source: https://jordanbray.github.io/chess/src/synstructure/lib.rs.html A helper function to trim characters from the start of a string slice, aliasing `trim_left_matches` for compatibility with older Rust versions. ```rust /// `trim_left_matches` has been deprecated in favor of `trim_start_matches`. /// This helper silences the warning, as we need to continue using /// `trim_left_matches` for rust 1.15 support. #[allow(deprecated)] fn trim_start_matches(s: &str, c: char) -> &str { s.trim_left_matches(c) } ``` -------------------------------- ### QSelf Example: Qualified Path Source: https://jordanbray.github.io/chess/syn/struct.QSelf.html Illustrates the structure of a qualified path with an explicit Self type, showing how 'ty' and 'position' fields are used. ```rust as a::b::Trait>::AssociatedItem ^~~~~~ ~~~~~~~~~~~~~~^ ty position = 3 ``` -------------------------------- ### Create Error with Start and End Spans in Rust Source: https://jordanbray.github.io/chess/src/syn/error.rs.html Initializes an `Error` with specific start and end spans and a message. This is useful for precise error location reporting. ```rust pub fn new2(start: Span, end: Span, message: T) -> Error { Error { messages: vec![ErrorMessage { start_span: ThreadBound::new(start), end_span: ThreadBound::new(end), message: message.to_string(), }], } } ``` -------------------------------- ### Rust Function Signature Example Source: https://jordanbray.github.io/chess/libc/fn.pthread_cond_broadcast.html This is an example of a C function signature in Rust, likely for FFI purposes. It requires `unsafe` and `extern "C"` keywords. ```rust pub unsafe extern "C" fn pthread_cond_broadcast( cond: *mut pthread_cond_t ) -> c_int ``` -------------------------------- ### Initialize Chess Game with Specific Board Source: https://jordanbray.github.io/chess/src/chess/game.rs.html Creates a new `Game` instance with a user-specified starting board position. Verifies that the game's current position matches the provided board. ```rust /// Create a new `Game` with a specific starting position. /// /// ``` /// use chess::{Game, Board}; /// /// let game = Game::new_with_board(Board::default()); /// assert_eq!(game.current_position(), Board::default()); /// ``` ``` -------------------------------- ### Attribute Examples in Rust Syntax Source: https://jordanbray.github.io/chess/syn/struct.Attribute.html Illustrates how attributes are represented in Rust code, showing the path and tokens for different attribute types. ```rust #[derive(Copy)] #[crate::precondition x < 5] ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~ path tokens path tokens ``` -------------------------------- ### Generate Legal Moves on Starting Position Source: https://jordanbray.github.io/chess/chess/index.html Generates all legal moves from the default chess starting position and asserts the count. Ensure the 'chess' crate is added as a dependency. ```rust use chess::{Board, MoveGen}; let board = Board::default(); let movegen = MoveGen::new_legal(&board); assert_eq!(movegen.len(), 20); ``` -------------------------------- ### Keyboard Shortcuts for Help and Navigation Source: https://jordanbray.github.io/chess/failure/struct.Context.html Lists keyboard shortcuts for displaying help, focusing search, navigating search results, switching tabs, and expanding/collapsing sections. ```text ? ``` ```text S ``` ```text ↑ ``` ```text ↓ ``` ```text ↹ ``` ```text ⏎ ``` ```text + ``` ```text - ``` -------------------------------- ### Compiler Error Example Source: https://jordanbray.github.io/chess/syn/spanned/index.html This is an example of a compiler error generated when a type does not satisfy a trait bound, with the error message correctly pointing to the problematic type due to span information. ```text error[E0277]: the trait bound `*const i32: std::marker::Sync` is not satisfied --> src/main.rs:10:21 | 10 | bad_field: *const i32, | ^^^^^^^^^^ `*const i32` cannot be shared between threads safely ```