diff options
Diffstat (limited to '')
-rw-r--r-- | src/tools/rust-analyzer/bench_data/glorious_old_parser | 8562 | ||||
-rw-r--r-- | src/tools/rust-analyzer/bench_data/numerous_macro_rules | 560 |
2 files changed, 9122 insertions, 0 deletions
diff --git a/src/tools/rust-analyzer/bench_data/glorious_old_parser b/src/tools/rust-analyzer/bench_data/glorious_old_parser new file mode 100644 index 000000000..7e900dfeb --- /dev/null +++ b/src/tools/rust-analyzer/bench_data/glorious_old_parser @@ -0,0 +1,8562 @@ +use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy}; +use crate::ast::{GenericBound, TraitBoundModifier}; +use crate::ast::Unsafety; +use crate::ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind}; +use crate::ast::Block; +use crate::ast::{BlockCheckMode, CaptureBy, Movability}; +use crate::ast::{Constness, Crate}; +use crate::ast::Defaultness; +use crate::ast::EnumDef; +use crate::ast::{Expr, ExprKind, RangeLimits}; +use crate::ast::{Field, FnDecl, FnHeader}; +use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; +use crate::ast::{GenericParam, GenericParamKind}; +use crate::ast::GenericArg; +use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind}; +use crate::ast::{Label, Lifetime, Lit, LitKind}; +use crate::ast::Local; +use crate::ast::MacStmtStyle; +use crate::ast::{Mac, Mac_, MacDelimiter}; +use crate::ast::{MutTy, Mutability}; +use crate::ast::{Pat, PatKind, PathSegment}; +use crate::ast::{PolyTraitRef, QSelf}; +use crate::ast::{Stmt, StmtKind}; +use crate::ast::{VariantData, StructField}; +use crate::ast::StrStyle; +use crate::ast::SelfKind; +use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax}; +use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds}; +use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar}; +use crate::ast::{UseTree, UseTreeKind}; +use crate::ast::{BinOpKind, UnOp}; +use crate::ast::{RangeEnd, RangeSyntax}; +use crate::{ast, attr}; +use crate::ext::base::DummyResult; +use crate::source_map::{self, SourceMap, Spanned, respan}; +use crate::parse::{self, SeqSep, classify, token}; +use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace}; +use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration}; +use crate::parse::token::DelimToken; +use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership}; +use crate::util::parser::{AssocOp, Fixity}; +use crate::print::pprust; +use crate::ptr::P; +use crate::parse::PResult; +use crate::ThinVec; +use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; +use crate::symbol::{Symbol, keywords}; + +use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; +use rustc_target::spec::abi::{self, Abi}; +use syntax_pos::{Span, MultiSpan, BytePos, FileName}; +use log::{debug, trace}; + +use std::borrow::Cow; +use std::cmp; +use std::mem; +use std::path::{self, Path, PathBuf}; +use std::slice; + +#[derive(Debug)] +/// Whether the type alias or associated type is a concrete type or an existential type +pub enum AliasKind { + /// Just a new name for the same type + Weak(P<Ty>), + /// Only trait impls of the type will be usable, not the actual type itself + Existential(GenericBounds), +} + +bitflags::bitflags! { + struct Restrictions: u8 { + const STMT_EXPR = 1 << 0; + const NO_STRUCT_LITERAL = 1 << 1; + } +} + +type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>); + +/// Specifies how to parse a path. +#[derive(Copy, Clone, PartialEq)] +pub enum PathStyle { + /// In some contexts, notably in expressions, paths with generic arguments are ambiguous + /// with something else. For example, in expressions `segment < ....` can be interpreted + /// as a comparison and `segment ( ....` can be interpreted as a function call. + /// In all such contexts the non-path interpretation is preferred by default for practical + /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g. + /// `x<y>` - comparisons, `x::<y>` - unambiguously a path. + Expr, + /// In other contexts, notably in types, no ambiguity exists and paths can be written + /// without the disambiguator, e.g., `x<y>` - unambiguously a path. + /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too. + Type, + /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports, + /// visibilities or attributes. + /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead + /// (paths in "mod" contexts have to be checked later for absence of generic arguments + /// anyway, due to macros), but it is used to avoid weird suggestions about expected + /// tokens when something goes wrong. + Mod, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum SemiColonMode { + Break, + Ignore, + Comma, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum BlockMode { + Break, + Ignore, +} + +/// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression +/// dropped into the token stream, which happens while parsing the result of +/// macro expansion). Placement of these is not as complex as I feared it would +/// be. The important thing is to make sure that lookahead doesn't balk at +/// `token::Interpolated` tokens. +macro_rules! maybe_whole_expr { + ($p:expr) => { + if let token::Interpolated(nt) = $p.token.clone() { + match *nt { + token::NtExpr(ref e) | token::NtLiteral(ref e) => { + $p.bump(); + return Ok((*e).clone()); + } + token::NtPath(ref path) => { + $p.bump(); + let span = $p.span; + let kind = ExprKind::Path(None, (*path).clone()); + return Ok($p.mk_expr(span, kind, ThinVec::new())); + } + token::NtBlock(ref block) => { + $p.bump(); + let span = $p.span; + let kind = ExprKind::Block((*block).clone(), None); + return Ok($p.mk_expr(span, kind, ThinVec::new())); + } + _ => {}, + }; + } + } +} + +/// As maybe_whole_expr, but for things other than expressions +macro_rules! maybe_whole { + ($p:expr, $constructor:ident, |$x:ident| $e:expr) => { + if let token::Interpolated(nt) = $p.token.clone() { + if let token::$constructor($x) = (*nt).clone() { + $p.bump(); + return Ok($e); + } + } + }; +} + +fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> { + if let Some(ref mut rhs) = rhs { + lhs.append(rhs); + } + lhs +} + +#[derive(Debug, Clone, Copy, PartialEq)] +enum PrevTokenKind { + DocComment, + Comma, + Plus, + Interpolated, + Eof, + Ident, + Other, +} + +trait RecoverQPath: Sized { + const PATH_STYLE: PathStyle = PathStyle::Expr; + fn to_ty(&self) -> Option<P<Ty>>; + fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self; + fn to_string(&self) -> String; +} + +impl RecoverQPath for Ty { + const PATH_STYLE: PathStyle = PathStyle::Type; + fn to_ty(&self) -> Option<P<Ty>> { + Some(P(self.clone())) + } + fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self { + Self { span: path.span, node: TyKind::Path(qself, path), id: self.id } + } + fn to_string(&self) -> String { + pprust::ty_to_string(self) + } +} + +impl RecoverQPath for Pat { + fn to_ty(&self) -> Option<P<Ty>> { + self.to_ty() + } + fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self { + Self { span: path.span, node: PatKind::Path(qself, path), id: self.id } + } + fn to_string(&self) -> String { + pprust::pat_to_string(self) + } +} + +impl RecoverQPath for Expr { + fn to_ty(&self) -> Option<P<Ty>> { + self.to_ty() + } + fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self { + Self { span: path.span, node: ExprKind::Path(qself, path), + id: self.id, attrs: self.attrs.clone() } + } + fn to_string(&self) -> String { + pprust::expr_to_string(self) + } +} + +/* ident is handled by common.rs */ + +#[derive(Clone)] +pub struct Parser<'a> { + pub sess: &'a ParseSess, + /// the current token: + pub token: token::Token, + /// the span of the current token: + pub span: Span, + /// the span of the previous token: + meta_var_span: Option<Span>, + pub prev_span: Span, + /// the previous token kind + prev_token_kind: PrevTokenKind, + restrictions: Restrictions, + /// Used to determine the path to externally loaded source files + crate directory: Directory<'a>, + /// Whether to parse sub-modules in other files. + pub recurse_into_file_modules: bool, + /// Name of the root module this parser originated from. If `None`, then the + /// name is not known. This does not change while the parser is descending + /// into modules, and sub-parsers have new values for this name. + pub root_module_name: Option<String>, + crate expected_tokens: Vec<TokenType>, + token_cursor: TokenCursor, + desugar_doc_comments: bool, + /// Whether we should configure out of line modules as we parse. + pub cfg_mods: bool, + /// This field is used to keep track of how many left angle brackets we have seen. This is + /// required in order to detect extra leading left angle brackets (`<` characters) and error + /// appropriately. + /// + /// See the comments in the `parse_path_segment` function for more details. + crate unmatched_angle_bracket_count: u32, + crate max_angle_bracket_count: u32, + /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery + /// it gets removed from here. Every entry left at the end gets emitted as an independent + /// error. + crate unclosed_delims: Vec<UnmatchedBrace>, +} + + +#[derive(Clone)] +struct TokenCursor { + frame: TokenCursorFrame, + stack: Vec<TokenCursorFrame>, +} + +#[derive(Clone)] +struct TokenCursorFrame { + delim: token::DelimToken, + span: DelimSpan, + open_delim: bool, + tree_cursor: tokenstream::Cursor, + close_delim: bool, + last_token: LastToken, +} + +/// This is used in `TokenCursorFrame` above to track tokens that are consumed +/// by the parser, and then that's transitively used to record the tokens that +/// each parse AST item is created with. +/// +/// Right now this has two states, either collecting tokens or not collecting +/// tokens. If we're collecting tokens we just save everything off into a local +/// `Vec`. This should eventually though likely save tokens from the original +/// token stream and just use slicing of token streams to avoid creation of a +/// whole new vector. +/// +/// The second state is where we're passively not recording tokens, but the last +/// token is still tracked for when we want to start recording tokens. This +/// "last token" means that when we start recording tokens we'll want to ensure +/// that this, the first token, is included in the output. +/// +/// You can find some more example usage of this in the `collect_tokens` method +/// on the parser. +#[derive(Clone)] +enum LastToken { + Collecting(Vec<TreeAndJoint>), + Was(Option<TreeAndJoint>), +} + +impl TokenCursorFrame { + fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self { + TokenCursorFrame { + delim: delim, + span: sp, + open_delim: delim == token::NoDelim, + tree_cursor: tts.clone().into_trees(), + close_delim: delim == token::NoDelim, + last_token: LastToken::Was(None), + } + } +} + +impl TokenCursor { + fn next(&mut self) -> TokenAndSpan { + loop { + let tree = if !self.frame.open_delim { + self.frame.open_delim = true; + TokenTree::open_tt(self.frame.span.open, self.frame.delim) + } else if let Some(tree) = self.frame.tree_cursor.next() { + tree + } else if !self.frame.close_delim { + self.frame.close_delim = true; + TokenTree::close_tt(self.frame.span.close, self.frame.delim) + } else if let Some(frame) = self.stack.pop() { + self.frame = frame; + continue + } else { + return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP } + }; + + match self.frame.last_token { + LastToken::Collecting(ref mut v) => v.push(tree.clone().into()), + LastToken::Was(ref mut t) => *t = Some(tree.clone().into()), + } + + match tree { + TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp }, + TokenTree::Delimited(sp, delim, tts) => { + let frame = TokenCursorFrame::new(sp, delim, &tts); + self.stack.push(mem::replace(&mut self.frame, frame)); + } + } + } + } + + fn next_desugared(&mut self) -> TokenAndSpan { + let (sp, name) = match self.next() { + TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name), + tok => return tok, + }; + + let stripped = strip_doc_comment_decoration(&name.as_str()); + + // Searches for the occurrences of `"#*` and returns the minimum number of `#`s + // required to wrap the text. + let mut num_of_hashes = 0; + let mut count = 0; + for ch in stripped.chars() { + count = match ch { + '"' => 1, + '#' if count > 0 => count + 1, + _ => 0, + }; + num_of_hashes = cmp::max(num_of_hashes, count); + } + + let delim_span = DelimSpan::from_single(sp); + let body = TokenTree::Delimited( + delim_span, + token::Bracket, + [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)), + TokenTree::Token(sp, token::Eq), + TokenTree::Token(sp, token::Literal( + token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None)) + ] + .iter().cloned().collect::<TokenStream>().into(), + ); + + self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new( + delim_span, + token::NoDelim, + &if doc_comment_style(&name.as_str()) == AttrStyle::Inner { + [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body] + .iter().cloned().collect::<TokenStream>().into() + } else { + [TokenTree::Token(sp, token::Pound), body] + .iter().cloned().collect::<TokenStream>().into() + }, + ))); + + self.next() + } +} + +#[derive(Clone, PartialEq)] +crate enum TokenType { + Token(token::Token), + Keyword(keywords::Keyword), + Operator, + Lifetime, + Ident, + Path, + Type, + Const, +} + +impl TokenType { + fn to_string(&self) -> String { + match *self { + TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)), + TokenType::Keyword(kw) => format!("`{}`", kw.name()), + TokenType::Operator => "an operator".to_string(), + TokenType::Lifetime => "lifetime".to_string(), + TokenType::Ident => "identifier".to_string(), + TokenType::Path => "path".to_string(), + TokenType::Type => "type".to_string(), + TokenType::Const => "const".to_string(), + } + } +} + +/// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`, +/// `IDENT<<u8 as Trait>::AssocTy>`. +/// +/// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes +/// that `IDENT` is not the ident of a fn trait. +fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool { + t == &token::ModSep || t == &token::Lt || + t == &token::BinOp(token::Shl) +} + +/// Information about the path to a module. +pub struct ModulePath { + name: String, + path_exists: bool, + pub result: Result<ModulePathSuccess, Error>, +} + +pub struct ModulePathSuccess { + pub path: PathBuf, + pub directory_ownership: DirectoryOwnership, + warn: bool, +} + +pub enum Error { + FileNotFoundForModule { + mod_name: String, + default_path: String, + secondary_path: String, + dir_path: String, + }, + DuplicatePaths { + mod_name: String, + default_path: String, + secondary_path: String, + }, + UselessDocComment, + InclusiveRangeWithNoEnd, +} + +impl Error { + fn span_err<S: Into<MultiSpan>>(self, + sp: S, + handler: &errors::Handler) -> DiagnosticBuilder<'_> { + match self { + Error::FileNotFoundForModule { ref mod_name, + ref default_path, + ref secondary_path, + ref dir_path } => { + let mut err = struct_span_err!(handler, sp, E0583, + "file not found for module `{}`", mod_name); + err.help(&format!("name the file either {} or {} inside the directory \"{}\"", + default_path, + secondary_path, + dir_path)); + err + } + Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => { + let mut err = struct_span_err!(handler, sp, E0584, + "file for module `{}` found at both {} and {}", + mod_name, + default_path, + secondary_path); + err.help("delete or rename one of them to remove the ambiguity"); + err + } + Error::UselessDocComment => { + let mut err = struct_span_err!(handler, sp, E0585, + "found a documentation comment that doesn't document anything"); + err.help("doc comments must come before what they document, maybe a comment was \ + intended with `//`?"); + err + } + Error::InclusiveRangeWithNoEnd => { + let mut err = struct_span_err!(handler, sp, E0586, + "inclusive range with no end"); + err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)"); + err + } + } + } +} + +#[derive(Debug)] +enum LhsExpr { + NotYetParsed, + AttributesParsed(ThinVec<Attribute>), + AlreadyParsed(P<Expr>), +} + +impl From<Option<ThinVec<Attribute>>> for LhsExpr { + fn from(o: Option<ThinVec<Attribute>>) -> Self { + if let Some(attrs) = o { + LhsExpr::AttributesParsed(attrs) + } else { + LhsExpr::NotYetParsed + } + } +} + +impl From<P<Expr>> for LhsExpr { + fn from(expr: P<Expr>) -> Self { + LhsExpr::AlreadyParsed(expr) + } +} + +/// Creates a placeholder argument. +fn dummy_arg(span: Span) -> Arg { + let ident = Ident::new(keywords::Invalid.name(), span); + let pat = P(Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None), + span, + }); + let ty = Ty { + node: TyKind::Err, + span, + id: ast::DUMMY_NODE_ID + }; + Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID } +} + +#[derive(Copy, Clone, Debug)] +enum TokenExpectType { + Expect, + NoExpect, +} + +impl<'a> Parser<'a> { + pub fn new(sess: &'a ParseSess, + tokens: TokenStream, + directory: Option<Directory<'a>>, + recurse_into_file_modules: bool, + desugar_doc_comments: bool) + -> Self { + let mut parser = Parser { + sess, + token: token::Whitespace, + span: syntax_pos::DUMMY_SP, + prev_span: syntax_pos::DUMMY_SP, + meta_var_span: None, + prev_token_kind: PrevTokenKind::Other, + restrictions: Restrictions::empty(), + recurse_into_file_modules, + directory: Directory { + path: Cow::from(PathBuf::new()), + ownership: DirectoryOwnership::Owned { relative: None } + }, + root_module_name: None, + expected_tokens: Vec::new(), + token_cursor: TokenCursor { + frame: TokenCursorFrame::new( + DelimSpan::dummy(), + token::NoDelim, + &tokens.into(), + ), + stack: Vec::new(), + }, + desugar_doc_comments, + cfg_mods: true, + unmatched_angle_bracket_count: 0, + max_angle_bracket_count: 0, + unclosed_delims: Vec::new(), + }; + + let tok = parser.next_tok(); + parser.token = tok.tok; + parser.span = tok.sp; + + if let Some(directory) = directory { + parser.directory = directory; + } else if !parser.span.is_dummy() { + if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) { + path.pop(); + parser.directory.path = Cow::from(path); + } + } + + parser.process_potential_macro_variable(); + parser + } + + fn next_tok(&mut self) -> TokenAndSpan { + let mut next = if self.desugar_doc_comments { + self.token_cursor.next_desugared() + } else { + self.token_cursor.next() + }; + if next.sp.is_dummy() { + // Tweak the location for better diagnostics, but keep syntactic context intact. + next.sp = self.prev_span.with_ctxt(next.sp.ctxt()); + } + next + } + + /// Converts the current token to a string using `self`'s reader. + pub fn this_token_to_string(&self) -> String { + pprust::token_to_string(&self.token) + } + + fn token_descr(&self) -> Option<&'static str> { + Some(match &self.token { + t if t.is_special_ident() => "reserved identifier", + t if t.is_used_keyword() => "keyword", + t if t.is_unused_keyword() => "reserved keyword", + token::DocComment(..) => "doc comment", + _ => return None, + }) + } + + fn this_token_descr(&self) -> String { + if let Some(prefix) = self.token_descr() { + format!("{} `{}`", prefix, self.this_token_to_string()) + } else { + format!("`{}`", self.this_token_to_string()) + } + } + + fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> { + let token_str = pprust::token_to_string(t); + Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str))) + } + + crate fn unexpected<T>(&mut self) -> PResult<'a, T> { + match self.expect_one_of(&[], &[]) { + Err(e) => Err(e), + Ok(_) => unreachable!(), + } + } + + /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. + pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> { + if self.expected_tokens.is_empty() { + if self.token == *t { + self.bump(); + Ok(false) + } else { + let token_str = pprust::token_to_string(t); + let this_token_str = self.this_token_descr(); + let mut err = self.fatal(&format!("expected `{}`, found {}", + token_str, + this_token_str)); + + let sp = if self.token == token::Token::Eof { + // EOF, don't want to point at the following char, but rather the last token + self.prev_span + } else { + self.sess.source_map().next_point(self.prev_span) + }; + let label_exp = format!("expected `{}`", token_str); + match self.recover_closing_delimiter(&[t.clone()], err) { + Err(e) => err = e, + Ok(recovered) => { + return Ok(recovered); + } + } + let cm = self.sess.source_map(); + match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { + (Ok(ref a), Ok(ref b)) if a.line == b.line => { + // When the spans are in the same line, it means that the only content + // between them is whitespace, point only at the found token. + err.span_label(self.span, label_exp); + } + _ => { + err.span_label(sp, label_exp); + err.span_label(self.span, "unexpected token"); + } + } + Err(err) + } + } else { + self.expect_one_of(slice::from_ref(t), &[]) + } + } + + fn recover_closing_delimiter( + &mut self, + tokens: &[token::Token], + mut err: DiagnosticBuilder<'a>, + ) -> PResult<'a, bool> { + let mut pos = None; + // we want to use the last closing delim that would apply + for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() { + if tokens.contains(&token::CloseDelim(unmatched.expected_delim)) + && Some(self.span) > unmatched.unclosed_span + { + pos = Some(i); + } + } + match pos { + Some(pos) => { + // Recover and assume that the detected unclosed delimiter was meant for + // this location. Emit the diagnostic and act as if the delimiter was + // present for the parser's sake. + + // Don't attempt to recover from this unclosed delimiter more than once. + let unmatched = self.unclosed_delims.remove(pos); + let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim)); + + // We want to suggest the inclusion of the closing delimiter where it makes + // the most sense, which is immediately after the last token: + // + // {foo(bar {}} + // - ^ + // | | + // | help: `)` may belong here (FIXME: #58270) + // | + // unclosed delimiter + if let Some(sp) = unmatched.unclosed_span { + err.span_label(sp, "unclosed delimiter"); + } + err.span_suggestion_short( + self.sess.source_map().next_point(self.prev_span), + &format!("{} may belong here", delim.to_string()), + delim.to_string(), + Applicability::MaybeIncorrect, + ); + err.emit(); + self.expected_tokens.clear(); // reduce errors + Ok(true) + } + _ => Err(err), + } + } + + /// Expect next token to be edible or inedible token. If edible, + /// then consume it; if inedible, then return without consuming + /// anything. Signal a fatal error if next token is unexpected. + pub fn expect_one_of( + &mut self, + edible: &[token::Token], + inedible: &[token::Token], + ) -> PResult<'a, bool /* recovered */> { + fn tokens_to_string(tokens: &[TokenType]) -> String { + let mut i = tokens.iter(); + // This might be a sign we need a connect method on Iterator. + let b = i.next() + .map_or(String::new(), |t| t.to_string()); + i.enumerate().fold(b, |mut b, (i, a)| { + if tokens.len() > 2 && i == tokens.len() - 2 { + b.push_str(", or "); + } else if tokens.len() == 2 && i == tokens.len() - 2 { + b.push_str(" or "); + } else { + b.push_str(", "); + } + b.push_str(&a.to_string()); + b + }) + } + if edible.contains(&self.token) { + self.bump(); + Ok(false) + } else if inedible.contains(&self.token) { + // leave it in the input + Ok(false) + } else { + let mut expected = edible.iter() + .map(|x| TokenType::Token(x.clone())) + .chain(inedible.iter().map(|x| TokenType::Token(x.clone()))) + .chain(self.expected_tokens.iter().cloned()) + .collect::<Vec<_>>(); + expected.sort_by_cached_key(|x| x.to_string()); + expected.dedup(); + let expect = tokens_to_string(&expected[..]); + let actual = self.this_token_to_string(); + let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 { + let short_expect = if expected.len() > 6 { + format!("{} possible tokens", expected.len()) + } else { + expect.clone() + }; + (format!("expected one of {}, found `{}`", expect, actual), + (self.sess.source_map().next_point(self.prev_span), + format!("expected one of {} here", short_expect))) + } else if expected.is_empty() { + (format!("unexpected token: `{}`", actual), + (self.prev_span, "unexpected token after this".to_string())) + } else { + (format!("expected {}, found `{}`", expect, actual), + (self.sess.source_map().next_point(self.prev_span), + format!("expected {} here", expect))) + }; + let mut err = self.fatal(&msg_exp); + if self.token.is_ident_named("and") { + err.span_suggestion_short( + self.span, + "use `&&` instead of `and` for the boolean operator", + "&&".to_string(), + Applicability::MaybeIncorrect, + ); + } + if self.token.is_ident_named("or") { + err.span_suggestion_short( + self.span, + "use `||` instead of `or` for the boolean operator", + "||".to_string(), + Applicability::MaybeIncorrect, + ); + } + let sp = if self.token == token::Token::Eof { + // This is EOF, don't want to point at the following char, but rather the last token + self.prev_span + } else { + label_sp + }; + match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt { + TokenType::Token(t) => Some(t.clone()), + _ => None, + }).collect::<Vec<_>>(), err) { + Err(e) => err = e, + Ok(recovered) => { + return Ok(recovered); + } + } + + let cm = self.sess.source_map(); + match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { + (Ok(ref a), Ok(ref b)) if a.line == b.line => { + // When the spans are in the same line, it means that the only content between + // them is whitespace, point at the found token in that case: + // + // X | () => { syntax error }; + // | ^^^^^ expected one of 8 possible tokens here + // + // instead of having: + // + // X | () => { syntax error }; + // | -^^^^^ unexpected token + // | | + // | expected one of 8 possible tokens here + err.span_label(self.span, label_exp); + } + _ if self.prev_span == syntax_pos::DUMMY_SP => { + // Account for macro context where the previous span might not be + // available to avoid incorrect output (#54841). + err.span_label(self.span, "unexpected token"); + } + _ => { + err.span_label(sp, label_exp); + err.span_label(self.span, "unexpected token"); + } + } + Err(err) + } + } + + /// Returns the span of expr, if it was not interpolated or the span of the interpolated token. + fn interpolated_or_expr_span(&self, + expr: PResult<'a, P<Expr>>) + -> PResult<'a, (Span, P<Expr>)> { + expr.map(|e| { + if self.prev_token_kind == PrevTokenKind::Interpolated { + (self.prev_span, e) + } else { + (e.span, e) + } + }) + } + + fn expected_ident_found(&self) -> DiagnosticBuilder<'a> { + let mut err = self.struct_span_err(self.span, + &format!("expected identifier, found {}", + self.this_token_descr())); + if let token::Ident(ident, false) = &self.token { + if ident.is_reserved() && !ident.is_path_segment_keyword() && + ident.name != keywords::Underscore.name() + { + err.span_suggestion( + self.span, + "you can escape reserved keywords to use them as identifiers", + format!("r#{}", ident), + Applicability::MaybeIncorrect, + ); + } + } + if let Some(token_descr) = self.token_descr() { + err.span_label(self.span, format!("expected identifier, found {}", token_descr)); + } else { + err.span_label(self.span, "expected identifier"); + if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) { + err.span_suggestion( + self.span, + "remove this comma", + String::new(), + Applicability::MachineApplicable, + ); + } + } + err + } + + pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> { + self.parse_ident_common(true) + } + + fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> { + match self.token { + token::Ident(ident, _) => { + if self.token.is_reserved_ident() { + let mut err = self.expected_ident_found(); + if recover { + err.emit(); + } else { + return Err(err); + } + } + let span = self.span; + self.bump(); + Ok(Ident::new(ident.name, span)) + } + _ => { + Err(if self.prev_token_kind == PrevTokenKind::DocComment { + self.span_fatal_err(self.prev_span, Error::UselessDocComment) + } else { + self.expected_ident_found() + }) + } + } + } + + /// Checks if the next token is `tok`, and returns `true` if so. + /// + /// This method will automatically add `tok` to `expected_tokens` if `tok` is not + /// encountered. + crate fn check(&mut self, tok: &token::Token) -> bool { + let is_present = self.token == *tok; + if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); } + is_present + } + + /// Consumes a token 'tok' if it exists. Returns whether the given token was present. + pub fn eat(&mut self, tok: &token::Token) -> bool { + let is_present = self.check(tok); + if is_present { self.bump() } + is_present + } + + fn check_keyword(&mut self, kw: keywords::Keyword) -> bool { + self.expected_tokens.push(TokenType::Keyword(kw)); + self.token.is_keyword(kw) + } + + /// If the next token is the given keyword, eats it and returns + /// `true`. Otherwise, returns `false`. + pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool { + if self.check_keyword(kw) { + self.bump(); + true + } else { + false + } + } + + fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool { + if self.token.is_keyword(kw) { + self.bump(); + true + } else { + false + } + } + + /// If the given word is not a keyword, signals an error. + /// If the next token is not the given word, signals an error. + /// Otherwise, eats it. + fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> { + if !self.eat_keyword(kw) { + self.unexpected() + } else { + Ok(()) + } + } + + fn check_ident(&mut self) -> bool { + if self.token.is_ident() { + true + } else { + self.expected_tokens.push(TokenType::Ident); + false + } + } + + fn check_path(&mut self) -> bool { + if self.token.is_path_start() { + true + } else { + self.expected_tokens.push(TokenType::Path); + false + } + } + + fn check_type(&mut self) -> bool { + if self.token.can_begin_type() { + true + } else { + self.expected_tokens.push(TokenType::Type); + false + } + } + + fn check_const_arg(&mut self) -> bool { + if self.token.can_begin_const_arg() { + true + } else { + self.expected_tokens.push(TokenType::Const); + false + } + } + + /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=` + /// and continues. If a `+` is not seen, returns `false`. + /// + /// This is used when token-splitting `+=` into `+`. + /// See issue #47856 for an example of when this may occur. + fn eat_plus(&mut self) -> bool { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus))); + match self.token { + token::BinOp(token::Plus) => { + self.bump(); + true + } + token::BinOpEq(token::Plus) => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + self.bump_with(token::Eq, span); + true + } + _ => false, + } + } + + + /// Checks to see if the next token is either `+` or `+=`. + /// Otherwise returns `false`. + fn check_plus(&mut self) -> bool { + if self.token.is_like_plus() { + true + } + else { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus))); + false + } + } + + /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single + /// `&` and continues. If an `&` is not seen, signals an error. + fn expect_and(&mut self) -> PResult<'a, ()> { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::And))); + match self.token { + token::BinOp(token::And) => { + self.bump(); + Ok(()) + } + token::AndAnd => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + Ok(self.bump_with(token::BinOp(token::And), span)) + } + _ => self.unexpected() + } + } + + /// Expects and consumes an `|`. If `||` is seen, replaces it with a single + /// `|` and continues. If an `|` is not seen, signals an error. + fn expect_or(&mut self) -> PResult<'a, ()> { + self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or))); + match self.token { + token::BinOp(token::Or) => { + self.bump(); + Ok(()) + } + token::OrOr => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + Ok(self.bump_with(token::BinOp(token::Or), span)) + } + _ => self.unexpected() + } + } + + fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) { + match suffix { + None => {/* everything ok */} + Some(suf) => { + let text = suf.as_str(); + if text.is_empty() { + self.span_bug(sp, "found empty literal suffix in Some") + } + let msg = format!("{} with a suffix is invalid", kind); + self.struct_span_err(sp, &msg) + .span_label(sp, msg) + .emit(); + } + } + } + + /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single + /// `<` and continue. If `<-` is seen, replaces it with a single `<` + /// and continue. If a `<` is not seen, returns false. + /// + /// This is meant to be used when parsing generics on a path to get the + /// starting token. + fn eat_lt(&mut self) -> bool { + self.expected_tokens.push(TokenType::Token(token::Lt)); + let ate = match self.token { + token::Lt => { + self.bump(); + true + } + token::BinOp(token::Shl) => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + self.bump_with(token::Lt, span); + true + } + token::LArrow => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + self.bump_with(token::BinOp(token::Minus), span); + true + } + _ => false, + }; + + if ate { + // See doc comment for `unmatched_angle_bracket_count`. + self.unmatched_angle_bracket_count += 1; + self.max_angle_bracket_count += 1; + debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); + } + + ate + } + + fn expect_lt(&mut self) -> PResult<'a, ()> { + if !self.eat_lt() { + self.unexpected() + } else { + Ok(()) + } + } + + /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it + /// with a single `>` and continues. If a `>` is not seen, signals an error. + fn expect_gt(&mut self) -> PResult<'a, ()> { + self.expected_tokens.push(TokenType::Token(token::Gt)); + let ate = match self.token { + token::Gt => { + self.bump(); + Some(()) + } + token::BinOp(token::Shr) => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + Some(self.bump_with(token::Gt, span)) + } + token::BinOpEq(token::Shr) => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + Some(self.bump_with(token::Ge, span)) + } + token::Ge => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + Some(self.bump_with(token::Eq, span)) + } + _ => None, + }; + + match ate { + Some(_) => { + // See doc comment for `unmatched_angle_bracket_count`. + if self.unmatched_angle_bracket_count > 0 { + self.unmatched_angle_bracket_count -= 1; + debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); + } + + Ok(()) + }, + None => self.unexpected(), + } + } + + /// Eats and discards tokens until one of `kets` is encountered. Respects token trees, + /// passes through any errors encountered. Used for error recovery. + fn eat_to_tokens(&mut self, kets: &[&token::Token]) { + let handler = self.diagnostic(); + + if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets, + SeqSep::none(), + TokenExpectType::Expect, + |p| Ok(p.parse_token_tree())) { + handler.cancel(err); + } + } + + /// Parses a sequence, including the closing delimiter. The function + /// `f` must consume tokens until reaching the next separator or + /// closing bracket. + pub fn parse_seq_to_end<T, F>(&mut self, + ket: &token::Token, + sep: SeqSep, + f: F) + -> PResult<'a, Vec<T>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; + if !recovered { + self.bump(); + } + Ok(val) + } + + /// Parses a sequence, not including the closing delimiter. The function + /// `f` must consume tokens until reaching the next separator or + /// closing bracket. + pub fn parse_seq_to_before_end<T, F>( + &mut self, + ket: &token::Token, + sep: SeqSep, + f: F, + ) -> PResult<'a, (Vec<T>, bool)> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, T> + { + self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) + } + + fn parse_seq_to_before_tokens<T, F>( + &mut self, + kets: &[&token::Token], + sep: SeqSep, + expect: TokenExpectType, + mut f: F, + ) -> PResult<'a, (Vec<T>, bool /* recovered */)> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, T> + { + let mut first = true; + let mut recovered = false; + let mut v = vec![]; + while !kets.iter().any(|k| { + match expect { + TokenExpectType::Expect => self.check(k), + TokenExpectType::NoExpect => self.token == **k, + } + }) { + match self.token { + token::CloseDelim(..) | token::Eof => break, + _ => {} + }; + if let Some(ref t) = sep.sep { + if first { + first = false; + } else { + match self.expect(t) { + Ok(false) => {} + Ok(true) => { + recovered = true; + break; + } + Err(mut e) => { + // Attempt to keep parsing if it was a similar separator + if let Some(ref tokens) = t.similar_tokens() { + if tokens.contains(&self.token) { + self.bump(); + } + } + e.emit(); + // Attempt to keep parsing if it was an omitted separator + match f(self) { + Ok(t) => { + v.push(t); + continue; + }, + Err(mut e) => { + e.cancel(); + break; + } + } + } + } + } + } + if sep.trailing_sep_allowed && kets.iter().any(|k| { + match expect { + TokenExpectType::Expect => self.check(k), + TokenExpectType::NoExpect => self.token == **k, + } + }) { + break; + } + + let t = f(self)?; + v.push(t); + } + + Ok((v, recovered)) + } + + /// Parses a sequence, including the closing delimiter. The function + /// `f` must consume tokens until reaching the next separator or + /// closing bracket. + fn parse_unspanned_seq<T, F>( + &mut self, + bra: &token::Token, + ket: &token::Token, + sep: SeqSep, + f: F, + ) -> PResult<'a, Vec<T>> where + F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, + { + self.expect(bra)?; + let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; + if !recovered { + self.eat(ket); + } + Ok(result) + } + + /// Advance the parser by one token + pub fn bump(&mut self) { + if self.prev_token_kind == PrevTokenKind::Eof { + // Bumping after EOF is a bad sign, usually an infinite loop. + self.bug("attempted to bump the parser past EOF (may be stuck in a loop)"); + } + + self.prev_span = self.meta_var_span.take().unwrap_or(self.span); + + // Record last token kind for possible error recovery. + self.prev_token_kind = match self.token { + token::DocComment(..) => PrevTokenKind::DocComment, + token::Comma => PrevTokenKind::Comma, + token::BinOp(token::Plus) => PrevTokenKind::Plus, + token::Interpolated(..) => PrevTokenKind::Interpolated, + token::Eof => PrevTokenKind::Eof, + token::Ident(..) => PrevTokenKind::Ident, + _ => PrevTokenKind::Other, + }; + + let next = self.next_tok(); + self.span = next.sp; + self.token = next.tok; + self.expected_tokens.clear(); + // check after each token + self.process_potential_macro_variable(); + } + + /// Advance the parser using provided token as a next one. Use this when + /// consuming a part of a token. For example a single `<` from `<<`. + fn bump_with(&mut self, next: token::Token, span: Span) { + self.prev_span = self.span.with_hi(span.lo()); + // It would be incorrect to record the kind of the current token, but + // fortunately for tokens currently using `bump_with`, the + // prev_token_kind will be of no use anyway. + self.prev_token_kind = PrevTokenKind::Other; + self.span = span; + self.token = next; + self.expected_tokens.clear(); + } + + pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where + F: FnOnce(&token::Token) -> R, + { + if dist == 0 { + return f(&self.token) + } + + f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { + Some(tree) => match tree { + TokenTree::Token(_, tok) => tok, + TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim), + }, + None => token::CloseDelim(self.token_cursor.frame.delim), + }) + } + + fn look_ahead_span(&self, dist: usize) -> Span { + if dist == 0 { + return self.span + } + + match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { + Some(TokenTree::Token(span, _)) => span, + Some(TokenTree::Delimited(span, ..)) => span.entire(), + None => self.look_ahead_span(dist - 1), + } + } + pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_fatal(self.span, m) + } + pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_fatal(sp, m) + } + fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> { + err.span_err(sp, self.diagnostic()) + } + fn bug(&self, m: &str) -> ! { + self.sess.span_diagnostic.span_bug(self.span, m) + } + fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) { + self.sess.span_diagnostic.span_err(sp, m) + } + fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_err(sp, m) + } + crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! { + self.sess.span_diagnostic.span_bug(sp, m) + } + + fn cancel(&self, err: &mut DiagnosticBuilder<'_>) { + self.sess.span_diagnostic.cancel(err) + } + + crate fn diagnostic(&self) -> &'a errors::Handler { + &self.sess.span_diagnostic + } + + /// Is the current token one of the keywords that signals a bare function type? + fn token_is_bare_fn_keyword(&mut self) -> bool { + self.check_keyword(keywords::Fn) || + self.check_keyword(keywords::Unsafe) || + self.check_keyword(keywords::Extern) + } + + /// Parses a `TyKind::BareFn` type. + fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> { + /* + + [unsafe] [extern "ABI"] fn (S) -> T + ^~~~^ ^~~~^ ^~^ ^ + | | | | + | | | Return type + | | Argument types + | | + | ABI + Function Style + */ + + let unsafety = self.parse_unsafety(); + let abi = if self.eat_keyword(keywords::Extern) { + self.parse_opt_abi()?.unwrap_or(Abi::C) + } else { + Abi::Rust + }; + + self.expect_keyword(keywords::Fn)?; + let (inputs, variadic) = self.parse_fn_args(false, true)?; + let ret_ty = self.parse_ret_ty(false)?; + let decl = P(FnDecl { + inputs, + output: ret_ty, + variadic, + }); + Ok(TyKind::BareFn(P(BareFnTy { + abi, + unsafety, + generic_params, + decl, + }))) + } + + /// Parses asyncness: `async` or nothing. + fn parse_asyncness(&mut self) -> IsAsync { + if self.eat_keyword(keywords::Async) { + IsAsync::Async { + closure_id: ast::DUMMY_NODE_ID, + return_impl_trait_id: ast::DUMMY_NODE_ID, + } + } else { + IsAsync::NotAsync + } + } + + /// Parses unsafety: `unsafe` or nothing. + fn parse_unsafety(&mut self) -> Unsafety { + if self.eat_keyword(keywords::Unsafe) { + Unsafety::Unsafe + } else { + Unsafety::Normal + } + } + + /// Parses the items in a trait declaration. + pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> { + maybe_whole!(self, NtTraitItem, |x| x); + let attrs = self.parse_outer_attributes()?; + let (mut item, tokens) = self.collect_tokens(|this| { + this.parse_trait_item_(at_end, attrs) + })?; + // See `parse_item` for why this clause is here. + if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) { + item.tokens = Some(tokens); + } + Ok(item) + } + + fn parse_trait_item_(&mut self, + at_end: &mut bool, + mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> { + let lo = self.span; + + let (name, node, generics) = if self.eat_keyword(keywords::Type) { + self.parse_trait_item_assoc_ty()? + } else if self.is_const_item() { + self.expect_keyword(keywords::Const)?; + let ident = self.parse_ident()?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + let default = if self.eat(&token::Eq) { + let expr = self.parse_expr()?; + self.expect(&token::Semi)?; + Some(expr) + } else { + self.expect(&token::Semi)?; + None + }; + (ident, TraitItemKind::Const(ty, default), ast::Generics::default()) + } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? { + // trait item macro. + (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default()) + } else { + let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?; + + let ident = self.parse_ident()?; + let mut generics = self.parse_generics()?; + + let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| { + // This is somewhat dubious; We don't want to allow + // argument names to be left off if there is a + // definition... + + // We don't allow argument names to be left off in edition 2018. + p.parse_arg_general(p.span.rust_2018(), true) + })?; + generics.where_clause = self.parse_where_clause()?; + + let sig = ast::MethodSig { + header: FnHeader { + unsafety, + constness, + abi, + asyncness, + }, + decl: d, + }; + + let body = match self.token { + token::Semi => { + self.bump(); + *at_end = true; + debug!("parse_trait_methods(): parsing required method"); + None + } + token::OpenDelim(token::Brace) => { + debug!("parse_trait_methods(): parsing provided method"); + *at_end = true; + let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(inner_attrs.iter().cloned()); + Some(body) + } + token::Interpolated(ref nt) => { + match **nt { + token::NtBlock(..) => { + *at_end = true; + let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(inner_attrs.iter().cloned()); + Some(body) + } + _ => { + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", + token_str)); + err.span_label(self.span, "expected `;` or `{`"); + return Err(err); + } + } + } + _ => { + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", + token_str)); + err.span_label(self.span, "expected `;` or `{`"); + return Err(err); + } + }; + (ident, ast::TraitItemKind::Method(sig, body), generics) + }; + + Ok(TraitItem { + id: ast::DUMMY_NODE_ID, + ident: name, + attrs, + generics, + node, + span: lo.to(self.prev_span), + tokens: None, + }) + } + + /// Parses an optional return type `[ -> TY ]` in a function declaration. + fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> { + if self.eat(&token::RArrow) { + Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?)) + } else { + Ok(FunctionRetTy::Default(self.span.shrink_to_lo())) + } + } + + /// Parses a type. + pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> { + self.parse_ty_common(true, true) + } + + /// Parses a type in restricted contexts where `+` is not permitted. + /// + /// Example 1: `&'a TYPE` + /// `+` is prohibited to maintain operator priority (P(+) < P(&)). + /// Example 2: `value1 as TYPE + value2` + /// `+` is prohibited to avoid interactions with expression grammar. + fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> { + self.parse_ty_common(false, true) + } + + fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool) + -> PResult<'a, P<Ty>> { + maybe_whole!(self, NtTy, |x| x); + + let lo = self.span; + let mut impl_dyn_multi = false; + let node = if self.eat(&token::OpenDelim(token::Paren)) { + // `(TYPE)` is a parenthesized type. + // `(TYPE,)` is a tuple with a single field of type TYPE. + let mut ts = vec![]; + let mut last_comma = false; + while self.token != token::CloseDelim(token::Paren) { + ts.push(self.parse_ty()?); + if self.eat(&token::Comma) { + last_comma = true; + } else { + last_comma = false; + break; + } + } + let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus; + self.expect(&token::CloseDelim(token::Paren))?; + + if ts.len() == 1 && !last_comma { + let ty = ts.into_iter().nth(0).unwrap().into_inner(); + let maybe_bounds = allow_plus && self.token.is_like_plus(); + match ty.node { + // `(TY_BOUND_NOPAREN) + BOUND + ...`. + TyKind::Path(None, ref path) if maybe_bounds => { + self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)? + } + TyKind::TraitObject(ref bounds, TraitObjectSyntax::None) + if maybe_bounds && bounds.len() == 1 && !trailing_plus => { + let path = match bounds[0] { + GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(), + GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"), + }; + self.parse_remaining_bounds(Vec::new(), path, lo, true)? + } + // `(TYPE)` + _ => TyKind::Paren(P(ty)) + } + } else { + TyKind::Tup(ts) + } + } else if self.eat(&token::Not) { + // Never type `!` + TyKind::Never + } else if self.eat(&token::BinOp(token::Star)) { + // Raw pointer + TyKind::Ptr(self.parse_ptr()?) + } else if self.eat(&token::OpenDelim(token::Bracket)) { + // Array or slice + let t = self.parse_ty()?; + // Parse optional `; EXPR` in `[TYPE; EXPR]` + let t = match self.maybe_parse_fixed_length_of_vec()? { + None => TyKind::Slice(t), + Some(length) => TyKind::Array(t, AnonConst { + id: ast::DUMMY_NODE_ID, + value: length, + }), + }; + self.expect(&token::CloseDelim(token::Bracket))?; + t + } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) { + // Reference + self.expect_and()?; + self.parse_borrowed_pointee()? + } else if self.eat_keyword_noexpect(keywords::Typeof) { + // `typeof(EXPR)` + // In order to not be ambiguous, the type must be surrounded by parens. + self.expect(&token::OpenDelim(token::Paren))?; + let e = AnonConst { + id: ast::DUMMY_NODE_ID, + value: self.parse_expr()?, + }; + self.expect(&token::CloseDelim(token::Paren))?; + TyKind::Typeof(e) + } else if self.eat_keyword(keywords::Underscore) { + // A type to be inferred `_` + TyKind::Infer + } else if self.token_is_bare_fn_keyword() { + // Function pointer type + self.parse_ty_bare_fn(Vec::new())? + } else if self.check_keyword(keywords::For) { + // Function pointer type or bound list (trait object type) starting with a poly-trait. + // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T` + // `for<'lt> Trait1<'lt> + Trait2 + 'a` + let lo = self.span; + let lifetime_defs = self.parse_late_bound_lifetime_defs()?; + if self.token_is_bare_fn_keyword() { + self.parse_ty_bare_fn(lifetime_defs)? + } else { + let path = self.parse_path(PathStyle::Type)?; + let parse_plus = allow_plus && self.check_plus(); + self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)? + } + } else if self.eat_keyword(keywords::Impl) { + // Always parse bounds greedily for better error recovery. + let bounds = self.parse_generic_bounds(None)?; + impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; + TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds) + } else if self.check_keyword(keywords::Dyn) && + (self.span.rust_2018() || + self.look_ahead(1, |t| t.can_begin_bound() && + !can_continue_type_after_non_fn_ident(t))) { + self.bump(); // `dyn` + // Always parse bounds greedily for better error recovery. + let bounds = self.parse_generic_bounds(None)?; + impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; + TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn) + } else if self.check(&token::Question) || + self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) { + // Bound list (trait object type) + TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?, + TraitObjectSyntax::None) + } else if self.eat_lt() { + // Qualified path + let (qself, path) = self.parse_qpath(PathStyle::Type)?; + TyKind::Path(Some(qself), path) + } else if self.token.is_path_start() { + // Simple path + let path = self.parse_path(PathStyle::Type)?; + if self.eat(&token::Not) { + // Macro invocation in type position + let (delim, tts) = self.expect_delimited_token_tree()?; + let node = Mac_ { path, tts, delim }; + TyKind::Mac(respan(lo.to(self.prev_span), node)) + } else { + // Just a type path or bound list (trait object type) starting with a trait. + // `Type` + // `Trait1 + Trait2 + 'a` + if allow_plus && self.check_plus() { + self.parse_remaining_bounds(Vec::new(), path, lo, true)? + } else { + TyKind::Path(None, path) + } + } + } else { + let msg = format!("expected type, found {}", self.this_token_descr()); + return Err(self.fatal(&msg)); + }; + + let span = lo.to(self.prev_span); + let ty = Ty { node, span, id: ast::DUMMY_NODE_ID }; + + // Try to recover from use of `+` with incorrect priority. + self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty); + self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?; + let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?; + + Ok(P(ty)) + } + + fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path, + lo: Span, parse_plus: bool) -> PResult<'a, TyKind> { + let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span)); + let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)]; + if parse_plus { + self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded + bounds.append(&mut self.parse_generic_bounds(None)?); + } + Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None)) + } + + fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) { + if !allow_plus && impl_dyn_multi { + let sum_with_parens = format!("({})", pprust::ty_to_string(&ty)); + self.struct_span_err(ty.span, "ambiguous `+` in a type") + .span_suggestion( + ty.span, + "use parentheses to disambiguate", + sum_with_parens, + Applicability::MachineApplicable + ).emit(); + } + } + + fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> { + // Do not add `+` to expected tokens. + if !allow_plus || !self.token.is_like_plus() { + return Ok(()) + } + + self.bump(); // `+` + let bounds = self.parse_generic_bounds(None)?; + let sum_span = ty.span.to(self.prev_span); + + let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178, + "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty)); + + match ty.node { + TyKind::Rptr(ref lifetime, ref mut_ty) => { + let sum_with_parens = pprust::to_string(|s| { + use crate::print::pprust::PrintState; + + s.s.word("&")?; + s.print_opt_lifetime(lifetime)?; + s.print_mutability(mut_ty.mutbl)?; + s.popen()?; + s.print_type(&mut_ty.ty)?; + s.print_type_bounds(" +", &bounds)?; + s.pclose() + }); + err.span_suggestion( + sum_span, + "try adding parentheses", + sum_with_parens, + Applicability::MachineApplicable + ); + } + TyKind::Ptr(..) | TyKind::BareFn(..) => { + err.span_label(sum_span, "perhaps you forgot parentheses?"); + } + _ => { + err.span_label(sum_span, "expected a path"); + }, + } + err.emit(); + Ok(()) + } + + // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`. + fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool) + -> PResult<'a, T> { + // Do not add `::` to expected tokens. + if !allow_recovery || self.token != token::ModSep { + return Ok(base); + } + let ty = match base.to_ty() { + Some(ty) => ty, + None => return Ok(base), + }; + + self.bump(); // `::` + let mut segments = Vec::new(); + self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?; + + let span = ty.span.to(self.prev_span); + let path_span = span.to(span); // use an empty path since `position` == 0 + let recovered = base.to_recovered( + Some(QSelf { ty, path_span, position: 0 }), + ast::Path { segments, span }, + ); + + self.diagnostic() + .struct_span_err(span, "missing angle brackets in associated item path") + .span_suggestion( // this is a best-effort recovery + span, "try", recovered.to_string(), Applicability::MaybeIncorrect + ).emit(); + + Ok(recovered) + } + + fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> { + let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None }; + let mutbl = self.parse_mutability(); + let ty = self.parse_ty_no_plus()?; + return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl })); + } + + fn parse_ptr(&mut self) -> PResult<'a, MutTy> { + let mutbl = if self.eat_keyword(keywords::Mut) { + Mutability::Mutable + } else if self.eat_keyword(keywords::Const) { + Mutability::Immutable + } else { + let span = self.prev_span; + let msg = "expected mut or const in raw pointer type"; + self.struct_span_err(span, msg) + .span_label(span, msg) + .help("use `*mut T` or `*const T` as appropriate") + .emit(); + Mutability::Immutable + }; + let t = self.parse_ty_no_plus()?; + Ok(MutTy { ty: t, mutbl: mutbl }) + } + + fn is_named_argument(&mut self) -> bool { + let offset = match self.token { + token::Interpolated(ref nt) => match **nt { + token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon), + _ => 0, + } + token::BinOp(token::And) | token::AndAnd => 1, + _ if self.token.is_keyword(keywords::Mut) => 1, + _ => 0, + }; + + self.look_ahead(offset, |t| t.is_ident()) && + self.look_ahead(offset + 1, |t| t == &token::Colon) + } + + /// Skips unexpected attributes and doc comments in this position and emits an appropriate + /// error. + fn eat_incorrect_doc_comment(&mut self, applied_to: &str) { + if let token::DocComment(_) = self.token { + let mut err = self.diagnostic().struct_span_err( + self.span, + &format!("documentation comments cannot be applied to {}", applied_to), + ); + err.span_label(self.span, "doc comments are not allowed here"); + err.emit(); + self.bump(); + } else if self.token == token::Pound && self.look_ahead(1, |t| { + *t == token::OpenDelim(token::Bracket) + }) { + let lo = self.span; + // Skip every token until next possible arg. + while self.token != token::CloseDelim(token::Bracket) { + self.bump(); + } + let sp = lo.to(self.span); + self.bump(); + let mut err = self.diagnostic().struct_span_err( + sp, + &format!("attributes cannot be applied to {}", applied_to), + ); + err.span_label(sp, "attributes are not allowed here"); + err.emit(); + } + } + + /// This version of parse arg doesn't necessarily require identifier names. + fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool) -> PResult<'a, Arg> { + maybe_whole!(self, NtArg, |x| x); + + if let Ok(Some(_)) = self.parse_self_arg() { + let mut err = self.struct_span_err(self.prev_span, + "unexpected `self` argument in function"); + err.span_label(self.prev_span, + "`self` is only valid as the first argument of an associated function"); + return Err(err); + } + + let (pat, ty) = if require_name || self.is_named_argument() { + debug!("parse_arg_general parse_pat (require_name:{})", + require_name); + self.eat_incorrect_doc_comment("method arguments"); + let pat = self.parse_pat(Some("argument name"))?; + + if let Err(mut err) = self.expect(&token::Colon) { + // If we find a pattern followed by an identifier, it could be an (incorrect) + // C-style parameter declaration. + if self.check_ident() && self.look_ahead(1, |t| { + *t == token::Comma || *t == token::CloseDelim(token::Paren) + }) { + let ident = self.parse_ident().unwrap(); + let span = pat.span.with_hi(ident.span.hi()); + + err.span_suggestion( + span, + "declare the type after the parameter binding", + String::from("<identifier>: <type>"), + Applicability::HasPlaceholders, + ); + } else if require_name && is_trait_item { + if let PatKind::Ident(_, ident, _) = pat.node { + err.span_suggestion( + pat.span, + "explicitly ignore parameter", + format!("_: {}", ident), + Applicability::MachineApplicable, + ); + } + + err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)"); + } + + return Err(err); + } + + self.eat_incorrect_doc_comment("a method argument's type"); + (pat, self.parse_ty()?) + } else { + debug!("parse_arg_general ident_to_pat"); + let parser_snapshot_before_ty = self.clone(); + self.eat_incorrect_doc_comment("a method argument's type"); + let mut ty = self.parse_ty(); + if ty.is_ok() && self.token != token::Comma && + self.token != token::CloseDelim(token::Paren) { + // This wasn't actually a type, but a pattern looking like a type, + // so we are going to rollback and re-parse for recovery. + ty = self.unexpected(); + } + match ty { + Ok(ty) => { + let ident = Ident::new(keywords::Invalid.name(), self.prev_span); + let pat = P(Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident( + BindingMode::ByValue(Mutability::Immutable), ident, None), + span: ty.span, + }); + (pat, ty) + } + Err(mut err) => { + // Recover from attempting to parse the argument as a type without pattern. + err.cancel(); + mem::replace(self, parser_snapshot_before_ty); + let pat = self.parse_pat(Some("argument name"))?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + + let mut err = self.diagnostic().struct_span_err_with_code( + pat.span, + "patterns aren't allowed in methods without bodies", + DiagnosticId::Error("E0642".into()), + ); + err.span_suggestion_short( + pat.span, + "give this argument a name or use an underscore to ignore it", + "_".to_owned(), + Applicability::MachineApplicable, + ); + err.emit(); + + // Pretend the pattern is `_`, to avoid duplicate errors from AST validation. + let pat = P(Pat { + node: PatKind::Wild, + span: pat.span, + id: ast::DUMMY_NODE_ID + }); + (pat, ty) + } + } + }; + + Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID }) + } + + /// Parses a single function argument. + crate fn parse_arg(&mut self) -> PResult<'a, Arg> { + self.parse_arg_general(true, false) + } + + /// Parses an argument in a lambda header (e.g., `|arg, arg|`). + fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> { + let pat = self.parse_pat(Some("argument name"))?; + let t = if self.eat(&token::Colon) { + self.parse_ty()? + } else { + P(Ty { + id: ast::DUMMY_NODE_ID, + node: TyKind::Infer, + span: self.prev_span, + }) + }; + Ok(Arg { + ty: t, + pat, + id: ast::DUMMY_NODE_ID + }) + } + + fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> { + if self.eat(&token::Semi) { + Ok(Some(self.parse_expr()?)) + } else { + Ok(None) + } + } + + /// Matches `token_lit = LIT_INTEGER | ...`. + fn parse_lit_token(&mut self) -> PResult<'a, LitKind> { + let out = match self.token { + token::Interpolated(ref nt) => match **nt { + token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node { + ExprKind::Lit(ref lit) => { lit.node.clone() } + _ => { return self.unexpected_last(&self.token); } + }, + _ => { return self.unexpected_last(&self.token); } + }, + token::Literal(lit, suf) => { + let diag = Some((self.span, &self.sess.span_diagnostic)); + let (suffix_illegal, result) = parse::lit_token(lit, suf, diag); + + if suffix_illegal { + let sp = self.span; + self.expect_no_suffix(sp, lit.literal_name(), suf) + } + + result.unwrap() + } + token::Dot if self.look_ahead(1, |t| match t { + token::Literal(parse::token::Lit::Integer(_) , _) => true, + _ => false, + }) => { // recover from `let x = .4;` + let lo = self.span; + self.bump(); + if let token::Literal( + parse::token::Lit::Integer(val), + suffix, + ) = self.token { + let suffix = suffix.and_then(|s| { + let s = s.as_str().get(); + if ["f32", "f64"].contains(&s) { + Some(s) + } else { + None + } + }).unwrap_or(""); + self.bump(); + let sp = lo.to(self.prev_span); + let mut err = self.diagnostic() + .struct_span_err(sp, "float literals must have an integer part"); + err.span_suggestion( + sp, + "must have an integer part", + format!("0.{}{}", val, suffix), + Applicability::MachineApplicable, + ); + err.emit(); + return Ok(match suffix { + "f32" => ast::LitKind::Float(val, ast::FloatTy::F32), + "f64" => ast::LitKind::Float(val, ast::FloatTy::F64), + _ => ast::LitKind::FloatUnsuffixed(val), + }); + } else { + unreachable!(); + }; + } + _ => { return self.unexpected_last(&self.token); } + }; + + self.bump(); + Ok(out) + } + + /// Matches `lit = true | false | token_lit`. + crate fn parse_lit(&mut self) -> PResult<'a, Lit> { + let lo = self.span; + let lit = if self.eat_keyword(keywords::True) { + LitKind::Bool(true) + } else if self.eat_keyword(keywords::False) { + LitKind::Bool(false) + } else { + let lit = self.parse_lit_token()?; + lit + }; + Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) }) + } + + /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). + crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> { + maybe_whole_expr!(self); + + let minus_lo = self.span; + let minus_present = self.eat(&token::BinOp(token::Minus)); + let lo = self.span; + let literal = self.parse_lit()?; + let hi = self.prev_span; + let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new()); + + if minus_present { + let minus_hi = self.prev_span; + let unary = self.mk_unary(UnOp::Neg, expr); + Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new())) + } else { + Ok(expr) + } + } + + fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> { + match self.token { + token::Ident(ident, _) if self.token.is_path_segment_keyword() => { + let span = self.span; + self.bump(); + Ok(Ident::new(ident.name, span)) + } + _ => self.parse_ident(), + } + } + + fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> { + match self.token { + token::Ident(ident, false) if ident.name == keywords::Underscore.name() => { + let span = self.span; + self.bump(); + Ok(Ident::new(ident.name, span)) + } + _ => self.parse_ident(), + } + } + + /// Parses a qualified path. + /// Assumes that the leading `<` has been parsed already. + /// + /// `qualified_path = <type [as trait_ref]>::path` + /// + /// # Examples + /// `<T>::default` + /// `<T as U>::a` + /// `<T as U>::F::a<S>` (without disambiguator) + /// `<T as U>::F::a::<S>` (with disambiguator) + fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> { + let lo = self.prev_span; + let ty = self.parse_ty()?; + + // `path` will contain the prefix of the path up to the `>`, + // if any (e.g., `U` in the `<T as U>::*` examples + // above). `path_span` has the span of that path, or an empty + // span in the case of something like `<T>::Bar`. + let (mut path, path_span); + if self.eat_keyword(keywords::As) { + let path_lo = self.span; + path = self.parse_path(PathStyle::Type)?; + path_span = path_lo.to(self.prev_span); + } else { + path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }; + path_span = self.span.to(self.span); + } + + // See doc comment for `unmatched_angle_bracket_count`. + self.expect(&token::Gt)?; + if self.unmatched_angle_bracket_count > 0 { + self.unmatched_angle_bracket_count -= 1; + debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count); + } + + self.expect(&token::ModSep)?; + + let qself = QSelf { ty, path_span, position: path.segments.len() }; + self.parse_path_segments(&mut path.segments, style, true)?; + + Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) })) + } + + /// Parses simple paths. + /// + /// `path = [::] segment+` + /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]` + /// + /// # Examples + /// `a::b::C<D>` (without disambiguator) + /// `a::b::C::<D>` (with disambiguator) + /// `Fn(Args)` (without disambiguator) + /// `Fn::(Args)` (with disambiguator) + pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> { + self.parse_path_common(style, true) + } + + crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool) + -> PResult<'a, ast::Path> { + maybe_whole!(self, NtPath, |path| { + if style == PathStyle::Mod && + path.segments.iter().any(|segment| segment.args.is_some()) { + self.diagnostic().span_err(path.span, "unexpected generic arguments in path"); + } + path + }); + + let lo = self.meta_var_span.unwrap_or(self.span); + let mut segments = Vec::new(); + let mod_sep_ctxt = self.span.ctxt(); + if self.eat(&token::ModSep) { + segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))); + } + self.parse_path_segments(&mut segments, style, enable_warning)?; + + Ok(ast::Path { segments, span: lo.to(self.prev_span) }) + } + + /// Like `parse_path`, but also supports parsing `Word` meta items into paths for + /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]` + /// attributes. + pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> { + let meta_ident = match self.token { + token::Interpolated(ref nt) => match **nt { + token::NtMeta(ref meta) => match meta.node { + ast::MetaItemKind::Word => Some(meta.ident.clone()), + _ => None, + }, + _ => None, + }, + _ => None, + }; + if let Some(path) = meta_ident { + self.bump(); + return Ok(path); + } + self.parse_path(style) + } + + fn parse_path_segments(&mut self, + segments: &mut Vec<PathSegment>, + style: PathStyle, + enable_warning: bool) + -> PResult<'a, ()> { + loop { + let segment = self.parse_path_segment(style, enable_warning)?; + if style == PathStyle::Expr { + // In order to check for trailing angle brackets, we must have finished + // recursing (`parse_path_segment` can indirectly call this function), + // that is, the next token must be the highlighted part of the below example: + // + // `Foo::<Bar as Baz<T>>::Qux` + // ^ here + // + // As opposed to the below highlight (if we had only finished the first + // recursion): + // + // `Foo::<Bar as Baz<T>>::Qux` + // ^ here + // + // `PathStyle::Expr` is only provided at the root invocation and never in + // `parse_path_segment` to recurse and therefore can be checked to maintain + // this invariant. + self.check_trailing_angle_brackets(&segment, token::ModSep); + } + segments.push(segment); + + if self.is_import_coupler() || !self.eat(&token::ModSep) { + return Ok(()); + } + } + } + + fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool) + -> PResult<'a, PathSegment> { + let ident = self.parse_path_segment_ident()?; + + let is_args_start = |token: &token::Token| match *token { + token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true, + _ => false, + }; + let check_args_start = |this: &mut Self| { + this.expected_tokens.extend_from_slice( + &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))] + ); + is_args_start(&this.token) + }; + + Ok(if style == PathStyle::Type && check_args_start(self) || + style != PathStyle::Mod && self.check(&token::ModSep) + && self.look_ahead(1, |t| is_args_start(t)) { + // Generic arguments are found - `<`, `(`, `::<` or `::(`. + if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning { + self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator") + .span_label(self.prev_span, "try removing `::`").emit(); + } + let lo = self.span; + + // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If + // it isn't, then we reset the unmatched angle bracket count as we're about to start + // parsing a new path. + if style == PathStyle::Expr { + self.unmatched_angle_bracket_count = 0; + self.max_angle_bracket_count = 0; + } + + let args = if self.eat_lt() { + // `<'a, T, A = U>` + let (args, bindings) = + self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?; + self.expect_gt()?; + let span = lo.to(self.prev_span); + AngleBracketedArgs { args, bindings, span }.into() + } else { + // `(T, U) -> R` + self.bump(); // `(` + let (inputs, recovered) = self.parse_seq_to_before_tokens( + &[&token::CloseDelim(token::Paren)], + SeqSep::trailing_allowed(token::Comma), + TokenExpectType::Expect, + |p| p.parse_ty())?; + if !recovered { + self.bump(); // `)` + } + let span = lo.to(self.prev_span); + let output = if self.eat(&token::RArrow) { + Some(self.parse_ty_common(false, false)?) + } else { + None + }; + ParenthesizedArgs { inputs, output, span }.into() + }; + + PathSegment { ident, args, id: ast::DUMMY_NODE_ID } + } else { + // Generic arguments are not found. + PathSegment::from_ident(ident) + }) + } + + crate fn check_lifetime(&mut self) -> bool { + self.expected_tokens.push(TokenType::Lifetime); + self.token.is_lifetime() + } + + /// Parses a single lifetime `'a` or panics. + crate fn expect_lifetime(&mut self) -> Lifetime { + if let Some(ident) = self.token.lifetime() { + let span = self.span; + self.bump(); + Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID } + } else { + self.span_bug(self.span, "not a lifetime") + } + } + + fn eat_label(&mut self) -> Option<Label> { + if let Some(ident) = self.token.lifetime() { + let span = self.span; + self.bump(); + Some(Label { ident: Ident::new(ident.name, span) }) + } else { + None + } + } + + /// Parses mutability (`mut` or nothing). + fn parse_mutability(&mut self) -> Mutability { + if self.eat_keyword(keywords::Mut) { + Mutability::Mutable + } else { + Mutability::Immutable + } + } + + fn parse_field_name(&mut self) -> PResult<'a, Ident> { + if let token::Literal(token::Integer(name), None) = self.token { + self.bump(); + Ok(Ident::new(name, self.prev_span)) + } else { + self.parse_ident_common(false) + } + } + + /// Parse ident (COLON expr)? + fn parse_field(&mut self) -> PResult<'a, Field> { + let attrs = self.parse_outer_attributes()?; + let lo = self.span; + + // Check if a colon exists one ahead. This means we're parsing a fieldname. + let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| { + t == &token::Colon || t == &token::Eq + }) { + let fieldname = self.parse_field_name()?; + + // Check for an equals token. This means the source incorrectly attempts to + // initialize a field with an eq rather than a colon. + if self.token == token::Eq { + self.diagnostic() + .struct_span_err(self.span, "expected `:`, found `=`") + .span_suggestion( + fieldname.span.shrink_to_hi().to(self.span), + "replace equals symbol with a colon", + ":".to_string(), + Applicability::MachineApplicable, + ) + .emit(); + } + self.bump(); // `:` + (fieldname, self.parse_expr()?, false) + } else { + let fieldname = self.parse_ident_common(false)?; + + // Mimic `x: x` for the `x` field shorthand. + let path = ast::Path::from_ident(fieldname); + let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new()); + (fieldname, expr, true) + }; + Ok(ast::Field { + ident: fieldname, + span: lo.to(expr.span), + expr, + is_shorthand, + attrs: attrs.into(), + }) + } + + fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> { + P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID }) + } + + fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind { + ExprKind::Unary(unop, expr) + } + + fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind { + ExprKind::Binary(binop, lhs, rhs) + } + + fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind { + ExprKind::Call(f, args) + } + + fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind { + ExprKind::Index(expr, idx) + } + + fn mk_range(&mut self, + start: Option<P<Expr>>, + end: Option<P<Expr>>, + limits: RangeLimits) + -> PResult<'a, ast::ExprKind> { + if end.is_none() && limits == RangeLimits::Closed { + Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd)) + } else { + Ok(ExprKind::Range(start, end, limits)) + } + } + + fn mk_assign_op(&mut self, binop: ast::BinOp, + lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind { + ExprKind::AssignOp(binop, lhs, rhs) + } + + pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> { + P(Expr { + id: ast::DUMMY_NODE_ID, + node: ExprKind::Mac(source_map::Spanned {node: m, span: span}), + span, + attrs, + }) + } + + fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> { + let delim = match self.token { + token::OpenDelim(delim) => delim, + _ => { + let msg = "expected open delimiter"; + let mut err = self.fatal(msg); + err.span_label(self.span, msg); + return Err(err) + } + }; + let tts = match self.parse_token_tree() { + TokenTree::Delimited(_, _, tts) => tts, + _ => unreachable!(), + }; + let delim = match delim { + token::Paren => MacDelimiter::Parenthesis, + token::Bracket => MacDelimiter::Bracket, + token::Brace => MacDelimiter::Brace, + token::NoDelim => self.bug("unexpected no delimiter"), + }; + Ok((delim, tts.into())) + } + + /// At the bottom (top?) of the precedence hierarchy, + /// Parses things like parenthesized exprs, macros, `return`, etc. + /// + /// N.B., this does not parse outer attributes, and is private because it only works + /// correctly if called from `parse_dot_or_call_expr()`. + fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> { + maybe_whole_expr!(self); + + // Outer attributes are already parsed and will be + // added to the return value after the fact. + // + // Therefore, prevent sub-parser from parsing + // attributes by giving them a empty "already parsed" list. + let mut attrs = ThinVec::new(); + + let lo = self.span; + let mut hi = self.span; + + let ex: ExprKind; + + // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr(). + match self.token { + token::OpenDelim(token::Paren) => { + self.bump(); + + attrs.extend(self.parse_inner_attributes()?); + + // (e) is parenthesized e + // (e,) is a tuple with only one field, e + let mut es = vec![]; + let mut trailing_comma = false; + let mut recovered = false; + while self.token != token::CloseDelim(token::Paren) { + es.push(self.parse_expr()?); + recovered = self.expect_one_of( + &[], + &[token::Comma, token::CloseDelim(token::Paren)], + )?; + if self.eat(&token::Comma) { + trailing_comma = true; + } else { + trailing_comma = false; + break; + } + } + if !recovered { + self.bump(); + } + + hi = self.prev_span; + ex = if es.len() == 1 && !trailing_comma { + ExprKind::Paren(es.into_iter().nth(0).unwrap()) + } else { + ExprKind::Tup(es) + }; + } + token::OpenDelim(token::Brace) => { + return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs); + } + token::BinOp(token::Or) | token::OrOr => { + return self.parse_lambda_expr(attrs); + } + token::OpenDelim(token::Bracket) => { + self.bump(); + + attrs.extend(self.parse_inner_attributes()?); + + if self.eat(&token::CloseDelim(token::Bracket)) { + // Empty vector. + ex = ExprKind::Array(Vec::new()); + } else { + // Nonempty vector. + let first_expr = self.parse_expr()?; + if self.eat(&token::Semi) { + // Repeating array syntax: [ 0; 512 ] + let count = AnonConst { + id: ast::DUMMY_NODE_ID, + value: self.parse_expr()?, + }; + self.expect(&token::CloseDelim(token::Bracket))?; + ex = ExprKind::Repeat(first_expr, count); + } else if self.eat(&token::Comma) { + // Vector with two or more elements. + let remaining_exprs = self.parse_seq_to_end( + &token::CloseDelim(token::Bracket), + SeqSep::trailing_allowed(token::Comma), + |p| Ok(p.parse_expr()?) + )?; + let mut exprs = vec![first_expr]; + exprs.extend(remaining_exprs); + ex = ExprKind::Array(exprs); + } else { + // Vector with one element. + self.expect(&token::CloseDelim(token::Bracket))?; + ex = ExprKind::Array(vec![first_expr]); + } + } + hi = self.prev_span; + } + _ => { + if self.eat_lt() { + let (qself, path) = self.parse_qpath(PathStyle::Expr)?; + hi = path.span; + return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs)); + } + if self.span.rust_2018() && self.check_keyword(keywords::Async) + { + if self.is_async_block() { // check for `async {` and `async move {` + return self.parse_async_block(attrs); + } else { + return self.parse_lambda_expr(attrs); + } + } + if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) { + return self.parse_lambda_expr(attrs); + } + if self.eat_keyword(keywords::If) { + return self.parse_if_expr(attrs); + } + if self.eat_keyword(keywords::For) { + let lo = self.prev_span; + return self.parse_for_expr(None, lo, attrs); + } + if self.eat_keyword(keywords::While) { + let lo = self.prev_span; + return self.parse_while_expr(None, lo, attrs); + } + if let Some(label) = self.eat_label() { + let lo = label.ident.span; + self.expect(&token::Colon)?; + if self.eat_keyword(keywords::While) { + return self.parse_while_expr(Some(label), lo, attrs) + } + if self.eat_keyword(keywords::For) { + return self.parse_for_expr(Some(label), lo, attrs) + } + if self.eat_keyword(keywords::Loop) { + return self.parse_loop_expr(Some(label), lo, attrs) + } + if self.token == token::OpenDelim(token::Brace) { + return self.parse_block_expr(Some(label), + lo, + BlockCheckMode::Default, + attrs); + } + let msg = "expected `while`, `for`, `loop` or `{` after a label"; + let mut err = self.fatal(msg); + err.span_label(self.span, msg); + return Err(err); + } + if self.eat_keyword(keywords::Loop) { + let lo = self.prev_span; + return self.parse_loop_expr(None, lo, attrs); + } + if self.eat_keyword(keywords::Continue) { + let label = self.eat_label(); + let ex = ExprKind::Continue(label); + let hi = self.prev_span; + return Ok(self.mk_expr(lo.to(hi), ex, attrs)); + } + if self.eat_keyword(keywords::Match) { + let match_sp = self.prev_span; + return self.parse_match_expr(attrs).map_err(|mut err| { + err.span_label(match_sp, "while parsing this match expression"); + err + }); + } + if self.eat_keyword(keywords::Unsafe) { + return self.parse_block_expr( + None, + lo, + BlockCheckMode::Unsafe(ast::UserProvided), + attrs); + } + if self.is_do_catch_block() { + let mut db = self.fatal("found removed `do catch` syntax"); + db.help("Following RFC #2388, the new non-placeholder syntax is `try`"); + return Err(db); + } + if self.is_try_block() { + let lo = self.span; + assert!(self.eat_keyword(keywords::Try)); + return self.parse_try_block(lo, attrs); + } + if self.eat_keyword(keywords::Return) { + if self.token.can_begin_expr() { + let e = self.parse_expr()?; + hi = e.span; + ex = ExprKind::Ret(Some(e)); + } else { + ex = ExprKind::Ret(None); + } + } else if self.eat_keyword(keywords::Break) { + let label = self.eat_label(); + let e = if self.token.can_begin_expr() + && !(self.token == token::OpenDelim(token::Brace) + && self.restrictions.contains( + Restrictions::NO_STRUCT_LITERAL)) { + Some(self.parse_expr()?) + } else { + None + }; + ex = ExprKind::Break(label, e); + hi = self.prev_span; + } else if self.eat_keyword(keywords::Yield) { + if self.token.can_begin_expr() { + let e = self.parse_expr()?; + hi = e.span; + ex = ExprKind::Yield(Some(e)); + } else { + ex = ExprKind::Yield(None); + } + } else if self.token.is_keyword(keywords::Let) { + // Catch this syntax error here, instead of in `parse_ident`, so + // that we can explicitly mention that let is not to be used as an expression + let mut db = self.fatal("expected expression, found statement (`let`)"); + db.span_label(self.span, "expected expression"); + db.note("variable declaration using `let` is a statement"); + return Err(db); + } else if self.token.is_path_start() { + let pth = self.parse_path(PathStyle::Expr)?; + + // `!`, as an operator, is prefix, so we know this isn't that + if self.eat(&token::Not) { + // MACRO INVOCATION expression + let (delim, tts) = self.expect_delimited_token_tree()?; + let hi = self.prev_span; + let node = Mac_ { path: pth, tts, delim }; + return Ok(self.mk_mac_expr(lo.to(hi), node, attrs)) + } + if self.check(&token::OpenDelim(token::Brace)) { + // This is a struct literal, unless we're prohibited + // from parsing struct literals here. + let prohibited = self.restrictions.contains( + Restrictions::NO_STRUCT_LITERAL + ); + if !prohibited { + return self.parse_struct_expr(lo, pth, attrs); + } + } + + hi = pth.span; + ex = ExprKind::Path(None, pth); + } else { + if !self.unclosed_delims.is_empty() && self.check(&token::Semi) { + // Don't complain about bare semicolons after unclosed braces + // recovery in order to keep the error count down. Fixing the + // delimiters will possibly also fix the bare semicolon found in + // expression context. For example, silence the following error: + // ``` + // error: expected expression, found `;` + // --> file.rs:2:13 + // | + // 2 | foo(bar(; + // | ^ expected expression + // ``` + self.bump(); + return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new())); + } + match self.parse_literal_maybe_minus() { + Ok(expr) => { + hi = expr.span; + ex = expr.node.clone(); + } + Err(mut err) => { + self.cancel(&mut err); + let msg = format!("expected expression, found {}", + self.this_token_descr()); + let mut err = self.fatal(&msg); + err.span_label(self.span, "expected expression"); + return Err(err); + } + } + } + } + } + + let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs }; + let expr = self.maybe_recover_from_bad_qpath(expr, true)?; + + return Ok(P(expr)); + } + + fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + let struct_sp = lo.to(self.prev_span); + self.bump(); + let mut fields = Vec::new(); + let mut base = None; + + attrs.extend(self.parse_inner_attributes()?); + + while self.token != token::CloseDelim(token::Brace) { + if self.eat(&token::DotDot) { + let exp_span = self.prev_span; + match self.parse_expr() { + Ok(e) => { + base = Some(e); + } + Err(mut e) => { + e.emit(); + self.recover_stmt(); + } + } + if self.token == token::Comma { + let mut err = self.sess.span_diagnostic.mut_span_err( + exp_span.to(self.prev_span), + "cannot use a comma after the base struct", + ); + err.span_suggestion_short( + self.span, + "remove this comma", + String::new(), + Applicability::MachineApplicable + ); + err.note("the base struct must always be the last field"); + err.emit(); + self.recover_stmt(); + } + break; + } + + let mut recovery_field = None; + if let token::Ident(ident, _) = self.token { + if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) { + // Use in case of error after field-looking code: `S { foo: () with a }` + let mut ident = ident.clone(); + ident.span = self.span; + recovery_field = Some(ast::Field { + ident, + span: self.span, + expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()), + is_shorthand: false, + attrs: ThinVec::new(), + }); + } + } + let mut parsed_field = None; + match self.parse_field() { + Ok(f) => parsed_field = Some(f), + Err(mut e) => { + e.span_label(struct_sp, "while parsing this struct"); + e.emit(); + + // If the next token is a comma, then try to parse + // what comes next as additional fields, rather than + // bailing out until next `}`. + if self.token != token::Comma { + self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore); + if self.token != token::Comma { + break; + } + } + } + } + + match self.expect_one_of(&[token::Comma], + &[token::CloseDelim(token::Brace)]) { + Ok(_) => if let Some(f) = parsed_field.or(recovery_field) { + // only include the field if there's no parse error for the field name + fields.push(f); + } + Err(mut e) => { + if let Some(f) = recovery_field { + fields.push(f); + } + e.span_label(struct_sp, "while parsing this struct"); + e.emit(); + self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore); + self.eat(&token::Comma); + } + } + } + + let span = lo.to(self.span); + self.expect(&token::CloseDelim(token::Brace))?; + return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs)); + } + + fn parse_or_use_outer_attributes(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, ThinVec<Attribute>> { + if let Some(attrs) = already_parsed_attrs { + Ok(attrs) + } else { + self.parse_outer_attributes().map(|a| a.into()) + } + } + + /// Parses a block or unsafe block. + fn parse_block_expr(&mut self, opt_label: Option<Label>, + lo: Span, blk_mode: BlockCheckMode, + outer_attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + self.expect(&token::OpenDelim(token::Brace))?; + + let mut attrs = outer_attrs; + attrs.extend(self.parse_inner_attributes()?); + + let blk = self.parse_block_tail(lo, blk_mode)?; + return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs)); + } + + /// Parses `a.b` or `a(13)` or `a[4]` or just `a`. + fn parse_dot_or_call_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; + + let b = self.parse_bottom_expr(); + let (span, b) = self.interpolated_or_expr_span(b)?; + self.parse_dot_or_call_expr_with(b, span, attrs) + } + + fn parse_dot_or_call_expr_with(&mut self, + e0: P<Expr>, + lo: Span, + mut attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + // Stitch the list of outer attributes onto the return value. + // A little bit ugly, but the best way given the current code + // structure + self.parse_dot_or_call_expr_with_(e0, lo) + .map(|expr| + expr.map(|mut expr| { + attrs.extend::<Vec<_>>(expr.attrs.into()); + expr.attrs = attrs; + match expr.node { + ExprKind::If(..) | ExprKind::IfLet(..) => { + if !expr.attrs.is_empty() { + // Just point to the first attribute in there... + let span = expr.attrs[0].span; + + self.span_err(span, + "attributes are not yet allowed on `if` \ + expressions"); + } + } + _ => {} + } + expr + }) + ) + } + + // Assuming we have just parsed `.`, continue parsing into an expression. + fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> { + let segment = self.parse_path_segment(PathStyle::Expr, true)?; + self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren)); + + Ok(match self.token { + token::OpenDelim(token::Paren) => { + // Method call `expr.f()` + let mut args = self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| Ok(p.parse_expr()?) + )?; + args.insert(0, self_arg); + + let span = lo.to(self.prev_span); + self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new()) + } + _ => { + // Field access `expr.f` + if let Some(args) = segment.args { + self.span_err(args.span(), + "field expressions may not have generic arguments"); + } + + let span = lo.to(self.prev_span); + self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new()) + } + }) + } + + /// This function checks if there are trailing angle brackets and produces + /// a diagnostic to suggest removing them. + /// + /// ```ignore (diagnostic) + /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>(); + /// ^^ help: remove extra angle brackets + /// ``` + fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) { + // This function is intended to be invoked after parsing a path segment where there are two + // cases: + // + // 1. A specific token is expected after the path segment. + // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call), + // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path). + // 2. No specific token is expected after the path segment. + // eg. `x.foo` (field access) + // + // This function is called after parsing `.foo` and before parsing the token `end` (if + // present). This includes any angle bracket arguments, such as `.foo::<u32>` or + // `Foo::<Bar>`. + + // We only care about trailing angle brackets if we previously parsed angle bracket + // arguments. This helps stop us incorrectly suggesting that extra angle brackets be + // removed in this case: + // + // `x.foo >> (3)` (where `x.foo` is a `u32` for example) + // + // This case is particularly tricky as we won't notice it just looking at the tokens - + // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will + // have already been parsed): + // + // `x.foo::<u32>>>(3)` + let parsed_angle_bracket_args = segment.args + .as_ref() + .map(|args| args.is_angle_bracketed()) + .unwrap_or(false); + + debug!( + "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}", + parsed_angle_bracket_args, + ); + if !parsed_angle_bracket_args { + return; + } + + // Keep the span at the start so we can highlight the sequence of `>` characters to be + // removed. + let lo = self.span; + + // We need to look-ahead to see if we have `>` characters without moving the cursor forward + // (since we might have the field access case and the characters we're eating are + // actual operators and not trailing characters - ie `x.foo >> 3`). + let mut position = 0; + + // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how + // many of each (so we can correctly pluralize our error messages) and continue to + // advance. + let mut number_of_shr = 0; + let mut number_of_gt = 0; + while self.look_ahead(position, |t| { + trace!("check_trailing_angle_brackets: t={:?}", t); + if *t == token::BinOp(token::BinOpToken::Shr) { + number_of_shr += 1; + true + } else if *t == token::Gt { + number_of_gt += 1; + true + } else { + false + } + }) { + position += 1; + } + + // If we didn't find any trailing `>` characters, then we have nothing to error about. + debug!( + "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}", + number_of_gt, number_of_shr, + ); + if number_of_gt < 1 && number_of_shr < 1 { + return; + } + + // Finally, double check that we have our end token as otherwise this is the + // second case. + if self.look_ahead(position, |t| { + trace!("check_trailing_angle_brackets: t={:?}", t); + *t == end + }) { + // Eat from where we started until the end token so that parsing can continue + // as if we didn't have those extra angle brackets. + self.eat_to_tokens(&[&end]); + let span = lo.until(self.span); + + let plural = number_of_gt > 1 || number_of_shr >= 1; + self.diagnostic() + .struct_span_err( + span, + &format!("unmatched angle bracket{}", if plural { "s" } else { "" }), + ) + .span_suggestion( + span, + &format!("remove extra angle bracket{}", if plural { "s" } else { "" }), + String::new(), + Applicability::MachineApplicable, + ) + .emit(); + } + } + + fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> { + let mut e = e0; + let mut hi; + loop { + // expr? + while self.eat(&token::Question) { + let hi = self.prev_span; + e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new()); + } + + // expr.f + if self.eat(&token::Dot) { + match self.token { + token::Ident(..) => { + e = self.parse_dot_suffix(e, lo)?; + } + token::Literal(token::Integer(name), _) => { + let span = self.span; + self.bump(); + let field = ExprKind::Field(e, Ident::new(name, span)); + e = self.mk_expr(lo.to(span), field, ThinVec::new()); + } + token::Literal(token::Float(n), _suf) => { + self.bump(); + let fstr = n.as_str(); + let mut err = self.diagnostic() + .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n)); + err.span_label(self.prev_span, "unexpected token"); + if fstr.chars().all(|x| "0123456789.".contains(x)) { + let float = match fstr.parse::<f64>().ok() { + Some(f) => f, + None => continue, + }; + let sugg = pprust::to_string(|s| { + use crate::print::pprust::PrintState; + s.popen()?; + s.print_expr(&e)?; + s.s.word( ".")?; + s.print_usize(float.trunc() as usize)?; + s.pclose()?; + s.s.word(".")?; + s.s.word(fstr.splitn(2, ".").last().unwrap().to_string()) + }); + err.span_suggestion( + lo.to(self.prev_span), + "try parenthesizing the first index", + sugg, + Applicability::MachineApplicable + ); + } + return Err(err); + + } + _ => { + // FIXME Could factor this out into non_fatal_unexpected or something. + let actual = self.this_token_to_string(); + self.span_err(self.span, &format!("unexpected token: `{}`", actual)); + } + } + continue; + } + if self.expr_is_complete(&e) { break; } + match self.token { + // expr(...) + token::OpenDelim(token::Paren) => { + let es = self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| Ok(p.parse_expr()?) + )?; + hi = self.prev_span; + + let nd = self.mk_call(e, es); + e = self.mk_expr(lo.to(hi), nd, ThinVec::new()); + } + + // expr[...] + // Could be either an index expression or a slicing expression. + token::OpenDelim(token::Bracket) => { + self.bump(); + let ix = self.parse_expr()?; + hi = self.span; + self.expect(&token::CloseDelim(token::Bracket))?; + let index = self.mk_index(e, ix); + e = self.mk_expr(lo.to(hi), index, ThinVec::new()) + } + _ => return Ok(e) + } + } + return Ok(e); + } + + crate fn process_potential_macro_variable(&mut self) { + let (token, span) = match self.token { + token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() && + self.look_ahead(1, |t| t.is_ident()) => { + self.bump(); + let name = match self.token { + token::Ident(ident, _) => ident, + _ => unreachable!() + }; + let mut err = self.fatal(&format!("unknown macro variable `{}`", name)); + err.span_label(self.span, "unknown macro variable"); + err.emit(); + self.bump(); + return + } + token::Interpolated(ref nt) => { + self.meta_var_span = Some(self.span); + // Interpolated identifier and lifetime tokens are replaced with usual identifier + // and lifetime tokens, so the former are never encountered during normal parsing. + match **nt { + token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span), + token::NtLifetime(ident) => (token::Lifetime(ident), ident.span), + _ => return, + } + } + _ => return, + }; + self.token = token; + self.span = span; + } + + /// Parses a single token tree from the input. + crate fn parse_token_tree(&mut self) -> TokenTree { + match self.token { + token::OpenDelim(..) => { + let frame = mem::replace(&mut self.token_cursor.frame, + self.token_cursor.stack.pop().unwrap()); + self.span = frame.span.entire(); + self.bump(); + TokenTree::Delimited( + frame.span, + frame.delim, + frame.tree_cursor.stream.into(), + ) + }, + token::CloseDelim(_) | token::Eof => unreachable!(), + _ => { + let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span); + self.bump(); + TokenTree::Token(span, token) + } + } + } + + // parse a stream of tokens into a list of TokenTree's, + // up to EOF. + pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> { + let mut tts = Vec::new(); + while self.token != token::Eof { + tts.push(self.parse_token_tree()); + } + Ok(tts) + } + + pub fn parse_tokens(&mut self) -> TokenStream { + let mut result = Vec::new(); + loop { + match self.token { + token::Eof | token::CloseDelim(..) => break, + _ => result.push(self.parse_token_tree().into()), + } + } + TokenStream::new(result) + } + + /// Parse a prefix-unary-operator expr + fn parse_prefix_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; + let lo = self.span; + // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr() + let (hi, ex) = match self.token { + token::Not => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + (lo.to(span), self.mk_unary(UnOp::Not, e)) + } + // Suggest `!` for bitwise negation when encountering a `~` + token::Tilde => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + let span_of_tilde = lo; + let mut err = self.diagnostic() + .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator"); + err.span_suggestion_short( + span_of_tilde, + "use `!` to perform bitwise negation", + "!".to_owned(), + Applicability::MachineApplicable + ); + err.emit(); + (lo.to(span), self.mk_unary(UnOp::Not, e)) + } + token::BinOp(token::Minus) => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + (lo.to(span), self.mk_unary(UnOp::Neg, e)) + } + token::BinOp(token::Star) => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + (lo.to(span), self.mk_unary(UnOp::Deref, e)) + } + token::BinOp(token::And) | token::AndAnd => { + self.expect_and()?; + let m = self.parse_mutability(); + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + (lo.to(span), ExprKind::AddrOf(m, e)) + } + token::Ident(..) if self.token.is_keyword(keywords::In) => { + self.bump(); + let place = self.parse_expr_res( + Restrictions::NO_STRUCT_LITERAL, + None, + )?; + let blk = self.parse_block()?; + let span = blk.span; + let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new()); + (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr)) + } + token::Ident(..) if self.token.is_keyword(keywords::Box) => { + self.bump(); + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + (lo.to(span), ExprKind::Box(e)) + } + token::Ident(..) if self.token.is_ident_named("not") => { + // `not` is just an ordinary identifier in Rust-the-language, + // but as `rustc`-the-compiler, we can issue clever diagnostics + // for confused users who really want to say `!` + let token_cannot_continue_expr = |t: &token::Token| match *t { + // These tokens can start an expression after `!`, but + // can't continue an expression after an ident + token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw), + token::Literal(..) | token::Pound => true, + token::Interpolated(ref nt) => match **nt { + token::NtIdent(..) | token::NtExpr(..) | + token::NtBlock(..) | token::NtPath(..) => true, + _ => false, + }, + _ => false + }; + let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr); + if cannot_continue_expr { + self.bump(); + // Emit the error ... + let mut err = self.diagnostic() + .struct_span_err(self.span, + &format!("unexpected {} after identifier", + self.this_token_descr())); + // span the `not` plus trailing whitespace to avoid + // trailing whitespace after the `!` in our suggestion + let to_replace = self.sess.source_map() + .span_until_non_whitespace(lo.to(self.span)); + err.span_suggestion_short( + to_replace, + "use `!` to perform logical negation", + "!".to_owned(), + Applicability::MachineApplicable + ); + err.emit(); + // —and recover! (just as if we were in the block + // for the `token::Not` arm) + let e = self.parse_prefix_expr(None); + let (span, e) = self.interpolated_or_expr_span(e)?; + (lo.to(span), self.mk_unary(UnOp::Not, e)) + } else { + return self.parse_dot_or_call_expr(Some(attrs)); + } + } + _ => { return self.parse_dot_or_call_expr(Some(attrs)); } + }; + return Ok(self.mk_expr(lo.to(hi), ex, attrs)); + } + + /// Parses an associative expression. + /// + /// This parses an expression accounting for associativity and precedence of the operators in + /// the expression. + #[inline] + fn parse_assoc_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + self.parse_assoc_expr_with(0, already_parsed_attrs.into()) + } + + /// Parses an associative expression with operators of at least `min_prec` precedence. + fn parse_assoc_expr_with(&mut self, + min_prec: usize, + lhs: LhsExpr) + -> PResult<'a, P<Expr>> { + let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { + expr + } else { + let attrs = match lhs { + LhsExpr::AttributesParsed(attrs) => Some(attrs), + _ => None, + }; + if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) { + return self.parse_prefix_range_expr(attrs); + } else { + self.parse_prefix_expr(attrs)? + } + }; + + if self.expr_is_complete(&lhs) { + // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071 + return Ok(lhs); + } + self.expected_tokens.push(TokenType::Operator); + while let Some(op) = AssocOp::from_token(&self.token) { + + // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what + // it refers to. Interpolated identifiers are unwrapped early and never show up here + // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process + // it as "interpolated", it doesn't change the answer for non-interpolated idents. + let lhs_span = match (self.prev_token_kind, &lhs.node) { + (PrevTokenKind::Interpolated, _) => self.prev_span, + (PrevTokenKind::Ident, &ExprKind::Path(None, ref path)) + if path.segments.len() == 1 => self.prev_span, + _ => lhs.span, + }; + + let cur_op_span = self.span; + let restrictions = if op.is_assign_like() { + self.restrictions & Restrictions::NO_STRUCT_LITERAL + } else { + self.restrictions + }; + if op.precedence() < min_prec { + break; + } + // Check for deprecated `...` syntax + if self.token == token::DotDotDot && op == AssocOp::DotDotEq { + self.err_dotdotdot_syntax(self.span); + } + + self.bump(); + if op.is_comparison() { + self.check_no_chained_comparison(&lhs, &op); + } + // Special cases: + if op == AssocOp::As { + lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?; + continue + } else if op == AssocOp::Colon { + lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) { + Ok(lhs) => lhs, + Err(mut err) => { + err.span_label(self.span, + "expecting a type here because of type ascription"); + let cm = self.sess.source_map(); + let cur_pos = cm.lookup_char_pos(self.span.lo()); + let op_pos = cm.lookup_char_pos(cur_op_span.hi()); + if cur_pos.line != op_pos.line { + err.span_suggestion( + cur_op_span, + "try using a semicolon", + ";".to_string(), + Applicability::MaybeIncorrect // speculative + ); + } + return Err(err); + } + }; + continue + } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq { + // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to + // generalise it to the Fixity::None code. + // + // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other + // two variants are handled with `parse_prefix_range_expr` call above. + let rhs = if self.is_at_start_of_range_notation_rhs() { + Some(self.parse_assoc_expr_with(op.precedence() + 1, + LhsExpr::NotYetParsed)?) + } else { + None + }; + let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs { + x.span + } else { + cur_op_span + }); + let limits = if op == AssocOp::DotDot { + RangeLimits::HalfOpen + } else { + RangeLimits::Closed + }; + + let r = self.mk_range(Some(lhs), rhs, limits)?; + lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new()); + break + } + + let rhs = match op.fixity() { + Fixity::Right => self.with_res( + restrictions - Restrictions::STMT_EXPR, + |this| { + this.parse_assoc_expr_with(op.precedence(), + LhsExpr::NotYetParsed) + }), + Fixity::Left => self.with_res( + restrictions - Restrictions::STMT_EXPR, + |this| { + this.parse_assoc_expr_with(op.precedence() + 1, + LhsExpr::NotYetParsed) + }), + // We currently have no non-associative operators that are not handled above by + // the special cases. The code is here only for future convenience. + Fixity::None => self.with_res( + restrictions - Restrictions::STMT_EXPR, + |this| { + this.parse_assoc_expr_with(op.precedence() + 1, + LhsExpr::NotYetParsed) + }), + }?; + + // Make sure that the span of the parent node is larger than the span of lhs and rhs, + // including the attributes. + let lhs_span = lhs + .attrs + .iter() + .filter(|a| a.style == AttrStyle::Outer) + .next() + .map_or(lhs_span, |a| a.span); + let span = lhs_span.to(rhs.span); + lhs = match op { + AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | + AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor | + AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight | + AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual | + AssocOp::Greater | AssocOp::GreaterEqual => { + let ast_op = op.to_ast_binop().unwrap(); + let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs); + self.mk_expr(span, binary, ThinVec::new()) + } + AssocOp::Assign => + self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()), + AssocOp::ObsoleteInPlace => + self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()), + AssocOp::AssignOp(k) => { + let aop = match k { + token::Plus => BinOpKind::Add, + token::Minus => BinOpKind::Sub, + token::Star => BinOpKind::Mul, + token::Slash => BinOpKind::Div, + token::Percent => BinOpKind::Rem, + token::Caret => BinOpKind::BitXor, + token::And => BinOpKind::BitAnd, + token::Or => BinOpKind::BitOr, + token::Shl => BinOpKind::Shl, + token::Shr => BinOpKind::Shr, + }; + let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs); + self.mk_expr(span, aopexpr, ThinVec::new()) + } + AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => { + self.bug("AssocOp should have been handled by special case") + } + }; + + if op.fixity() == Fixity::None { break } + } + Ok(lhs) + } + + fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span, + expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind) + -> PResult<'a, P<Expr>> { + let mk_expr = |this: &mut Self, rhs: P<Ty>| { + this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new()) + }; + + // Save the state of the parser before parsing type normally, in case there is a + // LessThan comparison after this cast. + let parser_snapshot_before_type = self.clone(); + match self.parse_ty_no_plus() { + Ok(rhs) => { + Ok(mk_expr(self, rhs)) + } + Err(mut type_err) => { + // Rewind to before attempting to parse the type with generics, to recover + // from situations like `x as usize < y` in which we first tried to parse + // `usize < y` as a type with generic arguments. + let parser_snapshot_after_type = self.clone(); + mem::replace(self, parser_snapshot_before_type); + + match self.parse_path(PathStyle::Expr) { + Ok(path) => { + let (op_noun, op_verb) = match self.token { + token::Lt => ("comparison", "comparing"), + token::BinOp(token::Shl) => ("shift", "shifting"), + _ => { + // We can end up here even without `<` being the next token, for + // example because `parse_ty_no_plus` returns `Err` on keywords, + // but `parse_path` returns `Ok` on them due to error recovery. + // Return original error and parser state. + mem::replace(self, parser_snapshot_after_type); + return Err(type_err); + } + }; + + // Successfully parsed the type path leaving a `<` yet to parse. + type_err.cancel(); + + // Report non-fatal diagnostics, keep `x as usize` as an expression + // in AST and continue parsing. + let msg = format!("`<` is interpreted as a start of generic \ + arguments for `{}`, not a {}", path, op_noun); + let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg); + err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span), + "interpreted as generic arguments"); + err.span_label(self.span, format!("not interpreted as {}", op_noun)); + + let expr = mk_expr(self, P(Ty { + span: path.span, + node: TyKind::Path(None, path), + id: ast::DUMMY_NODE_ID + })); + + let expr_str = self.sess.source_map().span_to_snippet(expr.span) + .unwrap_or_else(|_| pprust::expr_to_string(&expr)); + err.span_suggestion( + expr.span, + &format!("try {} the cast value", op_verb), + format!("({})", expr_str), + Applicability::MachineApplicable + ); + err.emit(); + + Ok(expr) + } + Err(mut path_err) => { + // Couldn't parse as a path, return original error and parser state. + path_err.cancel(); + mem::replace(self, parser_snapshot_after_type); + Err(type_err) + } + } + } + } + } + + /// Produce an error if comparison operators are chained (RFC #558). + /// We only need to check lhs, not rhs, because all comparison ops + /// have same precedence and are left-associative + fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) { + debug_assert!(outer_op.is_comparison(), + "check_no_chained_comparison: {:?} is not comparison", + outer_op); + match lhs.node { + ExprKind::Binary(op, _, _) if op.node.is_comparison() => { + // respan to include both operators + let op_span = op.span.to(self.span); + let mut err = self.diagnostic().struct_span_err(op_span, + "chained comparison operators require parentheses"); + if op.node == BinOpKind::Lt && + *outer_op == AssocOp::Less || // Include `<` to provide this recommendation + *outer_op == AssocOp::Greater // even in a case like the following: + { // Foo<Bar<Baz<Qux, ()>>> + err.help( + "use `::<...>` instead of `<...>` if you meant to specify type arguments"); + err.help("or use `(...)` if you meant to specify fn arguments"); + } + err.emit(); + } + _ => {} + } + } + + /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr` + fn parse_prefix_range_expr(&mut self, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + // Check for deprecated `...` syntax + if self.token == token::DotDotDot { + self.err_dotdotdot_syntax(self.span); + } + + debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token), + "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq", + self.token); + let tok = self.token.clone(); + let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; + let lo = self.span; + let mut hi = self.span; + self.bump(); + let opt_end = if self.is_at_start_of_range_notation_rhs() { + // RHS must be parsed with more associativity than the dots. + let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1; + Some(self.parse_assoc_expr_with(next_prec, + LhsExpr::NotYetParsed) + .map(|x|{ + hi = x.span; + x + })?) + } else { + None + }; + let limits = if tok == token::DotDot { + RangeLimits::HalfOpen + } else { + RangeLimits::Closed + }; + + let r = self.mk_range(None, opt_end, limits)?; + Ok(self.mk_expr(lo.to(hi), r, attrs)) + } + + fn is_at_start_of_range_notation_rhs(&self) -> bool { + if self.token.can_begin_expr() { + // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`. + if self.token == token::OpenDelim(token::Brace) { + return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL); + } + true + } else { + false + } + } + + /// Parses an `if` or `if let` expression (`if` token already eaten). + fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + if self.check_keyword(keywords::Let) { + return self.parse_if_let_expr(attrs); + } + let lo = self.prev_span; + let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; + + // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then + // verify that the last statement is either an implicit return (no `;`) or an explicit + // return. This won't catch blocks with an explicit `return`, but that would be caught by + // the dead code lint. + if self.eat_keyword(keywords::Else) || !cond.returns() { + let sp = self.sess.source_map().next_point(lo); + let mut err = self.diagnostic() + .struct_span_err(sp, "missing condition for `if` statemement"); + err.span_label(sp, "expected if condition here"); + return Err(err) + } + let not_block = self.token != token::OpenDelim(token::Brace); + let thn = self.parse_block().map_err(|mut err| { + if not_block { + err.span_label(lo, "this `if` statement has a condition, but no block"); + } + err + })?; + let mut els: Option<P<Expr>> = None; + let mut hi = thn.span; + if self.eat_keyword(keywords::Else) { + let elexpr = self.parse_else_expr()?; + hi = elexpr.span; + els = Some(elexpr); + } + Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs)) + } + + /// Parses an `if let` expression (`if` token already eaten). + fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> { + let lo = self.prev_span; + self.expect_keyword(keywords::Let)?; + let pats = self.parse_pats()?; + self.expect(&token::Eq)?; + let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; + let thn = self.parse_block()?; + let (hi, els) = if self.eat_keyword(keywords::Else) { + let expr = self.parse_else_expr()?; + (expr.span, Some(expr)) + } else { + (thn.span, None) + }; + Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs)) + } + + /// Parses `move |args| expr`. + fn parse_lambda_expr(&mut self, + attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> + { + let lo = self.span; + let movability = if self.eat_keyword(keywords::Static) { + Movability::Static + } else { + Movability::Movable + }; + let asyncness = if self.span.rust_2018() { + self.parse_asyncness() + } else { + IsAsync::NotAsync + }; + let capture_clause = if self.eat_keyword(keywords::Move) { + CaptureBy::Value + } else { + CaptureBy::Ref + }; + let decl = self.parse_fn_block_decl()?; + let decl_hi = self.prev_span; + let body = match decl.output { + FunctionRetTy::Default(_) => { + let restrictions = self.restrictions - Restrictions::STMT_EXPR; + self.parse_expr_res(restrictions, None)? + }, + _ => { + // If an explicit return type is given, require a + // block to appear (RFC 968). + let body_lo = self.span; + self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())? + } + }; + + Ok(self.mk_expr( + lo.to(body.span), + ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)), + attrs)) + } + + // `else` token already eaten + fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> { + if self.eat_keyword(keywords::If) { + return self.parse_if_expr(ThinVec::new()); + } else { + let blk = self.parse_block()?; + return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new())); + } + } + + /// Parse a 'for' .. 'in' expression ('for' token already eaten) + fn parse_for_expr(&mut self, opt_label: Option<Label>, + span_lo: Span, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + // Parse: `for <src_pat> in <src_expr> <src_loop_block>` + + let pat = self.parse_top_level_pat()?; + if !self.eat_keyword(keywords::In) { + let in_span = self.prev_span.between(self.span); + let mut err = self.sess.span_diagnostic + .struct_span_err(in_span, "missing `in` in `for` loop"); + err.span_suggestion_short( + in_span, "try adding `in` here", " in ".into(), + // has been misleading, at least in the past (closed Issue #48492) + Applicability::MaybeIncorrect + ); + err.emit(); + } + let in_span = self.prev_span; + if self.eat_keyword(keywords::In) { + // a common typo: `for _ in in bar {}` + let mut err = self.sess.span_diagnostic.struct_span_err( + self.prev_span, + "expected iterable, found keyword `in`", + ); + err.span_suggestion_short( + in_span.until(self.prev_span), + "remove the duplicated `in`", + String::new(), + Applicability::MachineApplicable, + ); + err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)"); + err.note("for more information on the status of emplacement syntax, see <\ + https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"); + err.emit(); + } + let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; + let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + + let hi = self.prev_span; + Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs)) + } + + /// Parses a `while` or `while let` expression (`while` token already eaten). + fn parse_while_expr(&mut self, opt_label: Option<Label>, + span_lo: Span, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + if self.token.is_keyword(keywords::Let) { + return self.parse_while_let_expr(opt_label, span_lo, attrs); + } + let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; + let (iattrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + let span = span_lo.to(body.span); + return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs)); + } + + /// Parses a `while let` expression (`while` token already eaten). + fn parse_while_let_expr(&mut self, opt_label: Option<Label>, + span_lo: Span, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + self.expect_keyword(keywords::Let)?; + let pats = self.parse_pats()?; + self.expect(&token::Eq)?; + let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; + let (iattrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + let span = span_lo.to(body.span); + return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs)); + } + + // parse `loop {...}`, `loop` token already eaten + fn parse_loop_expr(&mut self, opt_label: Option<Label>, + span_lo: Span, + mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + let (iattrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + let span = span_lo.to(body.span); + Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs)) + } + + /// Parses an `async move {...}` expression. + pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> + { + let span_lo = self.span; + self.expect_keyword(keywords::Async)?; + let capture_clause = if self.eat_keyword(keywords::Move) { + CaptureBy::Value + } else { + CaptureBy::Ref + }; + let (iattrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + Ok(self.mk_expr( + span_lo.to(body.span), + ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs)) + } + + /// Parses a `try {...}` expression (`try` token already eaten). + fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>) + -> PResult<'a, P<Expr>> + { + let (iattrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs)) + } + + // `match` token already eaten + fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { + let match_span = self.prev_span; + let lo = self.prev_span; + let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, + None)?; + if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) { + if self.token == token::Token::Semi { + e.span_suggestion_short( + match_span, + "try removing this `match`", + String::new(), + Applicability::MaybeIncorrect // speculative + ); + } + return Err(e) + } + attrs.extend(self.parse_inner_attributes()?); + + let mut arms: Vec<Arm> = Vec::new(); + while self.token != token::CloseDelim(token::Brace) { + match self.parse_arm() { + Ok(arm) => arms.push(arm), + Err(mut e) => { + // Recover by skipping to the end of the block. + e.emit(); + self.recover_stmt(); + let span = lo.to(self.span); + if self.token == token::CloseDelim(token::Brace) { + self.bump(); + } + return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs)); + } + } + } + let hi = self.span; + self.bump(); + return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs)); + } + + crate fn parse_arm(&mut self) -> PResult<'a, Arm> { + maybe_whole!(self, NtArm, |x| x); + + let attrs = self.parse_outer_attributes()?; + let pats = self.parse_pats()?; + let guard = if self.eat_keyword(keywords::If) { + Some(Guard::If(self.parse_expr()?)) + } else { + None + }; + let arrow_span = self.span; + self.expect(&token::FatArrow)?; + let arm_start_span = self.span; + + let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None) + .map_err(|mut err| { + err.span_label(arrow_span, "while parsing the `match` arm starting here"); + err + })?; + + let require_comma = classify::expr_requires_semi_to_be_stmt(&expr) + && self.token != token::CloseDelim(token::Brace); + + if require_comma { + let cm = self.sess.source_map(); + self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) + .map_err(|mut err| { + match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) { + (Ok(ref expr_lines), Ok(ref arm_start_lines)) + if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col + && expr_lines.lines.len() == 2 + && self.token == token::FatArrow => { + // We check whether there's any trailing code in the parse span, + // if there isn't, we very likely have the following: + // + // X | &Y => "y" + // | -- - missing comma + // | | + // | arrow_span + // X | &X => "x" + // | - ^^ self.span + // | | + // | parsed until here as `"y" & X` + err.span_suggestion_short( + cm.next_point(arm_start_span), + "missing a comma here to end this `match` arm", + ",".to_owned(), + Applicability::MachineApplicable + ); + } + _ => { + err.span_label(arrow_span, + "while parsing the `match` arm starting here"); + } + } + err + })?; + } else { + self.eat(&token::Comma); + } + + Ok(ast::Arm { + attrs, + pats, + guard, + body: expr, + }) + } + + /// Parses an expression. + #[inline] + pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> { + self.parse_expr_res(Restrictions::empty(), None) + } + + /// Evaluates the closure with restrictions in place. + /// + /// Afters the closure is evaluated, restrictions are reset. + fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T + where F: FnOnce(&mut Self) -> T + { + let old = self.restrictions; + self.restrictions = r; + let r = f(self); + self.restrictions = old; + return r; + + } + + /// Parses an expression, subject to the given restrictions. + #[inline] + fn parse_expr_res(&mut self, r: Restrictions, + already_parsed_attrs: Option<ThinVec<Attribute>>) + -> PResult<'a, P<Expr>> { + self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs)) + } + + /// Parses the RHS of a local variable declaration (e.g., '= 14;'). + fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> { + if self.eat(&token::Eq) { + Ok(Some(self.parse_expr()?)) + } else if skip_eq { + Ok(Some(self.parse_expr()?)) + } else { + Ok(None) + } + } + + /// Parses patterns, separated by '|' s. + fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> { + // Allow a '|' before the pats (RFC 1925 + RFC 2530) + self.eat(&token::BinOp(token::Or)); + + let mut pats = Vec::new(); + loop { + pats.push(self.parse_top_level_pat()?); + + if self.token == token::OrOr { + let mut err = self.struct_span_err(self.span, + "unexpected token `||` after pattern"); + err.span_suggestion( + self.span, + "use a single `|` to specify multiple patterns", + "|".to_owned(), + Applicability::MachineApplicable + ); + err.emit(); + self.bump(); + } else if self.eat(&token::BinOp(token::Or)) { + // This is a No-op. Continue the loop to parse the next + // pattern. + } else { + return Ok(pats); + } + }; + } + + // Parses a parenthesized list of patterns like + // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns: + // - a vector of the patterns that were parsed + // - an option indicating the index of the `..` element + // - a boolean indicating whether a trailing comma was present. + // Trailing commas are significant because (p) and (p,) are different patterns. + fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> { + self.expect(&token::OpenDelim(token::Paren))?; + let result = self.parse_pat_list()?; + self.expect(&token::CloseDelim(token::Paren))?; + Ok(result) + } + + fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> { + let mut fields = Vec::new(); + let mut ddpos = None; + let mut trailing_comma = false; + loop { + if self.eat(&token::DotDot) { + if ddpos.is_none() { + ddpos = Some(fields.len()); + } else { + // Emit a friendly error, ignore `..` and continue parsing + self.struct_span_err( + self.prev_span, + "`..` can only be used once per tuple or tuple struct pattern", + ) + .span_label(self.prev_span, "can only be used once per pattern") + .emit(); + } + } else if !self.check(&token::CloseDelim(token::Paren)) { + fields.push(self.parse_pat(None)?); + } else { + break + } + + trailing_comma = self.eat(&token::Comma); + if !trailing_comma { + break + } + } + + if ddpos == Some(fields.len()) && trailing_comma { + // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed. + let msg = "trailing comma is not permitted after `..`"; + self.struct_span_err(self.prev_span, msg) + .span_label(self.prev_span, msg) + .emit(); + } + + Ok((fields, ddpos, trailing_comma)) + } + + fn parse_pat_vec_elements( + &mut self, + ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> { + let mut before = Vec::new(); + let mut slice = None; + let mut after = Vec::new(); + let mut first = true; + let mut before_slice = true; + + while self.token != token::CloseDelim(token::Bracket) { + if first { + first = false; + } else { + self.expect(&token::Comma)?; + + if self.token == token::CloseDelim(token::Bracket) + && (before_slice || !after.is_empty()) { + break + } + } + + if before_slice { + if self.eat(&token::DotDot) { + + if self.check(&token::Comma) || + self.check(&token::CloseDelim(token::Bracket)) { + slice = Some(P(Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Wild, + span: self.prev_span, + })); + before_slice = false; + } + continue + } + } + + let subpat = self.parse_pat(None)?; + if before_slice && self.eat(&token::DotDot) { + slice = Some(subpat); + before_slice = false; + } else if before_slice { + before.push(subpat); + } else { + after.push(subpat); + } + } + + Ok((before, slice, after)) + } + + fn parse_pat_field( + &mut self, + lo: Span, + attrs: Vec<Attribute> + ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> { + // Check if a colon exists one ahead. This means we're parsing a fieldname. + let hi; + let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) { + // Parsing a pattern of the form "fieldname: pat" + let fieldname = self.parse_field_name()?; + self.bump(); + let pat = self.parse_pat(None)?; + hi = pat.span; + (pat, fieldname, false) + } else { + // Parsing a pattern of the form "(box) (ref) (mut) fieldname" + let is_box = self.eat_keyword(keywords::Box); + let boxed_span = self.span; + let is_ref = self.eat_keyword(keywords::Ref); + let is_mut = self.eat_keyword(keywords::Mut); + let fieldname = self.parse_ident()?; + hi = self.prev_span; + + let bind_type = match (is_ref, is_mut) { + (true, true) => BindingMode::ByRef(Mutability::Mutable), + (true, false) => BindingMode::ByRef(Mutability::Immutable), + (false, true) => BindingMode::ByValue(Mutability::Mutable), + (false, false) => BindingMode::ByValue(Mutability::Immutable), + }; + let fieldpat = P(Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Ident(bind_type, fieldname, None), + span: boxed_span.to(hi), + }); + + let subpat = if is_box { + P(Pat { + id: ast::DUMMY_NODE_ID, + node: PatKind::Box(fieldpat), + span: lo.to(hi), + }) + } else { + fieldpat + }; + (subpat, fieldname, true) + }; + + Ok(source_map::Spanned { + span: lo.to(hi), + node: ast::FieldPat { + ident: fieldname, + pat: subpat, + is_shorthand, + attrs: attrs.into(), + } + }) + } + + /// Parses the fields of a struct-like pattern. + fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> { + let mut fields = Vec::new(); + let mut etc = false; + let mut ate_comma = true; + let mut delayed_err: Option<DiagnosticBuilder<'a>> = None; + let mut etc_span = None; + + while self.token != token::CloseDelim(token::Brace) { + let attrs = self.parse_outer_attributes()?; + let lo = self.span; + + // check that a comma comes after every field + if !ate_comma { + let err = self.struct_span_err(self.prev_span, "expected `,`"); + if let Some(mut delayed) = delayed_err { + delayed.emit(); + } + return Err(err); + } + ate_comma = false; + + if self.check(&token::DotDot) || self.token == token::DotDotDot { + etc = true; + let mut etc_sp = self.span; + + if self.token == token::DotDotDot { // Issue #46718 + // Accept `...` as if it were `..` to avoid further errors + let mut err = self.struct_span_err(self.span, + "expected field pattern, found `...`"); + err.span_suggestion( + self.span, + "to omit remaining fields, use one fewer `.`", + "..".to_owned(), + Applicability::MachineApplicable + ); + err.emit(); + } + self.bump(); // `..` || `...` + + if self.token == token::CloseDelim(token::Brace) { + etc_span = Some(etc_sp); + break; + } + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!("expected `}}`, found {}", token_str)); + + err.span_label(self.span, "expected `}`"); + let mut comma_sp = None; + if self.token == token::Comma { // Issue #49257 + etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span)); + err.span_label(etc_sp, + "`..` must be at the end and cannot have a trailing comma"); + comma_sp = Some(self.span); + self.bump(); + ate_comma = true; + } + + etc_span = Some(etc_sp.until(self.span)); + if self.token == token::CloseDelim(token::Brace) { + // If the struct looks otherwise well formed, recover and continue. + if let Some(sp) = comma_sp { + err.span_suggestion_short( + sp, + "remove this comma", + String::new(), + Applicability::MachineApplicable, + ); + } + err.emit(); + break; + } else if self.token.is_ident() && ate_comma { + // Accept fields coming after `..,`. + // This way we avoid "pattern missing fields" errors afterwards. + // We delay this error until the end in order to have a span for a + // suggested fix. + if let Some(mut delayed_err) = delayed_err { + delayed_err.emit(); + return Err(err); + } else { + delayed_err = Some(err); + } + } else { + if let Some(mut err) = delayed_err { + err.emit(); + } + return Err(err); + } + } + + fields.push(match self.parse_pat_field(lo, attrs) { + Ok(field) => field, + Err(err) => { + if let Some(mut delayed_err) = delayed_err { + delayed_err.emit(); + } + return Err(err); + } + }); + ate_comma = self.eat(&token::Comma); + } + + if let Some(mut err) = delayed_err { + if let Some(etc_span) = etc_span { + err.multipart_suggestion( + "move the `..` to the end of the field list", + vec![ + (etc_span, String::new()), + (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })), + ], + Applicability::MachineApplicable, + ); + } + err.emit(); + } + return Ok((fields, etc)); + } + + fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> { + if self.token.is_path_start() { + let lo = self.span; + let (qself, path) = if self.eat_lt() { + // Parse a qualified path + let (qself, path) = self.parse_qpath(PathStyle::Expr)?; + (Some(qself), path) + } else { + // Parse an unqualified path + (None, self.parse_path(PathStyle::Expr)?) + }; + let hi = self.prev_span; + Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new())) + } else { + self.parse_literal_maybe_minus() + } + } + + // helper function to decide whether to parse as ident binding or to try to do + // something more complex like range patterns + fn parse_as_ident(&mut self) -> bool { + self.look_ahead(1, |t| match *t { + token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) | + token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false), + // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the + // range pattern branch + token::DotDot => None, + _ => Some(true), + }).unwrap_or_else(|| self.look_ahead(2, |t| match *t { + token::Comma | token::CloseDelim(token::Bracket) => true, + _ => false, + })) + } + + /// A wrapper around `parse_pat` with some special error handling for the + /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast + /// to subpatterns within such). + fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> { + let pat = self.parse_pat(None)?; + if self.token == token::Comma { + // An unexpected comma after a top-level pattern is a clue that the + // user (perhaps more accustomed to some other language) forgot the + // parentheses in what should have been a tuple pattern; return a + // suggestion-enhanced error here rather than choking on the comma + // later. + let comma_span = self.span; + self.bump(); + if let Err(mut err) = self.parse_pat_list() { + // We didn't expect this to work anyway; we just wanted + // to advance to the end of the comma-sequence so we know + // the span to suggest parenthesizing + err.cancel(); + } + let seq_span = pat.span.to(self.prev_span); + let mut err = self.struct_span_err(comma_span, + "unexpected `,` in pattern"); + if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) { + err.span_suggestion( + seq_span, + "try adding parentheses to match on a tuple..", + format!("({})", seq_snippet), + Applicability::MachineApplicable + ).span_suggestion( + seq_span, + "..or a vertical bar to match on multiple alternatives", + format!("{}", seq_snippet.replace(",", " |")), + Applicability::MachineApplicable + ); + } + return Err(err); + } + Ok(pat) + } + + /// Parses a pattern. + pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> { + self.parse_pat_with_range_pat(true, expected) + } + + /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are + /// allowed). + fn parse_pat_with_range_pat( + &mut self, + allow_range_pat: bool, + expected: Option<&'static str>, + ) -> PResult<'a, P<Pat>> { + maybe_whole!(self, NtPat, |x| x); + + let lo = self.span; + let pat; + match self.token { + token::BinOp(token::And) | token::AndAnd => { + // Parse &pat / &mut pat + self.expect_and()?; + let mutbl = self.parse_mutability(); + if let token::Lifetime(ident) = self.token { + let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", + ident)); + err.span_label(self.span, "unexpected lifetime"); + return Err(err); + } + let subpat = self.parse_pat_with_range_pat(false, expected)?; + pat = PatKind::Ref(subpat, mutbl); + } + token::OpenDelim(token::Paren) => { + // Parse (pat,pat,pat,...) as tuple pattern + let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?; + pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma { + PatKind::Paren(fields.into_iter().nth(0).unwrap()) + } else { + PatKind::Tuple(fields, ddpos) + }; + } + token::OpenDelim(token::Bracket) => { + // Parse [pat,pat,...] as slice pattern + self.bump(); + let (before, slice, after) = self.parse_pat_vec_elements()?; + self.expect(&token::CloseDelim(token::Bracket))?; + pat = PatKind::Slice(before, slice, after); + } + // At this point, token != &, &&, (, [ + _ => if self.eat_keyword(keywords::Underscore) { + // Parse _ + pat = PatKind::Wild; + } else if self.eat_keyword(keywords::Mut) { + // Parse mut ident @ pat / mut ref ident @ pat + let mutref_span = self.prev_span.to(self.span); + let binding_mode = if self.eat_keyword(keywords::Ref) { + self.diagnostic() + .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect") + .span_suggestion( + mutref_span, + "try switching the order", + "ref mut".into(), + Applicability::MachineApplicable + ).emit(); + BindingMode::ByRef(Mutability::Mutable) + } else { + BindingMode::ByValue(Mutability::Mutable) + }; + pat = self.parse_pat_ident(binding_mode)?; + } else if self.eat_keyword(keywords::Ref) { + // Parse ref ident @ pat / ref mut ident @ pat + let mutbl = self.parse_mutability(); + pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?; + } else if self.eat_keyword(keywords::Box) { + // Parse box pat + let subpat = self.parse_pat_with_range_pat(false, None)?; + pat = PatKind::Box(subpat); + } else if self.token.is_ident() && !self.token.is_reserved_ident() && + self.parse_as_ident() { + // Parse ident @ pat + // This can give false positives and parse nullary enums, + // they are dealt with later in resolve + let binding_mode = BindingMode::ByValue(Mutability::Immutable); + pat = self.parse_pat_ident(binding_mode)?; + } else if self.token.is_path_start() { + // Parse pattern starting with a path + let (qself, path) = if self.eat_lt() { + // Parse a qualified path + let (qself, path) = self.parse_qpath(PathStyle::Expr)?; + (Some(qself), path) + } else { + // Parse an unqualified path + (None, self.parse_path(PathStyle::Expr)?) + }; + match self.token { + token::Not if qself.is_none() => { + // Parse macro invocation + self.bump(); + let (delim, tts) = self.expect_delimited_token_tree()?; + let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim }); + pat = PatKind::Mac(mac); + } + token::DotDotDot | token::DotDotEq | token::DotDot => { + let end_kind = match self.token { + token::DotDot => RangeEnd::Excluded, + token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot), + token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq), + _ => panic!("can only parse `..`/`...`/`..=` for ranges \ + (checked above)"), + }; + let op_span = self.span; + // Parse range + let span = lo.to(self.prev_span); + let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new()); + self.bump(); + let end = self.parse_pat_range_end()?; + let op = Spanned { span: op_span, node: end_kind }; + pat = PatKind::Range(begin, end, op); + } + token::OpenDelim(token::Brace) => { + if qself.is_some() { + let msg = "unexpected `{` after qualified path"; + let mut err = self.fatal(msg); + err.span_label(self.span, msg); + return Err(err); + } + // Parse struct pattern + self.bump(); + let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| { + e.emit(); + self.recover_stmt(); + (vec![], false) + }); + self.bump(); + pat = PatKind::Struct(path, fields, etc); + } + token::OpenDelim(token::Paren) => { + if qself.is_some() { + let msg = "unexpected `(` after qualified path"; + let mut err = self.fatal(msg); + err.span_label(self.span, msg); + return Err(err); + } + // Parse tuple struct or enum pattern + let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?; + pat = PatKind::TupleStruct(path, fields, ddpos) + } + _ => pat = PatKind::Path(qself, path), + } + } else { + // Try to parse everything else as literal with optional minus + match self.parse_literal_maybe_minus() { + Ok(begin) => { + let op_span = self.span; + if self.check(&token::DotDot) || self.check(&token::DotDotEq) || + self.check(&token::DotDotDot) { + let end_kind = if self.eat(&token::DotDotDot) { + RangeEnd::Included(RangeSyntax::DotDotDot) + } else if self.eat(&token::DotDotEq) { + RangeEnd::Included(RangeSyntax::DotDotEq) + } else if self.eat(&token::DotDot) { + RangeEnd::Excluded + } else { + panic!("impossible case: we already matched \ + on a range-operator token") + }; + let end = self.parse_pat_range_end()?; + let op = Spanned { span: op_span, node: end_kind }; + pat = PatKind::Range(begin, end, op); + } else { + pat = PatKind::Lit(begin); + } + } + Err(mut err) => { + self.cancel(&mut err); + let expected = expected.unwrap_or("pattern"); + let msg = format!( + "expected {}, found {}", + expected, + self.this_token_descr(), + ); + let mut err = self.fatal(&msg); + err.span_label(self.span, format!("expected {}", expected)); + return Err(err); + } + } + } + } + + let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID }; + let pat = self.maybe_recover_from_bad_qpath(pat, true)?; + + if !allow_range_pat { + match pat.node { + PatKind::Range( + _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. } + ) => {}, + PatKind::Range(..) => { + let mut err = self.struct_span_err( + pat.span, + "the range pattern here has ambiguous interpretation", + ); + err.span_suggestion( + pat.span, + "add parentheses to clarify the precedence", + format!("({})", pprust::pat_to_string(&pat)), + // "ambiguous interpretation" implies that we have to be guessing + Applicability::MaybeIncorrect + ); + return Err(err); + } + _ => {} + } + } + + Ok(P(pat)) + } + + /// Parses `ident` or `ident @ pat`. + /// used by the copy foo and ref foo patterns to give a good + /// error message when parsing mistakes like `ref foo(a, b)`. + fn parse_pat_ident(&mut self, + binding_mode: ast::BindingMode) + -> PResult<'a, PatKind> { + let ident = self.parse_ident()?; + let sub = if self.eat(&token::At) { + Some(self.parse_pat(Some("binding pattern"))?) + } else { + None + }; + + // just to be friendly, if they write something like + // ref Some(i) + // we end up here with ( as the current token. This shortly + // leads to a parse error. Note that if there is no explicit + // binding mode then we do not end up here, because the lookahead + // will direct us over to parse_enum_variant() + if self.token == token::OpenDelim(token::Paren) { + return Err(self.span_fatal( + self.prev_span, + "expected identifier, found enum pattern")) + } + + Ok(PatKind::Ident(binding_mode, ident, sub)) + } + + /// Parses a local variable declaration. + fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> { + let lo = self.prev_span; + let pat = self.parse_top_level_pat()?; + + let (err, ty) = if self.eat(&token::Colon) { + // Save the state of the parser before parsing type normally, in case there is a `:` + // instead of an `=` typo. + let parser_snapshot_before_type = self.clone(); + let colon_sp = self.prev_span; + match self.parse_ty() { + Ok(ty) => (None, Some(ty)), + Err(mut err) => { + // Rewind to before attempting to parse the type and continue parsing + let parser_snapshot_after_type = self.clone(); + mem::replace(self, parser_snapshot_before_type); + + let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap(); + err.span_label(pat.span, format!("while parsing the type for `{}`", snippet)); + (Some((parser_snapshot_after_type, colon_sp, err)), None) + } + } + } else { + (None, None) + }; + let init = match (self.parse_initializer(err.is_some()), err) { + (Ok(init), None) => { // init parsed, ty parsed + init + } + (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error + // Could parse the type as if it were the initializer, it is likely there was a + // typo in the code: `:` instead of `=`. Add suggestion and emit the error. + err.span_suggestion_short( + colon_sp, + "use `=` if you meant to assign", + "=".to_string(), + Applicability::MachineApplicable + ); + err.emit(); + // As this was parsed successfully, continue as if the code has been fixed for the + // rest of the file. It will still fail due to the emitted error, but we avoid + // extra noise. + init + } + (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error + init_err.cancel(); + // Couldn't parse the type nor the initializer, only raise the type error and + // return to the parser state before parsing the type as the initializer. + // let x: <parse_error>; + mem::replace(self, snapshot); + return Err(ty_err); + } + (Err(err), None) => { // init error, ty parsed + // Couldn't parse the initializer and we're not attempting to recover a failed + // parse of the type, return the error. + return Err(err); + } + }; + let hi = if self.token == token::Semi { + self.span + } else { + self.prev_span + }; + Ok(P(ast::Local { + ty, + pat, + init, + id: ast::DUMMY_NODE_ID, + span: lo.to(hi), + attrs, + })) + } + + /// Parses a structure field. + fn parse_name_and_ty(&mut self, + lo: Span, + vis: Visibility, + attrs: Vec<Attribute>) + -> PResult<'a, StructField> { + let name = self.parse_ident()?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + Ok(StructField { + span: lo.to(self.prev_span), + ident: Some(name), + vis, + id: ast::DUMMY_NODE_ID, + ty, + attrs, + }) + } + + /// Emits an expected-item-after-attributes error. + fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> { + let message = match attrs.last() { + Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment", + _ => "expected item after attributes", + }; + + let mut err = self.diagnostic().struct_span_err(self.prev_span, message); + if attrs.last().unwrap().is_sugared_doc { + err.span_label(self.prev_span, "this doc comment doesn't document anything"); + } + Err(err) + } + + /// Parse a statement. This stops just before trailing semicolons on everything but items. + /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. + pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> { + Ok(self.parse_stmt_(true)) + } + + // Eat tokens until we can be relatively sure we reached the end of the + // statement. This is something of a best-effort heuristic. + // + // We terminate when we find an unmatched `}` (without consuming it). + fn recover_stmt(&mut self) { + self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore) + } + + // If `break_on_semi` is `Break`, then we will stop consuming tokens after + // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is + // approximate - it can mean we break too early due to macros, but that + // should only lead to sub-optimal recovery, not inaccurate parsing). + // + // If `break_on_block` is `Break`, then we will stop consuming tokens + // after finding (and consuming) a brace-delimited block. + fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) { + let mut brace_depth = 0; + let mut bracket_depth = 0; + let mut in_block = false; + debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", + break_on_semi, break_on_block); + loop { + debug!("recover_stmt_ loop {:?}", self.token); + match self.token { + token::OpenDelim(token::DelimToken::Brace) => { + brace_depth += 1; + self.bump(); + if break_on_block == BlockMode::Break && + brace_depth == 1 && + bracket_depth == 0 { + in_block = true; + } + } + token::OpenDelim(token::DelimToken::Bracket) => { + bracket_depth += 1; + self.bump(); + } + token::CloseDelim(token::DelimToken::Brace) => { + if brace_depth == 0 { + debug!("recover_stmt_ return - close delim {:?}", self.token); + break; + } + brace_depth -= 1; + self.bump(); + if in_block && bracket_depth == 0 && brace_depth == 0 { + debug!("recover_stmt_ return - block end {:?}", self.token); + break; + } + } + token::CloseDelim(token::DelimToken::Bracket) => { + bracket_depth -= 1; + if bracket_depth < 0 { + bracket_depth = 0; + } + self.bump(); + } + token::Eof => { + debug!("recover_stmt_ return - Eof"); + break; + } + token::Semi => { + self.bump(); + if break_on_semi == SemiColonMode::Break && + brace_depth == 0 && + bracket_depth == 0 { + debug!("recover_stmt_ return - Semi"); + break; + } + } + token::Comma => { + if break_on_semi == SemiColonMode::Comma && + brace_depth == 0 && + bracket_depth == 0 { + debug!("recover_stmt_ return - Semi"); + break; + } else { + self.bump(); + } + } + _ => { + self.bump() + } + } + } + } + + fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> { + self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| { + e.emit(); + self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); + None + }) + } + + fn is_async_block(&mut self) -> bool { + self.token.is_keyword(keywords::Async) && + ( + ( // `async move {` + self.look_ahead(1, |t| t.is_keyword(keywords::Move)) && + self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) + ) || ( // `async {` + self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) + ) + ) + } + + fn is_do_catch_block(&mut self) -> bool { + self.token.is_keyword(keywords::Do) && + self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) && + self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) && + !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) + } + + fn is_try_block(&mut self) -> bool { + self.token.is_keyword(keywords::Try) && + self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) && + self.span.rust_2018() && + // prevent `while try {} {}`, `if try {} {} else {}`, etc. + !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) + } + + fn is_union_item(&self) -> bool { + self.token.is_keyword(keywords::Union) && + self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) + } + + fn is_crate_vis(&self) -> bool { + self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep) + } + + fn is_existential_type_decl(&self) -> bool { + self.token.is_keyword(keywords::Existential) && + self.look_ahead(1, |t| t.is_keyword(keywords::Type)) + } + + fn is_auto_trait_item(&mut self) -> bool { + // auto trait + (self.token.is_keyword(keywords::Auto) + && self.look_ahead(1, |t| t.is_keyword(keywords::Trait))) + || // unsafe auto trait + (self.token.is_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) && + self.look_ahead(2, |t| t.is_keyword(keywords::Trait))) + } + + fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span) + -> PResult<'a, Option<P<Item>>> { + let token_lo = self.span; + let (ident, def) = match self.token { + token::Ident(ident, false) if ident.name == keywords::Macro.name() => { + self.bump(); + let ident = self.parse_ident()?; + let tokens = if self.check(&token::OpenDelim(token::Brace)) { + match self.parse_token_tree() { + TokenTree::Delimited(_, _, tts) => tts, + _ => unreachable!(), + } + } else if self.check(&token::OpenDelim(token::Paren)) { + let args = self.parse_token_tree(); + let body = if self.check(&token::OpenDelim(token::Brace)) { + self.parse_token_tree() + } else { + self.unexpected()?; + unreachable!() + }; + TokenStream::new(vec![ + args.into(), + TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(), + body.into(), + ]) + } else { + self.unexpected()?; + unreachable!() + }; + + (ident, ast::MacroDef { tokens: tokens.into(), legacy: false }) + } + token::Ident(ident, _) if ident.name == "macro_rules" && + self.look_ahead(1, |t| *t == token::Not) => { + let prev_span = self.prev_span; + self.complain_if_pub_macro(&vis.node, prev_span); + self.bump(); + self.bump(); + + let ident = self.parse_ident()?; + let (delim, tokens) = self.expect_delimited_token_tree()?; + if delim != MacDelimiter::Brace { + if !self.eat(&token::Semi) { + let msg = "macros that expand to items must either \ + be surrounded with braces or followed by a semicolon"; + self.span_err(self.prev_span, msg); + } + } + + (ident, ast::MacroDef { tokens: tokens, legacy: true }) + } + _ => return Ok(None), + }; + + let span = lo.to(self.prev_span); + Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec()))) + } + + fn parse_stmt_without_recovery(&mut self, + macro_legacy_warnings: bool) + -> PResult<'a, Option<Stmt>> { + maybe_whole!(self, NtStmt, |x| Some(x)); + + let attrs = self.parse_outer_attributes()?; + let lo = self.span; + + Ok(Some(if self.eat_keyword(keywords::Let) { + Stmt { + id: ast::DUMMY_NODE_ID, + node: StmtKind::Local(self.parse_local(attrs.into())?), + span: lo.to(self.prev_span), + } + } else if let Some(macro_def) = self.eat_macro_def( + &attrs, + &source_map::respan(lo, VisibilityKind::Inherited), + lo, + )? { + Stmt { + id: ast::DUMMY_NODE_ID, + node: StmtKind::Item(macro_def), + span: lo.to(self.prev_span), + } + // Starts like a simple path, being careful to avoid contextual keywords + // such as a union items, item with `crate` visibility or auto trait items. + // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts + // like a path (1 token), but it fact not a path. + // `union::b::c` - path, `union U { ... }` - not a path. + // `crate::b::c` - path, `crate struct S;` - not a path. + } else if self.token.is_path_start() && + !self.token.is_qpath_start() && + !self.is_union_item() && + !self.is_crate_vis() && + !self.is_existential_type_decl() && + !self.is_auto_trait_item() { + let pth = self.parse_path(PathStyle::Expr)?; + + if !self.eat(&token::Not) { + let expr = if self.check(&token::OpenDelim(token::Brace)) { + self.parse_struct_expr(lo, pth, ThinVec::new())? + } else { + let hi = self.prev_span; + self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new()) + }; + + let expr = self.with_res(Restrictions::STMT_EXPR, |this| { + let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; + this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) + })?; + + return Ok(Some(Stmt { + id: ast::DUMMY_NODE_ID, + node: StmtKind::Expr(expr), + span: lo.to(self.prev_span), + })); + } + + // it's a macro invocation + let id = match self.token { + token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier + _ => self.parse_ident()?, + }; + + // check that we're pointing at delimiters (need to check + // again after the `if`, because of `parse_ident` + // consuming more tokens). + match self.token { + token::OpenDelim(_) => {} + _ => { + // we only expect an ident if we didn't parse one + // above. + let ident_str = if id.name == keywords::Invalid.name() { + "identifier, " + } else { + "" + }; + let tok_str = self.this_token_descr(); + let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}", + ident_str, + tok_str)); + err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str)); + return Err(err) + }, + } + + let (delim, tts) = self.expect_delimited_token_tree()?; + let hi = self.prev_span; + + let style = if delim == MacDelimiter::Brace { + MacStmtStyle::Braces + } else { + MacStmtStyle::NoBraces + }; + + if id.name == keywords::Invalid.name() { + let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim }); + let node = if delim == MacDelimiter::Brace || + self.token == token::Semi || self.token == token::Eof { + StmtKind::Mac(P((mac, style, attrs.into()))) + } + // We used to incorrectly stop parsing macro-expanded statements here. + // If the next token will be an error anyway but could have parsed with the + // earlier behavior, stop parsing here and emit a warning to avoid breakage. + else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token { + // These can continue an expression, so we can't stop parsing and warn. + token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | + token::BinOp(token::Minus) | token::BinOp(token::Star) | + token::BinOp(token::And) | token::BinOp(token::Or) | + token::AndAnd | token::OrOr | + token::DotDot | token::DotDotDot | token::DotDotEq => false, + _ => true, + } { + self.warn_missing_semicolon(); + StmtKind::Mac(P((mac, style, attrs.into()))) + } else { + let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new()); + let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?; + let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; + StmtKind::Expr(e) + }; + Stmt { + id: ast::DUMMY_NODE_ID, + span: lo.to(hi), + node, + } + } else { + // if it has a special ident, it's definitely an item + // + // Require a semicolon or braces. + if style != MacStmtStyle::Braces { + if !self.eat(&token::Semi) { + self.span_err(self.prev_span, + "macros that expand to items must \ + either be surrounded with braces or \ + followed by a semicolon"); + } + } + let span = lo.to(hi); + Stmt { + id: ast::DUMMY_NODE_ID, + span, + node: StmtKind::Item({ + self.mk_item( + span, id /*id is good here*/, + ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })), + respan(lo, VisibilityKind::Inherited), + attrs) + }), + } + } + } else { + // FIXME: Bad copy of attrs + let old_directory_ownership = + mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); + let item = self.parse_item_(attrs.clone(), false, true)?; + self.directory.ownership = old_directory_ownership; + + match item { + Some(i) => Stmt { + id: ast::DUMMY_NODE_ID, + span: lo.to(i.span), + node: StmtKind::Item(i), + }, + None => { + let unused_attrs = |attrs: &[Attribute], s: &mut Self| { + if !attrs.is_empty() { + if s.prev_token_kind == PrevTokenKind::DocComment { + s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit(); + } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { + s.span_err(s.span, "expected statement after outer attribute"); + } + } + }; + + // Do not attempt to parse an expression if we're done here. + if self.token == token::Semi { + unused_attrs(&attrs, self); + self.bump(); + return Ok(None); + } + + if self.token == token::CloseDelim(token::Brace) { + unused_attrs(&attrs, self); + return Ok(None); + } + + // Remainder are line-expr stmts. + let e = self.parse_expr_res( + Restrictions::STMT_EXPR, Some(attrs.into()))?; + Stmt { + id: ast::DUMMY_NODE_ID, + span: lo.to(e.span), + node: StmtKind::Expr(e), + } + } + } + })) + } + + /// Checks if this expression is a successfully parsed statement. + fn expr_is_complete(&mut self, e: &Expr) -> bool { + self.restrictions.contains(Restrictions::STMT_EXPR) && + !classify::expr_requires_semi_to_be_stmt(e) + } + + /// Parses a block. No inner attributes are allowed. + pub fn parse_block(&mut self) -> PResult<'a, P<Block>> { + maybe_whole!(self, NtBlock, |x| x); + + let lo = self.span; + + if !self.eat(&token::OpenDelim(token::Brace)) { + let sp = self.span; + let tok = self.this_token_descr(); + let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok)); + let do_not_suggest_help = + self.token.is_keyword(keywords::In) || self.token == token::Colon; + + if self.token.is_ident_named("and") { + e.span_suggestion_short( + self.span, + "use `&&` instead of `and` for the boolean operator", + "&&".to_string(), + Applicability::MaybeIncorrect, + ); + } + if self.token.is_ident_named("or") { + e.span_suggestion_short( + self.span, + "use `||` instead of `or` for the boolean operator", + "||".to_string(), + Applicability::MaybeIncorrect, + ); + } + + // Check to see if the user has written something like + // + // if (cond) + // bar; + // + // Which is valid in other languages, but not Rust. + match self.parse_stmt_without_recovery(false) { + Ok(Some(stmt)) => { + if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) + || do_not_suggest_help { + // if the next token is an open brace (e.g., `if a b {`), the place- + // inside-a-block suggestion would be more likely wrong than right + e.span_label(sp, "expected `{`"); + return Err(e); + } + let mut stmt_span = stmt.span; + // expand the span to include the semicolon, if it exists + if self.eat(&token::Semi) { + stmt_span = stmt_span.with_hi(self.prev_span.hi()); + } + let sugg = pprust::to_string(|s| { + use crate::print::pprust::{PrintState, INDENT_UNIT}; + s.ibox(INDENT_UNIT)?; + s.bopen()?; + s.print_stmt(&stmt)?; + s.bclose_maybe_open(stmt.span, INDENT_UNIT, false) + }); + e.span_suggestion( + stmt_span, + "try placing this code inside a block", + sugg, + // speculative, has been misleading in the past (closed Issue #46836) + Applicability::MaybeIncorrect + ); + } + Err(mut e) => { + self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); + self.cancel(&mut e); + } + _ => () + } + e.span_label(sp, "expected `{`"); + return Err(e); + } + + self.parse_block_tail(lo, BlockCheckMode::Default) + } + + /// Parses a block. Inner attributes are allowed. + fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> { + maybe_whole!(self, NtBlock, |x| (Vec::new(), x)); + + let lo = self.span; + self.expect(&token::OpenDelim(token::Brace))?; + Ok((self.parse_inner_attributes()?, + self.parse_block_tail(lo, BlockCheckMode::Default)?)) + } + + /// Parses the rest of a block expression or function body. + /// Precondition: already parsed the '{'. + fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> { + let mut stmts = vec![]; + while !self.eat(&token::CloseDelim(token::Brace)) { + let stmt = match self.parse_full_stmt(false) { + Err(mut err) => { + err.emit(); + self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore); + Some(Stmt { + id: ast::DUMMY_NODE_ID, + node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)), + span: self.span, + }) + } + Ok(stmt) => stmt, + }; + if let Some(stmt) = stmt { + stmts.push(stmt); + } else if self.token == token::Eof { + break; + } else { + // Found only `;` or `}`. + continue; + }; + } + Ok(P(ast::Block { + stmts, + id: ast::DUMMY_NODE_ID, + rules: s, + span: lo.to(self.prev_span), + })) + } + + /// Parses a statement, including the trailing semicolon. + crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> { + // skip looking for a trailing semicolon when we have an interpolated statement + maybe_whole!(self, NtStmt, |x| Some(x)); + + let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? { + Some(stmt) => stmt, + None => return Ok(None), + }; + + match stmt.node { + StmtKind::Expr(ref expr) if self.token != token::Eof => { + // expression without semicolon + if classify::expr_requires_semi_to_be_stmt(expr) { + // Just check for errors and recover; do not eat semicolon yet. + if let Err(mut e) = + self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)]) + { + e.emit(); + self.recover_stmt(); + } + } + } + StmtKind::Local(..) => { + // We used to incorrectly allow a macro-expanded let statement to lack a semicolon. + if macro_legacy_warnings && self.token != token::Semi { + self.warn_missing_semicolon(); + } else { + self.expect_one_of(&[], &[token::Semi])?; + } + } + _ => {} + } + + if self.eat(&token::Semi) { + stmt = stmt.add_trailing_semicolon(); + } + + stmt.span = stmt.span.with_hi(self.prev_span.hi()); + Ok(Some(stmt)) + } + + fn warn_missing_semicolon(&self) { + self.diagnostic().struct_span_warn(self.span, { + &format!("expected `;`, found {}", self.this_token_descr()) + }).note({ + "This was erroneously allowed and will become a hard error in a future release" + }).emit(); + } + + fn err_dotdotdot_syntax(&self, span: Span) { + self.diagnostic().struct_span_err(span, { + "unexpected token: `...`" + }).span_suggestion( + span, "use `..` for an exclusive range", "..".to_owned(), + Applicability::MaybeIncorrect + ).span_suggestion( + span, "or `..=` for an inclusive range", "..=".to_owned(), + Applicability::MaybeIncorrect + ).emit(); + } + + /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`. + /// + /// ``` + /// BOUND = TY_BOUND | LT_BOUND + /// LT_BOUND = LIFETIME (e.g., `'a`) + /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) + /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`) + /// ``` + fn parse_generic_bounds_common(&mut self, + allow_plus: bool, + colon_span: Option<Span>) -> PResult<'a, GenericBounds> { + let mut bounds = Vec::new(); + let mut negative_bounds = Vec::new(); + let mut last_plus_span = None; + loop { + // This needs to be synchronized with `Token::can_begin_bound`. + let is_bound_start = self.check_path() || self.check_lifetime() || + self.check(&token::Not) || // used for error reporting only + self.check(&token::Question) || + self.check_keyword(keywords::For) || + self.check(&token::OpenDelim(token::Paren)); + if is_bound_start { + let lo = self.span; + let has_parens = self.eat(&token::OpenDelim(token::Paren)); + let inner_lo = self.span; + let is_negative = self.eat(&token::Not); + let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None }; + if self.token.is_lifetime() { + if let Some(question_span) = question { + self.span_err(question_span, + "`?` may only modify trait bounds, not lifetime bounds"); + } + bounds.push(GenericBound::Outlives(self.expect_lifetime())); + if has_parens { + let inner_span = inner_lo.to(self.prev_span); + self.expect(&token::CloseDelim(token::Paren))?; + let mut err = self.struct_span_err( + lo.to(self.prev_span), + "parenthesized lifetime bounds are not supported" + ); + if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) { + err.span_suggestion_short( + lo.to(self.prev_span), + "remove the parentheses", + snippet.to_owned(), + Applicability::MachineApplicable + ); + } + err.emit(); + } + } else { + let lifetime_defs = self.parse_late_bound_lifetime_defs()?; + let path = self.parse_path(PathStyle::Type)?; + if has_parens { + self.expect(&token::CloseDelim(token::Paren))?; + } + let poly_span = lo.to(self.prev_span); + if is_negative { + negative_bounds.push( + last_plus_span.or(colon_span).unwrap() + .to(poly_span)); + } else { + let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span); + let modifier = if question.is_some() { + TraitBoundModifier::Maybe + } else { + TraitBoundModifier::None + }; + bounds.push(GenericBound::Trait(poly_trait, modifier)); + } + } + } else { + break + } + + if !allow_plus || !self.eat_plus() { + break + } else { + last_plus_span = Some(self.prev_span); + } + } + + if !negative_bounds.is_empty() { + let plural = negative_bounds.len() > 1; + let mut err = self.struct_span_err(negative_bounds, + "negative trait bounds are not supported"); + let bound_list = colon_span.unwrap().to(self.prev_span); + let mut new_bound_list = String::new(); + if !bounds.is_empty() { + let mut snippets = bounds.iter().map(|bound| bound.span()) + .map(|span| self.sess.source_map().span_to_snippet(span)); + while let Some(Ok(snippet)) = snippets.next() { + new_bound_list.push_str(" + "); + new_bound_list.push_str(&snippet); + } + new_bound_list = new_bound_list.replacen(" +", ":", 1); + } + err.span_suggestion_short(bound_list, + &format!("remove the trait bound{}", + if plural { "s" } else { "" }), + new_bound_list, + Applicability::MachineApplicable); + err.emit(); + } + + return Ok(bounds); + } + + fn parse_generic_bounds(&mut self, colon_span: Option<Span>) -> PResult<'a, GenericBounds> { + self.parse_generic_bounds_common(true, colon_span) + } + + /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. + /// + /// ``` + /// BOUND = LT_BOUND (e.g., `'a`) + /// ``` + fn parse_lt_param_bounds(&mut self) -> GenericBounds { + let mut lifetimes = Vec::new(); + while self.check_lifetime() { + lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime())); + + if !self.eat_plus() { + break + } + } + lifetimes + } + + /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`. + fn parse_ty_param(&mut self, + preceding_attrs: Vec<Attribute>) + -> PResult<'a, GenericParam> { + let ident = self.parse_ident()?; + + // Parse optional colon and param bounds. + let bounds = if self.eat(&token::Colon) { + self.parse_generic_bounds(None)? + } else { + Vec::new() + }; + + let default = if self.eat(&token::Eq) { + Some(self.parse_ty()?) + } else { + None + }; + + Ok(GenericParam { + ident, + id: ast::DUMMY_NODE_ID, + attrs: preceding_attrs.into(), + bounds, + kind: GenericParamKind::Type { + default, + } + }) + } + + /// Parses the following grammar: + /// + /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty] + fn parse_trait_item_assoc_ty(&mut self) + -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> { + let ident = self.parse_ident()?; + let mut generics = self.parse_generics()?; + + // Parse optional colon and param bounds. + let bounds = if self.eat(&token::Colon) { + self.parse_generic_bounds(None)? + } else { + Vec::new() + }; + generics.where_clause = self.parse_where_clause()?; + + let default = if self.eat(&token::Eq) { + Some(self.parse_ty()?) + } else { + None + }; + self.expect(&token::Semi)?; + + Ok((ident, TraitItemKind::Type(bounds, default), generics)) + } + + fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> { + self.expect_keyword(keywords::Const)?; + let ident = self.parse_ident()?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + + Ok(GenericParam { + ident, + id: ast::DUMMY_NODE_ID, + attrs: preceding_attrs.into(), + bounds: Vec::new(), + kind: GenericParamKind::Const { + ty, + } + }) + } + + /// Parses a (possibly empty) list of lifetime and type parameters, possibly including + /// a trailing comma and erroneous trailing attributes. + crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> { + let mut params = Vec::new(); + loop { + let attrs = self.parse_outer_attributes()?; + if self.check_lifetime() { + let lifetime = self.expect_lifetime(); + // Parse lifetime parameter. + let bounds = if self.eat(&token::Colon) { + self.parse_lt_param_bounds() + } else { + Vec::new() + }; + params.push(ast::GenericParam { + ident: lifetime.ident, + id: lifetime.id, + attrs: attrs.into(), + bounds, + kind: ast::GenericParamKind::Lifetime, + }); + } else if self.check_keyword(keywords::Const) { + // Parse const parameter. + params.push(self.parse_const_param(attrs)?); + } else if self.check_ident() { + // Parse type parameter. + params.push(self.parse_ty_param(attrs)?); + } else { + // Check for trailing attributes and stop parsing. + if !attrs.is_empty() { + if !params.is_empty() { + self.struct_span_err( + attrs[0].span, + &format!("trailing attribute after generic parameter"), + ) + .span_label(attrs[0].span, "attributes must go before parameters") + .emit(); + } else { + self.struct_span_err( + attrs[0].span, + &format!("attribute without generic parameters"), + ) + .span_label( + attrs[0].span, + "attributes are only permitted when preceding parameters", + ) + .emit(); + } + } + break + } + + if !self.eat(&token::Comma) { + break + } + } + Ok(params) + } + + /// Parses a set of optional generic type parameter declarations. Where + /// clauses are not parsed here, and must be added later via + /// `parse_where_clause()`. + /// + /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > ) + /// | ( < lifetimes , typaramseq ( , )? > ) + /// where typaramseq = ( typaram ) | ( typaram , typaramseq ) + fn parse_generics(&mut self) -> PResult<'a, ast::Generics> { + maybe_whole!(self, NtGenerics, |x| x); + + let span_lo = self.span; + if self.eat_lt() { + let params = self.parse_generic_params()?; + self.expect_gt()?; + Ok(ast::Generics { + params, + where_clause: WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + span: syntax_pos::DUMMY_SP, + }, + span: span_lo.to(self.prev_span), + }) + } else { + Ok(ast::Generics::default()) + } + } + + /// Parses generic args (within a path segment) with recovery for extra leading angle brackets. + /// For the purposes of understanding the parsing logic of generic arguments, this function + /// can be thought of being the same as just calling `self.parse_generic_args()` if the source + /// had the correct amount of leading angle brackets. + /// + /// ```ignore (diagnostics) + /// bar::<<<<T as Foo>::Output>(); + /// ^^ help: remove extra angle brackets + /// ``` + fn parse_generic_args_with_leaning_angle_bracket_recovery( + &mut self, + style: PathStyle, + lo: Span, + ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> { + // We need to detect whether there are extra leading left angle brackets and produce an + // appropriate error and suggestion. This cannot be implemented by looking ahead at + // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens + // then there won't be matching `>` tokens to find. + // + // To explain how this detection works, consider the following example: + // + // ```ignore (diagnostics) + // bar::<<<<T as Foo>::Output>(); + // ^^ help: remove extra angle brackets + // ``` + // + // Parsing of the left angle brackets starts in this function. We start by parsing the + // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via + // `eat_lt`): + // + // *Upcoming tokens:* `<<<<T as Foo>::Output>;` + // *Unmatched count:* 1 + // *`parse_path_segment` calls deep:* 0 + // + // This has the effect of recursing as this function is called if a `<` character + // is found within the expected generic arguments: + // + // *Upcoming tokens:* `<<<T as Foo>::Output>;` + // *Unmatched count:* 2 + // *`parse_path_segment` calls deep:* 1 + // + // Eventually we will have recursed until having consumed all of the `<` tokens and + // this will be reflected in the count: + // + // *Upcoming tokens:* `T as Foo>::Output>;` + // *Unmatched count:* 4 + // `parse_path_segment` calls deep:* 3 + // + // The parser will continue until reaching the first `>` - this will decrement the + // unmatched angle bracket count and return to the parent invocation of this function + // having succeeded in parsing: + // + // *Upcoming tokens:* `::Output>;` + // *Unmatched count:* 3 + // *`parse_path_segment` calls deep:* 2 + // + // This will continue until the next `>` character which will also return successfully + // to the parent invocation of this function and decrement the count: + // + // *Upcoming tokens:* `;` + // *Unmatched count:* 2 + // *`parse_path_segment` calls deep:* 1 + // + // At this point, this function will expect to find another matching `>` character but + // won't be able to and will return an error. This will continue all the way up the + // call stack until the first invocation: + // + // *Upcoming tokens:* `;` + // *Unmatched count:* 2 + // *`parse_path_segment` calls deep:* 0 + // + // In doing this, we have managed to work out how many unmatched leading left angle + // brackets there are, but we cannot recover as the unmatched angle brackets have + // already been consumed. To remedy this, we keep a snapshot of the parser state + // before we do the above. We can then inspect whether we ended up with a parsing error + // and unmatched left angle brackets and if so, restore the parser state before we + // consumed any `<` characters to emit an error and consume the erroneous tokens to + // recover by attempting to parse again. + // + // In practice, the recursion of this function is indirect and there will be other + // locations that consume some `<` characters - as long as we update the count when + // this happens, it isn't an issue. + + let is_first_invocation = style == PathStyle::Expr; + // Take a snapshot before attempting to parse - we can restore this later. + let snapshot = if is_first_invocation { + Some(self.clone()) + } else { + None + }; + + debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)"); + match self.parse_generic_args() { + Ok(value) => Ok(value), + Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => { + // Cancel error from being unable to find `>`. We know the error + // must have been this due to a non-zero unmatched angle bracket + // count. + e.cancel(); + + // Swap `self` with our backup of the parser state before attempting to parse + // generic arguments. + let snapshot = mem::replace(self, snapshot.unwrap()); + + debug!( + "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \ + snapshot.count={:?}", + snapshot.unmatched_angle_bracket_count, + ); + + // Eat the unmatched angle brackets. + for _ in 0..snapshot.unmatched_angle_bracket_count { + self.eat_lt(); + } + + // Make a span over ${unmatched angle bracket count} characters. + let span = lo.with_hi( + lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count) + ); + let plural = snapshot.unmatched_angle_bracket_count > 1; + self.diagnostic() + .struct_span_err( + span, + &format!( + "unmatched angle bracket{}", + if plural { "s" } else { "" } + ), + ) + .span_suggestion( + span, + &format!( + "remove extra angle bracket{}", + if plural { "s" } else { "" } + ), + String::new(), + Applicability::MachineApplicable, + ) + .emit(); + + // Try again without unmatched angle bracket characters. + self.parse_generic_args() + }, + Err(e) => Err(e), + } + } + + /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, + /// possibly including trailing comma. + fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> { + let mut args = Vec::new(); + let mut bindings = Vec::new(); + let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new(); + let mut assoc_ty_bindings: Vec<Span> = Vec::new(); + + let args_lo = self.span; + + loop { + if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { + // Parse lifetime argument. + args.push(GenericArg::Lifetime(self.expect_lifetime())); + misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings); + } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) { + // Parse associated type binding. + let lo = self.span; + let ident = self.parse_ident()?; + self.bump(); + let ty = self.parse_ty()?; + let span = lo.to(self.prev_span); + bindings.push(TypeBinding { + id: ast::DUMMY_NODE_ID, + ident, + ty, + span, + }); + assoc_ty_bindings.push(span); + } else if self.check_const_arg() { + // FIXME(const_generics): to distinguish between idents for types and consts, + // we should introduce a GenericArg::Ident in the AST and distinguish when + // lowering to the HIR. For now, idents for const args are not permitted. + + // Parse const argument. + let expr = if let token::OpenDelim(token::Brace) = self.token { + self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())? + } else if self.token.is_ident() { + // FIXME(const_generics): to distinguish between idents for types and consts, + // we should introduce a GenericArg::Ident in the AST and distinguish when + // lowering to the HIR. For now, idents for const args are not permitted. + return Err( + self.fatal("identifiers may currently not be used for const generics") + ); + } else { + // FIXME(const_generics): this currently conflicts with emplacement syntax + // with negative integer literals. + self.parse_literal_maybe_minus()? + }; + let value = AnonConst { + id: ast::DUMMY_NODE_ID, + value: expr, + }; + args.push(GenericArg::Const(value)); + misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings); + } else if self.check_type() { + // Parse type argument. + args.push(GenericArg::Type(self.parse_ty()?)); + misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings); + } else { + break + } + + if !self.eat(&token::Comma) { + break + } + } + + // FIXME: we would like to report this in ast_validation instead, but we currently do not + // preserve ordering of generic parameters with respect to associated type binding, so we + // lose that information after parsing. + if misplaced_assoc_ty_bindings.len() > 0 { + let mut err = self.struct_span_err( + args_lo.to(self.prev_span), + "associated type bindings must be declared after generic parameters", + ); + for span in misplaced_assoc_ty_bindings { + err.span_label( + span, + "this associated type binding should be moved after the generic parameters", + ); + } + err.emit(); + } + + Ok((args, bindings)) + } + + /// Parses an optional where-clause and places it in `generics`. + /// + /// ```ignore (only-for-syntax-highlight) + /// where T : Trait<U, V> + 'b, 'a : 'b + /// ``` + fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> { + maybe_whole!(self, NtWhereClause, |x| x); + + let mut where_clause = WhereClause { + id: ast::DUMMY_NODE_ID, + predicates: Vec::new(), + span: syntax_pos::DUMMY_SP, + }; + + if !self.eat_keyword(keywords::Where) { + return Ok(where_clause); + } + let lo = self.prev_span; + + // We are considering adding generics to the `where` keyword as an alternative higher-rank + // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking + // change we parse those generics now, but report an error. + if self.choose_generics_over_qpath() { + let generics = self.parse_generics()?; + self.struct_span_err( + generics.span, + "generic parameters on `where` clauses are reserved for future use", + ) + .span_label(generics.span, "currently unsupported") + .emit(); + } + + loop { + let lo = self.span; + if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { + let lifetime = self.expect_lifetime(); + // Bounds starting with a colon are mandatory, but possibly empty. + self.expect(&token::Colon)?; + let bounds = self.parse_lt_param_bounds(); + where_clause.predicates.push(ast::WherePredicate::RegionPredicate( + ast::WhereRegionPredicate { + span: lo.to(self.prev_span), + lifetime, + bounds, + } + )); + } else if self.check_type() { + // Parse optional `for<'a, 'b>`. + // This `for` is parsed greedily and applies to the whole predicate, + // the bounded type can have its own `for` applying only to it. + // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/> + // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/> + // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/> + let lifetime_defs = self.parse_late_bound_lifetime_defs()?; + + // Parse type with mandatory colon and (possibly empty) bounds, + // or with mandatory equality sign and the second type. + let ty = self.parse_ty()?; + if self.eat(&token::Colon) { + let bounds = self.parse_generic_bounds(None)?; + where_clause.predicates.push(ast::WherePredicate::BoundPredicate( + ast::WhereBoundPredicate { + span: lo.to(self.prev_span), + bound_generic_params: lifetime_defs, + bounded_ty: ty, + bounds, + } + )); + // FIXME: Decide what should be used here, `=` or `==`. + // FIXME: We are just dropping the binders in lifetime_defs on the floor here. + } else if self.eat(&token::Eq) || self.eat(&token::EqEq) { + let rhs_ty = self.parse_ty()?; + where_clause.predicates.push(ast::WherePredicate::EqPredicate( + ast::WhereEqPredicate { + span: lo.to(self.prev_span), + lhs_ty: ty, + rhs_ty, + id: ast::DUMMY_NODE_ID, + } + )); + } else { + return self.unexpected(); + } + } else { + break + } + + if !self.eat(&token::Comma) { + break + } + } + + where_clause.span = lo.to(self.prev_span); + Ok(where_clause) + } + + fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool) + -> PResult<'a, (Vec<Arg> , bool)> { + self.expect(&token::OpenDelim(token::Paren))?; + + let sp = self.span; + let mut variadic = false; + let (args, recovered): (Vec<Option<Arg>>, bool) = + self.parse_seq_to_before_end( + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| { + if p.token == token::DotDotDot { + p.bump(); + variadic = true; + if allow_variadic { + if p.token != token::CloseDelim(token::Paren) { + let span = p.span; + p.span_err(span, + "`...` must be last in argument list for variadic function"); + } + Ok(None) + } else { + let span = p.prev_span; + if p.token == token::CloseDelim(token::Paren) { + // continue parsing to present any further errors + p.struct_span_err( + span, + "only foreign functions are allowed to be variadic" + ).emit(); + Ok(Some(dummy_arg(span))) + } else { + // this function definition looks beyond recovery, stop parsing + p.span_err(span, + "only foreign functions are allowed to be variadic"); + Ok(None) + } + } + } else { + match p.parse_arg_general(named_args, false) { + Ok(arg) => Ok(Some(arg)), + Err(mut e) => { + e.emit(); + let lo = p.prev_span; + // Skip every token until next possible arg or end. + p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]); + // Create a placeholder argument for proper arg count (#34264). + let span = lo.to(p.prev_span); + Ok(Some(dummy_arg(span))) + } + } + } + } + )?; + + if !recovered { + self.eat(&token::CloseDelim(token::Paren)); + } + + let args: Vec<_> = args.into_iter().filter_map(|x| x).collect(); + + if variadic && args.is_empty() { + self.span_err(sp, + "variadic function must be declared with at least one named argument"); + } + + Ok((args, variadic)) + } + + /// Parses the argument list and result type of a function declaration. + fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> { + + let (args, variadic) = self.parse_fn_args(true, allow_variadic)?; + let ret_ty = self.parse_ret_ty(true)?; + + Ok(P(FnDecl { + inputs: args, + output: ret_ty, + variadic, + })) + } + + /// Returns the parsed optional self argument and whether a self shortcut was used. + fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> { + let expect_ident = |this: &mut Self| match this.token { + // Preserve hygienic context. + token::Ident(ident, _) => + { let span = this.span; this.bump(); Ident::new(ident.name, span) } + _ => unreachable!() + }; + let isolated_self = |this: &mut Self, n| { + this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) && + this.look_ahead(n + 1, |t| t != &token::ModSep) + }; + + // Parse optional self parameter of a method. + // Only a limited set of initial token sequences is considered self parameters, anything + // else is parsed as a normal function parameter list, so some lookahead is required. + let eself_lo = self.span; + let (eself, eself_ident, eself_hi) = match self.token { + token::BinOp(token::And) => { + // &self + // &mut self + // &'lt self + // &'lt mut self + // ¬_self + (if isolated_self(self, 1) { + self.bump(); + SelfKind::Region(None, Mutability::Immutable) + } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) && + isolated_self(self, 2) { + self.bump(); + self.bump(); + SelfKind::Region(None, Mutability::Mutable) + } else if self.look_ahead(1, |t| t.is_lifetime()) && + isolated_self(self, 2) { + self.bump(); + let lt = self.expect_lifetime(); + SelfKind::Region(Some(lt), Mutability::Immutable) + } else if self.look_ahead(1, |t| t.is_lifetime()) && + self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) && + isolated_self(self, 3) { + self.bump(); + let lt = self.expect_lifetime(); + self.bump(); + SelfKind::Region(Some(lt), Mutability::Mutable) + } else { + return Ok(None); + }, expect_ident(self), self.prev_span) + } + token::BinOp(token::Star) => { + // *self + // *const self + // *mut self + // *not_self + // Emit special error for `self` cases. + let msg = "cannot pass `self` by raw pointer"; + (if isolated_self(self, 1) { + self.bump(); + self.struct_span_err(self.span, msg) + .span_label(self.span, msg) + .emit(); + SelfKind::Value(Mutability::Immutable) + } else if self.look_ahead(1, |t| t.is_mutability()) && + isolated_self(self, 2) { + self.bump(); + self.bump(); + self.struct_span_err(self.span, msg) + .span_label(self.span, msg) + .emit(); + SelfKind::Value(Mutability::Immutable) + } else { + return Ok(None); + }, expect_ident(self), self.prev_span) + } + token::Ident(..) => { + if isolated_self(self, 0) { + // self + // self: TYPE + let eself_ident = expect_ident(self); + let eself_hi = self.prev_span; + (if self.eat(&token::Colon) { + let ty = self.parse_ty()?; + SelfKind::Explicit(ty, Mutability::Immutable) + } else { + SelfKind::Value(Mutability::Immutable) + }, eself_ident, eself_hi) + } else if self.token.is_keyword(keywords::Mut) && + isolated_self(self, 1) { + // mut self + // mut self: TYPE + self.bump(); + let eself_ident = expect_ident(self); + let eself_hi = self.prev_span; + (if self.eat(&token::Colon) { + let ty = self.parse_ty()?; + SelfKind::Explicit(ty, Mutability::Mutable) + } else { + SelfKind::Value(Mutability::Mutable) + }, eself_ident, eself_hi) + } else { + return Ok(None); + } + } + _ => return Ok(None), + }; + + let eself = source_map::respan(eself_lo.to(eself_hi), eself); + Ok(Some(Arg::from_self(eself, eself_ident))) + } + + /// Parses the parameter list and result type of a function that may have a `self` parameter. + fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>> + where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>, + { + self.expect(&token::OpenDelim(token::Paren))?; + + // Parse optional self argument + let self_arg = self.parse_self_arg()?; + + // Parse the rest of the function parameter list. + let sep = SeqSep::trailing_allowed(token::Comma); + let (fn_inputs, recovered) = if let Some(self_arg) = self_arg { + if self.check(&token::CloseDelim(token::Paren)) { + (vec![self_arg], false) + } else if self.eat(&token::Comma) { + let mut fn_inputs = vec![self_arg]; + let (mut input, recovered) = self.parse_seq_to_before_end( + &token::CloseDelim(token::Paren), sep, parse_arg_fn)?; + fn_inputs.append(&mut input); + (fn_inputs, recovered) + } else { + return self.unexpected(); + } + } else { + self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)? + }; + + if !recovered { + // Parse closing paren and return type. + self.expect(&token::CloseDelim(token::Paren))?; + } + Ok(P(FnDecl { + inputs: fn_inputs, + output: self.parse_ret_ty(true)?, + variadic: false + })) + } + + /// Parses the `|arg, arg|` header of a closure. + fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> { + let inputs_captures = { + if self.eat(&token::OrOr) { + Vec::new() + } else { + self.expect(&token::BinOp(token::Or))?; + let args = self.parse_seq_to_before_tokens( + &[&token::BinOp(token::Or), &token::OrOr], + SeqSep::trailing_allowed(token::Comma), + TokenExpectType::NoExpect, + |p| p.parse_fn_block_arg() + )?.0; + self.expect_or()?; + args + } + }; + let output = self.parse_ret_ty(true)?; + + Ok(P(FnDecl { + inputs: inputs_captures, + output, + variadic: false + })) + } + + /// Parses the name and optional generic types of a function header. + fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> { + let id = self.parse_ident()?; + let generics = self.parse_generics()?; + Ok((id, generics)) + } + + fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility, + attrs: Vec<Attribute>) -> P<Item> { + P(Item { + ident, + attrs, + id: ast::DUMMY_NODE_ID, + node, + vis, + span, + tokens: None, + }) + } + + /// Parses an item-position function declaration. + fn parse_item_fn(&mut self, + unsafety: Unsafety, + asyncness: IsAsync, + constness: Spanned<Constness>, + abi: Abi) + -> PResult<'a, ItemInfo> { + let (ident, mut generics) = self.parse_fn_header()?; + let decl = self.parse_fn_decl(false)?; + generics.where_clause = self.parse_where_clause()?; + let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; + let header = FnHeader { unsafety, asyncness, constness, abi }; + Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs))) + } + + /// Returns `true` if we are looking at `const ID` + /// (returns `false` for things like `const fn`, etc.). + fn is_const_item(&mut self) -> bool { + self.token.is_keyword(keywords::Const) && + !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) && + !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) + } + + /// Parses all the "front matter" for a `fn` declaration, up to + /// and including the `fn` keyword: + /// + /// - `const fn` + /// - `unsafe fn` + /// - `const unsafe fn` + /// - `extern fn` + /// - etc. + fn parse_fn_front_matter(&mut self) + -> PResult<'a, ( + Spanned<Constness>, + Unsafety, + IsAsync, + Abi + )> + { + let is_const_fn = self.eat_keyword(keywords::Const); + let const_span = self.prev_span; + let unsafety = self.parse_unsafety(); + let asyncness = self.parse_asyncness(); + let (constness, unsafety, abi) = if is_const_fn { + (respan(const_span, Constness::Const), unsafety, Abi::Rust) + } else { + let abi = if self.eat_keyword(keywords::Extern) { + self.parse_opt_abi()?.unwrap_or(Abi::C) + } else { + Abi::Rust + }; + (respan(self.prev_span, Constness::NotConst), unsafety, abi) + }; + self.expect_keyword(keywords::Fn)?; + Ok((constness, unsafety, asyncness, abi)) + } + + /// Parses an impl item. + pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> { + maybe_whole!(self, NtImplItem, |x| x); + let attrs = self.parse_outer_attributes()?; + let (mut item, tokens) = self.collect_tokens(|this| { + this.parse_impl_item_(at_end, attrs) + })?; + + // See `parse_item` for why this clause is here. + if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) { + item.tokens = Some(tokens); + } + Ok(item) + } + + fn parse_impl_item_(&mut self, + at_end: &mut bool, + mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> { + let lo = self.span; + let vis = self.parse_visibility(false)?; + let defaultness = self.parse_defaultness(); + let (name, node, generics) = if let Some(type_) = self.eat_type() { + let (name, alias, generics) = type_?; + let kind = match alias { + AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ), + AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds), + }; + (name, kind, generics) + } else if self.is_const_item() { + // This parses the grammar: + // ImplItemConst = "const" Ident ":" Ty "=" Expr ";" + self.expect_keyword(keywords::Const)?; + let name = self.parse_ident()?; + self.expect(&token::Colon)?; + let typ = self.parse_ty()?; + self.expect(&token::Eq)?; + let expr = self.parse_expr()?; + self.expect(&token::Semi)?; + (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default()) + } else { + let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?; + attrs.extend(inner_attrs); + (name, node, generics) + }; + + Ok(ImplItem { + id: ast::DUMMY_NODE_ID, + span: lo.to(self.prev_span), + ident: name, + vis, + defaultness, + attrs, + generics, + node, + tokens: None, + }) + } + + fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) { + match *vis { + VisibilityKind::Inherited => {} + _ => { + let is_macro_rules: bool = match self.token { + token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"), + _ => false, + }; + let mut err = if is_macro_rules { + let mut err = self.diagnostic() + .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`"); + err.span_suggestion( + sp, + "try exporting the macro", + "#[macro_export]".to_owned(), + Applicability::MaybeIncorrect // speculative + ); + err + } else { + let mut err = self.diagnostic() + .struct_span_err(sp, "can't qualify macro invocation with `pub`"); + err.help("try adjusting the macro to put `pub` inside the invocation"); + err + }; + err.emit(); + } + } + } + + fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span) + -> DiagnosticBuilder<'a> + { + let expected_kinds = if item_type == "extern" { + "missing `fn`, `type`, or `static`" + } else { + "missing `fn`, `type`, or `const`" + }; + + // Given this code `path(`, it seems like this is not + // setting the visibility of a macro invocation, but rather + // a mistyped method declaration. + // Create a diagnostic pointing out that `fn` is missing. + // + // x | pub path(&self) { + // | ^ missing `fn`, `type`, or `const` + // pub path( + // ^^ `sp` below will point to this + let sp = prev_span.between(self.prev_span); + let mut err = self.diagnostic().struct_span_err( + sp, + &format!("{} for {}-item declaration", + expected_kinds, item_type)); + err.span_label(sp, expected_kinds); + err + } + + /// Parse a method or a macro invocation in a trait impl. + fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool) + -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics, + ast::ImplItemKind)> { + // code copied from parse_macro_use_or_failure... abstraction! + if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? { + // method macro + Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(), + ast::ImplItemKind::Macro(mac))) + } else { + let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?; + let ident = self.parse_ident()?; + let mut generics = self.parse_generics()?; + let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?; + generics.where_clause = self.parse_where_clause()?; + *at_end = true; + let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; + let header = ast::FnHeader { abi, unsafety, constness, asyncness }; + Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method( + ast::MethodSig { header, decl }, + body + ))) + } + } + + /// Parses `trait Foo { ... }` or `trait Foo = Bar;`. + fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> { + let ident = self.parse_ident()?; + let mut tps = self.parse_generics()?; + + // Parse optional colon and supertrait bounds. + let bounds = if self.eat(&token::Colon) { + self.parse_generic_bounds(Some(self.prev_span))? + } else { + Vec::new() + }; + + if self.eat(&token::Eq) { + // it's a trait alias + let bounds = self.parse_generic_bounds(None)?; + tps.where_clause = self.parse_where_clause()?; + self.expect(&token::Semi)?; + if is_auto == IsAuto::Yes { + let msg = "trait aliases cannot be `auto`"; + self.struct_span_err(self.prev_span, msg) + .span_label(self.prev_span, msg) + .emit(); + } + if unsafety != Unsafety::Normal { + let msg = "trait aliases cannot be `unsafe`"; + self.struct_span_err(self.prev_span, msg) + .span_label(self.prev_span, msg) + .emit(); + } + Ok((ident, ItemKind::TraitAlias(tps, bounds), None)) + } else { + // it's a normal trait + tps.where_clause = self.parse_where_clause()?; + self.expect(&token::OpenDelim(token::Brace))?; + let mut trait_items = vec![]; + while !self.eat(&token::CloseDelim(token::Brace)) { + let mut at_end = false; + match self.parse_trait_item(&mut at_end) { + Ok(item) => trait_items.push(item), + Err(mut e) => { + e.emit(); + if !at_end { + self.recover_stmt_(SemiColonMode::Break, BlockMode::Break); + } + } + } + } + Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None)) + } + } + + fn choose_generics_over_qpath(&self) -> bool { + // There's an ambiguity between generic parameters and qualified paths in impls. + // If we see `<` it may start both, so we have to inspect some following tokens. + // The following combinations can only start generics, + // but not qualified paths (with one exception): + // `<` `>` - empty generic parameters + // `<` `#` - generic parameters with attributes + // `<` (LIFETIME|IDENT) `>` - single generic parameter + // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list + // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds + // `<` (LIFETIME|IDENT) `=` - generic parameter with a default + // `<` const - generic const parameter + // The only truly ambiguous case is + // `<` IDENT `>` `::` IDENT ... + // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`) + // because this is what almost always expected in practice, qualified paths in impls + // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment. + self.token == token::Lt && + (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) || + self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) && + self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma || + t == &token::Colon || t == &token::Eq) || + self.look_ahead(1, |t| t.is_keyword(keywords::Const))) + } + + fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> { + self.expect(&token::OpenDelim(token::Brace))?; + let attrs = self.parse_inner_attributes()?; + + let mut impl_items = Vec::new(); + while !self.eat(&token::CloseDelim(token::Brace)) { + let mut at_end = false; + match self.parse_impl_item(&mut at_end) { + Ok(impl_item) => impl_items.push(impl_item), + Err(mut err) => { + err.emit(); + if !at_end { + self.recover_stmt_(SemiColonMode::Break, BlockMode::Break); + } + } + } + } + Ok((impl_items, attrs)) + } + + /// Parses an implementation item, `impl` keyword is already parsed. + /// + /// impl<'a, T> TYPE { /* impl items */ } + /// impl<'a, T> TRAIT for TYPE { /* impl items */ } + /// impl<'a, T> !TRAIT for TYPE { /* impl items */ } + /// + /// We actually parse slightly more relaxed grammar for better error reporting and recovery. + /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}` + /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}` + fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness) + -> PResult<'a, ItemInfo> { + // First, parse generic parameters if necessary. + let mut generics = if self.choose_generics_over_qpath() { + self.parse_generics()? + } else { + ast::Generics::default() + }; + + // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type. + let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) { + self.bump(); // `!` + ast::ImplPolarity::Negative + } else { + ast::ImplPolarity::Positive + }; + + // Parse both types and traits as a type, then reinterpret if necessary. + let ty_first = self.parse_ty()?; + + // If `for` is missing we try to recover. + let has_for = self.eat_keyword(keywords::For); + let missing_for_span = self.prev_span.between(self.span); + + let ty_second = if self.token == token::DotDot { + // We need to report this error after `cfg` expansion for compatibility reasons + self.bump(); // `..`, do not add it to expected tokens + Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID })) + } else if has_for || self.token.can_begin_type() { + Some(self.parse_ty()?) + } else { + None + }; + + generics.where_clause = self.parse_where_clause()?; + + let (impl_items, attrs) = self.parse_impl_body()?; + + let item_kind = match ty_second { + Some(ty_second) => { + // impl Trait for Type + if !has_for { + self.struct_span_err(missing_for_span, "missing `for` in a trait impl") + .span_suggestion_short( + missing_for_span, + "add `for` here", + " for ".to_string(), + Applicability::MachineApplicable, + ).emit(); + } + + let ty_first = ty_first.into_inner(); + let path = match ty_first.node { + // This notably includes paths passed through `ty` macro fragments (#46438). + TyKind::Path(None, path) => path, + _ => { + self.span_err(ty_first.span, "expected a trait, found type"); + ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span)) + } + }; + let trait_ref = TraitRef { path, ref_id: ty_first.id }; + + ItemKind::Impl(unsafety, polarity, defaultness, + generics, Some(trait_ref), ty_second, impl_items) + } + None => { + // impl Type + ItemKind::Impl(unsafety, polarity, defaultness, + generics, None, ty_first, impl_items) + } + }; + + Ok((keywords::Invalid.ident(), item_kind, Some(attrs))) + } + + fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> { + if self.eat_keyword(keywords::For) { + self.expect_lt()?; + let params = self.parse_generic_params()?; + self.expect_gt()?; + // We rely on AST validation to rule out invalid cases: There must not be type + // parameters, and the lifetime parameters must not have bounds. + Ok(params) + } else { + Ok(Vec::new()) + } + } + + /// Parses `struct Foo { ... }`. + fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> { + let class_name = self.parse_ident()?; + + let mut generics = self.parse_generics()?; + + // There is a special case worth noting here, as reported in issue #17904. + // If we are parsing a tuple struct it is the case that the where clause + // should follow the field list. Like so: + // + // struct Foo<T>(T) where T: Copy; + // + // If we are parsing a normal record-style struct it is the case + // that the where clause comes before the body, and after the generics. + // So if we look ahead and see a brace or a where-clause we begin + // parsing a record style struct. + // + // Otherwise if we look ahead and see a paren we parse a tuple-style + // struct. + + let vdata = if self.token.is_keyword(keywords::Where) { + generics.where_clause = self.parse_where_clause()?; + if self.eat(&token::Semi) { + // If we see a: `struct Foo<T> where T: Copy;` style decl. + VariantData::Unit(ast::DUMMY_NODE_ID) + } else { + // If we see: `struct Foo<T> where T: Copy { ... }` + VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID) + } + // No `where` so: `struct Foo<T>;` + } else if self.eat(&token::Semi) { + VariantData::Unit(ast::DUMMY_NODE_ID) + // Record-style struct definition + } else if self.token == token::OpenDelim(token::Brace) { + VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID) + // Tuple-style struct definition with optional where-clause. + } else if self.token == token::OpenDelim(token::Paren) { + let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID); + generics.where_clause = self.parse_where_clause()?; + self.expect(&token::Semi)?; + body + } else { + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!( + "expected `where`, `{{`, `(`, or `;` after struct name, found {}", + token_str + )); + err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name"); + return Err(err); + }; + + Ok((class_name, ItemKind::Struct(vdata, generics), None)) + } + + /// Parses `union Foo { ... }`. + fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> { + let class_name = self.parse_ident()?; + + let mut generics = self.parse_generics()?; + + let vdata = if self.token.is_keyword(keywords::Where) { + generics.where_clause = self.parse_where_clause()?; + VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID) + } else if self.token == token::OpenDelim(token::Brace) { + VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID) + } else { + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!( + "expected `where` or `{{` after union name, found {}", token_str)); + err.span_label(self.span, "expected `where` or `{` after union name"); + return Err(err); + }; + + Ok((class_name, ItemKind::Union(vdata, generics), None)) + } + + fn consume_block(&mut self, delim: token::DelimToken) { + let mut brace_depth = 0; + loop { + if self.eat(&token::OpenDelim(delim)) { + brace_depth += 1; + } else if self.eat(&token::CloseDelim(delim)) { + if brace_depth == 0 { + return; + } else { + brace_depth -= 1; + continue; + } + } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) { + return; + } else { + self.bump(); + } + } + } + + fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> { + let mut fields = Vec::new(); + if self.eat(&token::OpenDelim(token::Brace)) { + while self.token != token::CloseDelim(token::Brace) { + let field = self.parse_struct_decl_field().map_err(|e| { + self.recover_stmt(); + e + }); + match field { + Ok(field) => fields.push(field), + Err(mut err) => { + err.emit(); + } + } + } + self.eat(&token::CloseDelim(token::Brace)); + } else { + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!( + "expected `where`, or `{{` after struct name, found {}", token_str)); + err.span_label(self.span, "expected `where`, or `{` after struct name"); + return Err(err); + } + + Ok(fields) + } + + fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> { + // This is the case where we find `struct Foo<T>(T) where T: Copy;` + // Unit like structs are handled in parse_item_struct function + let fields = self.parse_unspanned_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + SeqSep::trailing_allowed(token::Comma), + |p| { + let attrs = p.parse_outer_attributes()?; + let lo = p.span; + let vis = p.parse_visibility(true)?; + let ty = p.parse_ty()?; + Ok(StructField { + span: lo.to(ty.span), + vis, + ident: None, + id: ast::DUMMY_NODE_ID, + ty, + attrs, + }) + })?; + + Ok(fields) + } + + /// Parses a structure field declaration. + fn parse_single_struct_field(&mut self, + lo: Span, + vis: Visibility, + attrs: Vec<Attribute> ) + -> PResult<'a, StructField> { + let mut seen_comma: bool = false; + let a_var = self.parse_name_and_ty(lo, vis, attrs)?; + if self.token == token::Comma { + seen_comma = true; + } + match self.token { + token::Comma => { + self.bump(); + } + token::CloseDelim(token::Brace) => {} + token::DocComment(_) => { + let previous_span = self.prev_span; + let mut err = self.span_fatal_err(self.span, Error::UselessDocComment); + self.bump(); // consume the doc comment + let comma_after_doc_seen = self.eat(&token::Comma); + // `seen_comma` is always false, because we are inside doc block + // condition is here to make code more readable + if seen_comma == false && comma_after_doc_seen == true { + seen_comma = true; + } + if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) { + err.emit(); + } else { + if seen_comma == false { + let sp = self.sess.source_map().next_point(previous_span); + err.span_suggestion( + sp, + "missing comma here", + ",".into(), + Applicability::MachineApplicable + ); + } + return Err(err); + } + } + _ => { + let sp = self.sess.source_map().next_point(self.prev_span); + let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}", + self.this_token_descr())); + if self.token.is_ident() { + // This is likely another field; emit the diagnostic and keep going + err.span_suggestion( + sp, + "try adding a comma", + ",".into(), + Applicability::MachineApplicable, + ); + err.emit(); + } else { + return Err(err) + } + } + } + Ok(a_var) + } + + /// Parses an element of a struct declaration. + fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> { + let attrs = self.parse_outer_attributes()?; + let lo = self.span; + let vis = self.parse_visibility(false)?; + self.parse_single_struct_field(lo, vis, attrs) + } + + /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, + /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. + /// If the following element can't be a tuple (i.e., it's a function definition), then + /// it's not a tuple struct field), and the contents within the parentheses isn't valid, + /// so emit a proper diagnostic. + pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> { + maybe_whole!(self, NtVis, |x| x); + + self.expected_tokens.push(TokenType::Keyword(keywords::Crate)); + if self.is_crate_vis() { + self.bump(); // `crate` + return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate))); + } + + if !self.eat_keyword(keywords::Pub) { + // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no + // keyword to grab a span from for inherited visibility; an empty span at the + // beginning of the current token would seem to be the "Schelling span". + return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited)) + } + let lo = self.prev_span; + + if self.check(&token::OpenDelim(token::Paren)) { + // We don't `self.bump()` the `(` yet because this might be a struct definition where + // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. + // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so + // by the following tokens. + if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) { + // `pub(crate)` + self.bump(); // `(` + self.bump(); // `crate` + self.expect(&token::CloseDelim(token::Paren))?; // `)` + let vis = respan( + lo.to(self.prev_span), + VisibilityKind::Crate(CrateSugar::PubCrate), + ); + return Ok(vis) + } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) { + // `pub(in path)` + self.bump(); // `(` + self.bump(); // `in` + let path = self.parse_path(PathStyle::Mod)?; // `path` + self.expect(&token::CloseDelim(token::Paren))?; // `)` + let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted { + path: P(path), + id: ast::DUMMY_NODE_ID, + }); + return Ok(vis) + } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) && + self.look_ahead(1, |t| t.is_keyword(keywords::Super) || + t.is_keyword(keywords::SelfLower)) + { + // `pub(self)` or `pub(super)` + self.bump(); // `(` + let path = self.parse_path(PathStyle::Mod)?; // `super`/`self` + self.expect(&token::CloseDelim(token::Paren))?; // `)` + let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted { + path: P(path), + id: ast::DUMMY_NODE_ID, + }); + return Ok(vis) + } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct + // `pub(something) fn ...` or `struct X { pub(something) y: Z }` + self.bump(); // `(` + let msg = "incorrect visibility restriction"; + let suggestion = r##"some possible visibility restrictions are: +`pub(crate)`: visible only on the current crate +`pub(super)`: visible only in the current module's parent +`pub(in path::to::module)`: visible only on the specified path"##; + let path = self.parse_path(PathStyle::Mod)?; + let sp = self.prev_span; + let help_msg = format!("make this visible only to module `{}` with `in`", path); + self.expect(&token::CloseDelim(token::Paren))?; // `)` + let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg); + err.help(suggestion); + err.span_suggestion( + sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable + ); + err.emit(); // emit diagnostic, but continue with public visibility + } + } + + Ok(respan(lo, VisibilityKind::Public)) + } + + /// Parses defaultness (i.e., `default` or nothing). + fn parse_defaultness(&mut self) -> Defaultness { + // `pub` is included for better error messages + if self.check_keyword(keywords::Default) && + self.look_ahead(1, |t| t.is_keyword(keywords::Impl) || + t.is_keyword(keywords::Const) || + t.is_keyword(keywords::Fn) || + t.is_keyword(keywords::Unsafe) || + t.is_keyword(keywords::Extern) || + t.is_keyword(keywords::Type) || + t.is_keyword(keywords::Pub)) { + self.bump(); // `default` + Defaultness::Default + } else { + Defaultness::Final + } + } + + fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool { + if self.eat(&token::Semi) { + let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`"); + err.span_suggestion_short( + self.prev_span, + "remove this semicolon", + String::new(), + Applicability::MachineApplicable, + ); + if !items.is_empty() { + let previous_item = &items[items.len()-1]; + let previous_item_kind_name = match previous_item.node { + // say "braced struct" because tuple-structs and + // braceless-empty-struct declarations do take a semicolon + ItemKind::Struct(..) => Some("braced struct"), + ItemKind::Enum(..) => Some("enum"), + ItemKind::Trait(..) => Some("trait"), + ItemKind::Union(..) => Some("union"), + _ => None, + }; + if let Some(name) = previous_item_kind_name { + err.help(&format!("{} declarations are not followed by a semicolon", name)); + } + } + err.emit(); + true + } else { + false + } + } + + /// Given a termination token, parses all of the items in a module. + fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> { + let mut items = vec![]; + while let Some(item) = self.parse_item()? { + items.push(item); + self.maybe_consume_incorrect_semicolon(&items); + } + + if !self.eat(term) { + let token_str = self.this_token_descr(); + if !self.maybe_consume_incorrect_semicolon(&items) { + let mut err = self.fatal(&format!("expected item, found {}", token_str)); + err.span_label(self.span, "expected item"); + return Err(err); + } + } + + let hi = if self.span.is_dummy() { + inner_lo + } else { + self.prev_span + }; + + Ok(ast::Mod { + inner: inner_lo.to(hi), + items, + inline: true + }) + } + + fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> { + let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + self.expect(&token::Eq)?; + let e = self.parse_expr()?; + self.expect(&token::Semi)?; + let item = match m { + Some(m) => ItemKind::Static(ty, m, e), + None => ItemKind::Const(ty, e), + }; + Ok((id, item, None)) + } + + /// Parse a `mod <foo> { ... }` or `mod <foo>;` item + fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> { + let (in_cfg, outer_attrs) = { + let mut strip_unconfigured = crate::config::StripUnconfigured { + sess: self.sess, + features: None, // don't perform gated feature checking + }; + let mut outer_attrs = outer_attrs.to_owned(); + strip_unconfigured.process_cfg_attrs(&mut outer_attrs); + (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs) + }; + + let id_span = self.span; + let id = self.parse_ident()?; + if self.eat(&token::Semi) { + if in_cfg && self.recurse_into_file_modules { + // This mod is in an external file. Let's go get it! + let ModulePathSuccess { path, directory_ownership, warn } = + self.submod_path(id, &outer_attrs, id_span)?; + let (module, mut attrs) = + self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?; + // Record that we fetched the mod from an external file + if warn { + let attr = Attribute { + id: attr::mk_attr_id(), + style: ast::AttrStyle::Outer, + path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")), + tokens: TokenStream::empty(), + is_sugared_doc: false, + span: syntax_pos::DUMMY_SP, + }; + attr::mark_known(&attr); + attrs.push(attr); + } + Ok((id, ItemKind::Mod(module), Some(attrs))) + } else { + let placeholder = ast::Mod { + inner: syntax_pos::DUMMY_SP, + items: Vec::new(), + inline: false + }; + Ok((id, ItemKind::Mod(placeholder), None)) + } + } else { + let old_directory = self.directory.clone(); + self.push_directory(id, &outer_attrs); + + self.expect(&token::OpenDelim(token::Brace))?; + let mod_inner_lo = self.span; + let attrs = self.parse_inner_attributes()?; + let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?; + + self.directory = old_directory; + Ok((id, ItemKind::Mod(module), Some(attrs))) + } + } + + fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) { + if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") { + self.directory.path.to_mut().push(&path.as_str()); + self.directory.ownership = DirectoryOwnership::Owned { relative: None }; + } else { + // We have to push on the current module name in the case of relative + // paths in order to ensure that any additional module paths from inline + // `mod x { ... }` come after the relative extension. + // + // For example, a `mod z { ... }` inside `x/y.rs` should set the current + // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`. + if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership { + if let Some(ident) = relative.take() { // remove the relative offset + self.directory.path.to_mut().push(ident.as_str()); + } + } + self.directory.path.to_mut().push(&id.as_str()); + } + } + + pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> { + if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") { + let s = s.as_str(); + + // On windows, the base path might have the form + // `\\?\foo\bar` in which case it does not tolerate + // mixed `/` and `\` separators, so canonicalize + // `/` to `\`. + #[cfg(windows)] + let s = s.replace("/", "\\"); + Some(dir_path.join(s)) + } else { + None + } + } + + /// Returns a path to a module. + pub fn default_submod_path( + id: ast::Ident, + relative: Option<ast::Ident>, + dir_path: &Path, + source_map: &SourceMap) -> ModulePath + { + // If we're in a foo.rs file instead of a mod.rs file, + // we need to look for submodules in + // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than + // `./<id>.rs` and `./<id>/mod.rs`. + let relative_prefix_string; + let relative_prefix = if let Some(ident) = relative { + relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR); + &relative_prefix_string + } else { + "" + }; + + let mod_name = id.to_string(); + let default_path_str = format!("{}{}.rs", relative_prefix, mod_name); + let secondary_path_str = format!("{}{}{}mod.rs", + relative_prefix, mod_name, path::MAIN_SEPARATOR); + let default_path = dir_path.join(&default_path_str); + let secondary_path = dir_path.join(&secondary_path_str); + let default_exists = source_map.file_exists(&default_path); + let secondary_exists = source_map.file_exists(&secondary_path); + + let result = match (default_exists, secondary_exists) { + (true, false) => Ok(ModulePathSuccess { + path: default_path, + directory_ownership: DirectoryOwnership::Owned { + relative: Some(id), + }, + warn: false, + }), + (false, true) => Ok(ModulePathSuccess { + path: secondary_path, + directory_ownership: DirectoryOwnership::Owned { + relative: None, + }, + warn: false, + }), + (false, false) => Err(Error::FileNotFoundForModule { + mod_name: mod_name.clone(), + default_path: default_path_str, + secondary_path: secondary_path_str, + dir_path: dir_path.display().to_string(), + }), + (true, true) => Err(Error::DuplicatePaths { + mod_name: mod_name.clone(), + default_path: default_path_str, + secondary_path: secondary_path_str, + }), + }; + + ModulePath { + name: mod_name, + path_exists: default_exists || secondary_exists, + result, + } + } + + fn submod_path(&mut self, + id: ast::Ident, + outer_attrs: &[Attribute], + id_sp: Span) + -> PResult<'a, ModulePathSuccess> { + if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) { + return Ok(ModulePathSuccess { + directory_ownership: match path.file_name().and_then(|s| s.to_str()) { + // All `#[path]` files are treated as though they are a `mod.rs` file. + // This means that `mod foo;` declarations inside `#[path]`-included + // files are siblings, + // + // Note that this will produce weirdness when a file named `foo.rs` is + // `#[path]` included and contains a `mod foo;` declaration. + // If you encounter this, it's your own darn fault :P + Some(_) => DirectoryOwnership::Owned { relative: None }, + _ => DirectoryOwnership::UnownedViaMod(true), + }, + path, + warn: false, + }); + } + + let relative = match self.directory.ownership { + DirectoryOwnership::Owned { relative } => relative, + DirectoryOwnership::UnownedViaBlock | + DirectoryOwnership::UnownedViaMod(_) => None, + }; + let paths = Parser::default_submod_path( + id, relative, &self.directory.path, self.sess.source_map()); + + match self.directory.ownership { + DirectoryOwnership::Owned { .. } => { + paths.result.map_err(|err| self.span_fatal_err(id_sp, err)) + }, + DirectoryOwnership::UnownedViaBlock => { + let msg = + "Cannot declare a non-inline module inside a block \ + unless it has a path attribute"; + let mut err = self.diagnostic().struct_span_err(id_sp, msg); + if paths.path_exists { + let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", + paths.name); + err.span_note(id_sp, &msg); + } + Err(err) + } + DirectoryOwnership::UnownedViaMod(warn) => { + if warn { + if let Ok(result) = paths.result { + return Ok(ModulePathSuccess { warn: true, ..result }); + } + } + let mut err = self.diagnostic().struct_span_err(id_sp, + "cannot declare a new module at this location"); + if !id_sp.is_dummy() { + let src_path = self.sess.source_map().span_to_filename(id_sp); + if let FileName::Real(src_path) = src_path { + if let Some(stem) = src_path.file_stem() { + let mut dest_path = src_path.clone(); + dest_path.set_file_name(stem); + dest_path.push("mod.rs"); + err.span_note(id_sp, + &format!("maybe move this module `{}` to its own \ + directory via `{}`", src_path.display(), + dest_path.display())); + } + } + } + if paths.path_exists { + err.span_note(id_sp, + &format!("... or maybe `use` the module `{}` instead \ + of possibly redeclaring it", + paths.name)); + } + Err(err) + } + } + } + + /// Reads a module from a source file. + fn eval_src_mod(&mut self, + path: PathBuf, + directory_ownership: DirectoryOwnership, + name: String, + id_sp: Span) + -> PResult<'a, (ast::Mod, Vec<Attribute> )> { + let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut(); + if let Some(i) = included_mod_stack.iter().position(|p| *p == path) { + let mut err = String::from("circular modules: "); + let len = included_mod_stack.len(); + for p in &included_mod_stack[i.. len] { + err.push_str(&p.to_string_lossy()); + err.push_str(" -> "); + } + err.push_str(&path.to_string_lossy()); + return Err(self.span_fatal(id_sp, &err[..])); + } + included_mod_stack.push(path.clone()); + drop(included_mod_stack); + + let mut p0 = + new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp); + p0.cfg_mods = self.cfg_mods; + let mod_inner_lo = p0.span; + let mod_attrs = p0.parse_inner_attributes()?; + let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?; + m0.inline = false; + self.sess.included_mod_stack.borrow_mut().pop(); + Ok((m0, mod_attrs)) + } + + /// Parses a function declaration from a foreign module. + fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) + -> PResult<'a, ForeignItem> { + self.expect_keyword(keywords::Fn)?; + + let (ident, mut generics) = self.parse_fn_header()?; + let decl = self.parse_fn_decl(true)?; + generics.where_clause = self.parse_where_clause()?; + let hi = self.span; + self.expect(&token::Semi)?; + Ok(ast::ForeignItem { + ident, + attrs, + node: ForeignItemKind::Fn(decl, generics), + id: ast::DUMMY_NODE_ID, + span: lo.to(hi), + vis, + }) + } + + /// Parses a static item from a foreign module. + /// Assumes that the `static` keyword is already parsed. + fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) + -> PResult<'a, ForeignItem> { + let mutbl = self.eat_keyword(keywords::Mut); + let ident = self.parse_ident()?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + let hi = self.span; + self.expect(&token::Semi)?; + Ok(ForeignItem { + ident, + attrs, + node: ForeignItemKind::Static(ty, mutbl), + id: ast::DUMMY_NODE_ID, + span: lo.to(hi), + vis, + }) + } + + /// Parses a type from a foreign module. + fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) + -> PResult<'a, ForeignItem> { + self.expect_keyword(keywords::Type)?; + + let ident = self.parse_ident()?; + let hi = self.span; + self.expect(&token::Semi)?; + Ok(ast::ForeignItem { + ident: ident, + attrs: attrs, + node: ForeignItemKind::Ty, + id: ast::DUMMY_NODE_ID, + span: lo.to(hi), + vis: vis + }) + } + + fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> { + let error_msg = "crate name using dashes are not valid in `extern crate` statements"; + let suggestion_msg = "if the original crate name uses dashes you need to use underscores \ + in the code"; + let mut ident = if self.token.is_keyword(keywords::SelfLower) { + self.parse_path_segment_ident() + } else { + self.parse_ident() + }?; + let mut idents = vec![]; + let mut replacement = vec![]; + let mut fixed_crate_name = false; + // Accept `extern crate name-like-this` for better diagnostics + let dash = token::Token::BinOp(token::BinOpToken::Minus); + if self.token == dash { // Do not include `-` as part of the expected tokens list + while self.eat(&dash) { + fixed_crate_name = true; + replacement.push((self.prev_span, "_".to_string())); + idents.push(self.parse_ident()?); + } + } + if fixed_crate_name { + let fixed_name_sp = ident.span.to(idents.last().unwrap().span); + let mut fixed_name = format!("{}", ident.name); + for part in idents { + fixed_name.push_str(&format!("_{}", part.name)); + } + ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp); + + let mut err = self.struct_span_err(fixed_name_sp, error_msg); + err.span_label(fixed_name_sp, "dash-separated idents are not valid"); + err.multipart_suggestion( + suggestion_msg, + replacement, + Applicability::MachineApplicable, + ); + err.emit(); + } + Ok(ident) + } + + /// Parses `extern crate` links. + /// + /// # Examples + /// + /// ``` + /// extern crate foo; + /// extern crate bar as foo; + /// ``` + fn parse_item_extern_crate(&mut self, + lo: Span, + visibility: Visibility, + attrs: Vec<Attribute>) + -> PResult<'a, P<Item>> { + // Accept `extern crate name-like-this` for better diagnostics + let orig_name = self.parse_crate_name_with_dashes()?; + let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? { + (rename, Some(orig_name.name)) + } else { + (orig_name, None) + }; + self.expect(&token::Semi)?; + + let span = lo.to(self.prev_span); + Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs)) + } + + /// Parses `extern` for foreign ABIs modules. + /// + /// `extern` is expected to have been + /// consumed before calling this method. + /// + /// # Examples + /// + /// ```ignore (only-for-syntax-highlight) + /// extern "C" {} + /// extern {} + /// ``` + fn parse_item_foreign_mod(&mut self, + lo: Span, + opt_abi: Option<Abi>, + visibility: Visibility, + mut attrs: Vec<Attribute>) + -> PResult<'a, P<Item>> { + self.expect(&token::OpenDelim(token::Brace))?; + + let abi = opt_abi.unwrap_or(Abi::C); + + attrs.extend(self.parse_inner_attributes()?); + + let mut foreign_items = vec![]; + while !self.eat(&token::CloseDelim(token::Brace)) { + foreign_items.push(self.parse_foreign_item()?); + } + + let prev_span = self.prev_span; + let m = ast::ForeignMod { + abi, + items: foreign_items + }; + let invalid = keywords::Invalid.ident(); + Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs)) + } + + /// Parses `type Foo = Bar;` + /// or + /// `existential type Foo: Bar;` + /// or + /// `return `None`` + /// without modifying the parser state. + fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> { + // This parses the grammar: + // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";" + if self.check_keyword(keywords::Type) || + self.check_keyword(keywords::Existential) && + self.look_ahead(1, |t| t.is_keyword(keywords::Type)) { + let existential = self.eat_keyword(keywords::Existential); + assert!(self.eat_keyword(keywords::Type)); + Some(self.parse_existential_or_alias(existential)) + } else { + None + } + } + + /// Parses a type alias or existential type. + fn parse_existential_or_alias( + &mut self, + existential: bool, + ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> { + let ident = self.parse_ident()?; + let mut tps = self.parse_generics()?; + tps.where_clause = self.parse_where_clause()?; + let alias = if existential { + self.expect(&token::Colon)?; + let bounds = self.parse_generic_bounds(None)?; + AliasKind::Existential(bounds) + } else { + self.expect(&token::Eq)?; + let ty = self.parse_ty()?; + AliasKind::Weak(ty) + }; + self.expect(&token::Semi)?; + Ok((ident, alias, tps)) + } + + /// Parses the part of an enum declaration following the `{`. + fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> { + let mut variants = Vec::new(); + let mut all_nullary = true; + let mut any_disr = vec![]; + while self.token != token::CloseDelim(token::Brace) { + let variant_attrs = self.parse_outer_attributes()?; + let vlo = self.span; + + let struct_def; + let mut disr_expr = None; + let ident = self.parse_ident()?; + if self.check(&token::OpenDelim(token::Brace)) { + // Parse a struct variant. + all_nullary = false; + struct_def = VariantData::Struct(self.parse_record_struct_body()?, + ast::DUMMY_NODE_ID); + } else if self.check(&token::OpenDelim(token::Paren)) { + all_nullary = false; + struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?, + ast::DUMMY_NODE_ID); + } else if self.eat(&token::Eq) { + disr_expr = Some(AnonConst { + id: ast::DUMMY_NODE_ID, + value: self.parse_expr()?, + }); + if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) { + any_disr.push(sp); + } + struct_def = VariantData::Unit(ast::DUMMY_NODE_ID); + } else { + struct_def = VariantData::Unit(ast::DUMMY_NODE_ID); + } + + let vr = ast::Variant_ { + ident, + attrs: variant_attrs, + data: struct_def, + disr_expr, + }; + variants.push(respan(vlo.to(self.prev_span), vr)); + + if !self.eat(&token::Comma) { break; } + } + self.expect(&token::CloseDelim(token::Brace))?; + if !any_disr.is_empty() && !all_nullary { + let mut err =self.struct_span_err( + any_disr.clone(), + "discriminator values can only be used with a field-less enum", + ); + for sp in any_disr { + err.span_label(sp, "only valid in field-less enums"); + } + err.emit(); + } + + Ok(ast::EnumDef { variants }) + } + + /// Parses an enum declaration. + fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> { + let id = self.parse_ident()?; + let mut generics = self.parse_generics()?; + generics.where_clause = self.parse_where_clause()?; + self.expect(&token::OpenDelim(token::Brace))?; + + let enum_definition = self.parse_enum_def(&generics).map_err(|e| { + self.recover_stmt(); + self.eat(&token::CloseDelim(token::Brace)); + e + })?; + Ok((id, ItemKind::Enum(enum_definition, generics), None)) + } + + /// Parses a string as an ABI spec on an extern type or module. Consumes + /// the `extern` keyword, if one is found. + fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> { + match self.token { + token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => { + let sp = self.span; + self.expect_no_suffix(sp, "ABI spec", suf); + self.bump(); + match abi::lookup(&s.as_str()) { + Some(abi) => Ok(Some(abi)), + None => { + let prev_span = self.prev_span; + let mut err = struct_span_err!( + self.sess.span_diagnostic, + prev_span, + E0703, + "invalid ABI: found `{}`", + s); + err.span_label(prev_span, "invalid ABI"); + err.help(&format!("valid ABIs: {}", abi::all_names().join(", "))); + err.emit(); + Ok(None) + } + } + } + + _ => Ok(None), + } + } + + fn is_static_global(&mut self) -> bool { + if self.check_keyword(keywords::Static) { + // Check if this could be a closure + !self.look_ahead(1, |token| { + if token.is_keyword(keywords::Move) { + return true; + } + match *token { + token::BinOp(token::Or) | token::OrOr => true, + _ => false, + } + }) + } else { + false + } + } + + fn parse_item_( + &mut self, + attrs: Vec<Attribute>, + macros_allowed: bool, + attributes_allowed: bool, + ) -> PResult<'a, Option<P<Item>>> { + let (ret, tokens) = self.collect_tokens(|this| { + this.parse_item_implementation(attrs, macros_allowed, attributes_allowed) + })?; + + // Once we've parsed an item and recorded the tokens we got while + // parsing we may want to store `tokens` into the item we're about to + // return. Note, though, that we specifically didn't capture tokens + // related to outer attributes. The `tokens` field here may later be + // used with procedural macros to convert this item back into a token + // stream, but during expansion we may be removing attributes as we go + // along. + // + // If we've got inner attributes then the `tokens` we've got above holds + // these inner attributes. If an inner attribute is expanded we won't + // actually remove it from the token stream, so we'll just keep yielding + // it (bad!). To work around this case for now we just avoid recording + // `tokens` if we detect any inner attributes. This should help keep + // expansion correct, but we should fix this bug one day! + Ok(ret.map(|item| { + item.map(|mut i| { + if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) { + i.tokens = Some(tokens); + } + i + }) + })) + } + + /// Parses one of the items allowed by the flags. + fn parse_item_implementation( + &mut self, + attrs: Vec<Attribute>, + macros_allowed: bool, + attributes_allowed: bool, + ) -> PResult<'a, Option<P<Item>>> { + maybe_whole!(self, NtItem, |item| { + let mut item = item.into_inner(); + let mut attrs = attrs; + mem::swap(&mut item.attrs, &mut attrs); + item.attrs.extend(attrs); + Some(P(item)) + }); + + let lo = self.span; + + let visibility = self.parse_visibility(false)?; + + if self.eat_keyword(keywords::Use) { + // USE ITEM + let item_ = ItemKind::Use(P(self.parse_use_tree()?)); + self.expect(&token::Semi)?; + + let span = lo.to(self.prev_span); + let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs); + return Ok(Some(item)); + } + + if self.eat_keyword(keywords::Extern) { + if self.eat_keyword(keywords::Crate) { + return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?)); + } + + let opt_abi = self.parse_opt_abi()?; + + if self.eat_keyword(keywords::Fn) { + // EXTERN FUNCTION ITEM + let fn_span = self.prev_span; + let abi = opt_abi.unwrap_or(Abi::C); + let (ident, item_, extra_attrs) = + self.parse_item_fn(Unsafety::Normal, + IsAsync::NotAsync, + respan(fn_span, Constness::NotConst), + abi)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } else if self.check(&token::OpenDelim(token::Brace)) { + return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?)); + } + + self.unexpected()?; + } + + if self.is_static_global() { + self.bump(); + // STATIC ITEM + let m = if self.eat_keyword(keywords::Mut) { + Mutability::Mutable + } else { + Mutability::Immutable + }; + let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Const) { + let const_span = self.prev_span; + if self.check_keyword(keywords::Fn) + || (self.check_keyword(keywords::Unsafe) + && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) { + // CONST FUNCTION ITEM + let unsafety = self.parse_unsafety(); + self.bump(); + let (ident, item_, extra_attrs) = + self.parse_item_fn(unsafety, + IsAsync::NotAsync, + respan(const_span, Constness::Const), + Abi::Rust)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + + // CONST ITEM + if self.eat_keyword(keywords::Mut) { + let prev_span = self.prev_span; + let mut err = self.diagnostic() + .struct_span_err(prev_span, "const globals cannot be mutable"); + err.span_label(prev_span, "cannot be mutable"); + err.span_suggestion( + const_span, + "you might want to declare a static instead", + "static".to_owned(), + Applicability::MaybeIncorrect, + ); + err.emit(); + } + let (ident, item_, extra_attrs) = self.parse_item_const(None)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + + // `unsafe async fn` or `async fn` + if ( + self.check_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Async)) + ) || ( + self.check_keyword(keywords::Async) && + self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) + ) + { + // ASYNC FUNCTION ITEM + let unsafety = self.parse_unsafety(); + self.expect_keyword(keywords::Async)?; + self.expect_keyword(keywords::Fn)?; + let fn_span = self.prev_span; + let (ident, item_, extra_attrs) = + self.parse_item_fn(unsafety, + IsAsync::Async { + closure_id: ast::DUMMY_NODE_ID, + return_impl_trait_id: ast::DUMMY_NODE_ID, + }, + respan(fn_span, Constness::NotConst), + Abi::Rust)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Unsafe) && + (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) || + self.look_ahead(1, |t| t.is_keyword(keywords::Auto))) + { + // UNSAFE TRAIT ITEM + self.bump(); // `unsafe` + let is_auto = if self.eat_keyword(keywords::Trait) { + IsAuto::No + } else { + self.expect_keyword(keywords::Auto)?; + self.expect_keyword(keywords::Trait)?; + IsAuto::Yes + }; + let (ident, item_, extra_attrs) = + self.parse_item_trait(is_auto, Unsafety::Unsafe)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Impl) || + self.check_keyword(keywords::Unsafe) && + self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) || + self.check_keyword(keywords::Default) && + self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) || + self.check_keyword(keywords::Default) && + self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) { + // IMPL ITEM + let defaultness = self.parse_defaultness(); + let unsafety = self.parse_unsafety(); + self.expect_keyword(keywords::Impl)?; + let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?; + let span = lo.to(self.prev_span); + return Ok(Some(self.mk_item(span, ident, item, visibility, + maybe_append(attrs, extra_attrs)))); + } + if self.check_keyword(keywords::Fn) { + // FUNCTION ITEM + self.bump(); + let fn_span = self.prev_span; + let (ident, item_, extra_attrs) = + self.parse_item_fn(Unsafety::Normal, + IsAsync::NotAsync, + respan(fn_span, Constness::NotConst), + Abi::Rust)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Unsafe) + && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) { + // UNSAFE FUNCTION ITEM + self.bump(); // `unsafe` + // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic + self.check(&token::OpenDelim(token::Brace)); + let abi = if self.eat_keyword(keywords::Extern) { + self.parse_opt_abi()?.unwrap_or(Abi::C) + } else { + Abi::Rust + }; + self.expect_keyword(keywords::Fn)?; + let fn_span = self.prev_span; + let (ident, item_, extra_attrs) = + self.parse_item_fn(Unsafety::Unsafe, + IsAsync::NotAsync, + respan(fn_span, Constness::NotConst), + abi)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Mod) { + // MODULE ITEM + let (ident, item_, extra_attrs) = + self.parse_item_mod(&attrs[..])?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if let Some(type_) = self.eat_type() { + let (ident, alias, generics) = type_?; + // TYPE ITEM + let item_ = match alias { + AliasKind::Weak(ty) => ItemKind::Ty(ty, generics), + AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics), + }; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + attrs); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Enum) { + // ENUM ITEM + let (ident, item_, extra_attrs) = self.parse_item_enum()?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.check_keyword(keywords::Trait) + || (self.check_keyword(keywords::Auto) + && self.look_ahead(1, |t| t.is_keyword(keywords::Trait))) + { + let is_auto = if self.eat_keyword(keywords::Trait) { + IsAuto::No + } else { + self.expect_keyword(keywords::Auto)?; + self.expect_keyword(keywords::Trait)?; + IsAuto::Yes + }; + // TRAIT ITEM + let (ident, item_, extra_attrs) = + self.parse_item_trait(is_auto, Unsafety::Normal)?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.eat_keyword(keywords::Struct) { + // STRUCT ITEM + let (ident, item_, extra_attrs) = self.parse_item_struct()?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if self.is_union_item() { + // UNION ITEM + self.bump(); + let (ident, item_, extra_attrs) = self.parse_item_union()?; + let prev_span = self.prev_span; + let item = self.mk_item(lo.to(prev_span), + ident, + item_, + visibility, + maybe_append(attrs, extra_attrs)); + return Ok(Some(item)); + } + if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? { + return Ok(Some(macro_def)); + } + + // Verify whether we have encountered a struct or method definition where the user forgot to + // add the `struct` or `fn` keyword after writing `pub`: `pub S {}` + if visibility.node.is_pub() && + self.check_ident() && + self.look_ahead(1, |t| *t != token::Not) + { + // Space between `pub` keyword and the identifier + // + // pub S {} + // ^^^ `sp` points here + let sp = self.prev_span.between(self.span); + let full_sp = self.prev_span.to(self.span); + let ident_sp = self.span; + if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) { + // possible public struct definition where `struct` was forgotten + let ident = self.parse_ident().unwrap(); + let msg = format!("add `struct` here to parse `{}` as a public struct", + ident); + let mut err = self.diagnostic() + .struct_span_err(sp, "missing `struct` for struct definition"); + err.span_suggestion_short( + sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative + ); + return Err(err); + } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) { + let ident = self.parse_ident().unwrap(); + self.bump(); // `(` + let kw_name = if let Ok(Some(_)) = self.parse_self_arg() { + "method" + } else { + "function" + }; + self.consume_block(token::Paren); + let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) { + self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]); + self.bump(); // `{` + ("fn", kw_name, false) + } else if self.check(&token::OpenDelim(token::Brace)) { + self.bump(); // `{` + ("fn", kw_name, false) + } else if self.check(&token::Colon) { + let kw = "struct"; + (kw, kw, false) + } else { + ("fn` or `struct", "function or struct", true) + }; + self.consume_block(token::Brace); + + let msg = format!("missing `{}` for {} definition", kw, kw_name); + let mut err = self.diagnostic().struct_span_err(sp, &msg); + if !ambiguous { + let suggestion = format!("add `{}` here to parse `{}` as a public {}", + kw, + ident, + kw_name); + err.span_suggestion_short( + sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable + ); + } else { + if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) { + err.span_suggestion( + full_sp, + "if you meant to call a macro, try", + format!("{}!", snippet), + // this is the `ambiguous` conditional branch + Applicability::MaybeIncorrect + ); + } else { + err.help("if you meant to call a macro, remove the `pub` \ + and add a trailing `!` after the identifier"); + } + } + return Err(err); + } else if self.look_ahead(1, |t| *t == token::Lt) { + let ident = self.parse_ident().unwrap(); + self.eat_to_tokens(&[&token::Gt]); + self.bump(); // `>` + let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) { + if let Ok(Some(_)) = self.parse_self_arg() { + ("fn", "method", false) + } else { + ("fn", "function", false) + } + } else if self.check(&token::OpenDelim(token::Brace)) { + ("struct", "struct", false) + } else { + ("fn` or `struct", "function or struct", true) + }; + let msg = format!("missing `{}` for {} definition", kw, kw_name); + let mut err = self.diagnostic().struct_span_err(sp, &msg); + if !ambiguous { + err.span_suggestion_short( + sp, + &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name), + format!(" {} ", kw), + Applicability::MachineApplicable, + ); + } + return Err(err); + } + } + self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility) + } + + /// Parses a foreign item. + crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> { + maybe_whole!(self, NtForeignItem, |ni| ni); + + let attrs = self.parse_outer_attributes()?; + let lo = self.span; + let visibility = self.parse_visibility(false)?; + + // FOREIGN STATIC ITEM + // Treat `const` as `static` for error recovery, but don't add it to expected tokens. + if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) { + if self.token.is_keyword(keywords::Const) { + self.diagnostic() + .struct_span_err(self.span, "extern items cannot be `const`") + .span_suggestion( + self.span, + "try using a static value", + "static".to_owned(), + Applicability::MachineApplicable + ).emit(); + } + self.bump(); // `static` or `const` + return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?); + } + // FOREIGN FUNCTION ITEM + if self.check_keyword(keywords::Fn) { + return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?); + } + // FOREIGN TYPE ITEM + if self.check_keyword(keywords::Type) { + return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?); + } + + match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? { + Some(mac) => { + Ok( + ForeignItem { + ident: keywords::Invalid.ident(), + span: lo.to(self.prev_span), + id: ast::DUMMY_NODE_ID, + attrs, + vis: visibility, + node: ForeignItemKind::Macro(mac), + } + ) + } + None => { + if !attrs.is_empty() { + self.expected_item_err(&attrs)?; + } + + self.unexpected() + } + } + } + + /// This is the fall-through for parsing items. + fn parse_macro_use_or_failure( + &mut self, + attrs: Vec<Attribute> , + macros_allowed: bool, + attributes_allowed: bool, + lo: Span, + visibility: Visibility + ) -> PResult<'a, Option<P<Item>>> { + if macros_allowed && self.token.is_path_start() { + // MACRO INVOCATION ITEM + + let prev_span = self.prev_span; + self.complain_if_pub_macro(&visibility.node, prev_span); + + let mac_lo = self.span; + + // item macro. + let pth = self.parse_path(PathStyle::Mod)?; + self.expect(&token::Not)?; + + // a 'special' identifier (like what `macro_rules!` uses) + // is optional. We should eventually unify invoc syntax + // and remove this. + let id = if self.token.is_ident() { + self.parse_ident()? + } else { + keywords::Invalid.ident() // no special identifier + }; + // eat a matched-delimiter token tree: + let (delim, tts) = self.expect_delimited_token_tree()?; + if delim != MacDelimiter::Brace { + if !self.eat(&token::Semi) { + self.span_err(self.prev_span, + "macros that expand to items must either \ + be surrounded with braces or followed by \ + a semicolon"); + } + } + + let hi = self.prev_span; + let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim }); + let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs); + return Ok(Some(item)); + } + + // FAILURE TO PARSE ITEM + match visibility.node { + VisibilityKind::Inherited => {} + _ => { + return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`")); + } + } + + if !attributes_allowed && !attrs.is_empty() { + self.expected_item_err(&attrs)?; + } + Ok(None) + } + + /// Parses a macro invocation inside a `trait`, `impl` or `extern` block. + fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>, + at_end: &mut bool) -> PResult<'a, Option<Mac>> + { + if self.token.is_path_start() { + let prev_span = self.prev_span; + let lo = self.span; + let pth = self.parse_path(PathStyle::Mod)?; + + if pth.segments.len() == 1 { + if !self.eat(&token::Not) { + return Err(self.missing_assoc_item_kind_err(item_kind, prev_span)); + } + } else { + self.expect(&token::Not)?; + } + + if let Some(vis) = vis { + self.complain_if_pub_macro(&vis.node, prev_span); + } + + *at_end = true; + + // eat a matched-delimiter token tree: + let (delim, tts) = self.expect_delimited_token_tree()?; + if delim != MacDelimiter::Brace { + self.expect(&token::Semi)?; + } + + Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim }))) + } else { + Ok(None) + } + } + + fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)> + where F: FnOnce(&mut Self) -> PResult<'a, R> + { + // Record all tokens we parse when parsing this item. + let mut tokens = Vec::new(); + let prev_collecting = match self.token_cursor.frame.last_token { + LastToken::Collecting(ref mut list) => { + Some(mem::replace(list, Vec::new())) + } + LastToken::Was(ref mut last) => { + tokens.extend(last.take()); + None + } + }; + self.token_cursor.frame.last_token = LastToken::Collecting(tokens); + let prev = self.token_cursor.stack.len(); + let ret = f(self); + let last_token = if self.token_cursor.stack.len() == prev { + &mut self.token_cursor.frame.last_token + } else { + &mut self.token_cursor.stack[prev].last_token + }; + + // Pull out the tokens that we've collected from the call to `f` above. + let mut collected_tokens = match *last_token { + LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()), + LastToken::Was(_) => panic!("our vector went away?"), + }; + + // If we're not at EOF our current token wasn't actually consumed by + // `f`, but it'll still be in our list that we pulled out. In that case + // put it back. + let extra_token = if self.token != token::Eof { + collected_tokens.pop() + } else { + None + }; + + // If we were previously collecting tokens, then this was a recursive + // call. In that case we need to record all the tokens we collected in + // our parent list as well. To do that we push a clone of our stream + // onto the previous list. + match prev_collecting { + Some(mut list) => { + list.extend(collected_tokens.iter().cloned()); + list.extend(extra_token); + *last_token = LastToken::Collecting(list); + } + None => { + *last_token = LastToken::Was(extra_token); + } + } + + Ok((ret?, TokenStream::new(collected_tokens))) + } + + pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> { + let attrs = self.parse_outer_attributes()?; + self.parse_item_(attrs, true, false) + } + + /// `::{` or `::*` + fn is_import_coupler(&mut self) -> bool { + self.check(&token::ModSep) && + self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) || + *t == token::BinOp(token::Star)) + } + + /// Parses a `UseTree`. + /// + /// ``` + /// USE_TREE = [`::`] `*` | + /// [`::`] `{` USE_TREE_LIST `}` | + /// PATH `::` `*` | + /// PATH `::` `{` USE_TREE_LIST `}` | + /// PATH [`as` IDENT] + /// ``` + fn parse_use_tree(&mut self) -> PResult<'a, UseTree> { + let lo = self.span; + + let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() }; + let kind = if self.check(&token::OpenDelim(token::Brace)) || + self.check(&token::BinOp(token::Star)) || + self.is_import_coupler() { + // `use *;` or `use ::*;` or `use {...};` or `use ::{...};` + let mod_sep_ctxt = self.span.ctxt(); + if self.eat(&token::ModSep) { + prefix.segments.push( + PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)) + ); + } + + if self.eat(&token::BinOp(token::Star)) { + UseTreeKind::Glob + } else { + UseTreeKind::Nested(self.parse_use_tree_list()?) + } + } else { + // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;` + prefix = self.parse_path(PathStyle::Mod)?; + + if self.eat(&token::ModSep) { + if self.eat(&token::BinOp(token::Star)) { + UseTreeKind::Glob + } else { + UseTreeKind::Nested(self.parse_use_tree_list()?) + } + } else { + UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID) + } + }; + + Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) }) + } + + /// Parses a `UseTreeKind::Nested(list)`. + /// + /// ``` + /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`] + /// ``` + fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> { + self.parse_unspanned_seq(&token::OpenDelim(token::Brace), + &token::CloseDelim(token::Brace), + SeqSep::trailing_allowed(token::Comma), |this| { + Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID)) + }) + } + + fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> { + if self.eat_keyword(keywords::As) { + self.parse_ident_or_underscore().map(Some) + } else { + Ok(None) + } + } + + /// Parses a source module as a crate. This is the main entry point for the parser. + pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> { + let lo = self.span; + let krate = Ok(ast::Crate { + attrs: self.parse_inner_attributes()?, + module: self.parse_mod_items(&token::Eof, lo)?, + span: lo.to(self.span), + }); + emit_unclosed_delims(&self.unclosed_delims, self.diagnostic()); + self.unclosed_delims.clear(); + krate + } + + pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> { + let ret = match self.token { + token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf), + token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf), + _ => return None + }; + self.bump(); + Some(ret) + } + + pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> { + match self.parse_optional_str() { + Some((s, style, suf)) => { + let sp = self.prev_span; + self.expect_no_suffix(sp, "string literal", suf); + Ok((s, style)) + } + _ => { + let msg = "expected string literal"; + let mut err = self.fatal(msg); + err.span_label(self.span, msg); + Err(err) + } + } + } +} + +pub fn emit_unclosed_delims(unclosed_delims: &[UnmatchedBrace], handler: &errors::Handler) { + for unmatched in unclosed_delims { + let mut err = handler.struct_span_err(unmatched.found_span, &format!( + "incorrect close delimiter: `{}`", + pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)), + )); + err.span_label(unmatched.found_span, "incorrect close delimiter"); + if let Some(sp) = unmatched.candidate_span { + err.span_label(sp, "close delimiter possibly meant for this"); + } + if let Some(sp) = unmatched.unclosed_span { + err.span_label(sp, "un-closed delimiter"); + } + err.emit(); + } +} diff --git a/src/tools/rust-analyzer/bench_data/numerous_macro_rules b/src/tools/rust-analyzer/bench_data/numerous_macro_rules new file mode 100644 index 000000000..bf89ed594 --- /dev/null +++ b/src/tools/rust-analyzer/bench_data/numerous_macro_rules @@ -0,0 +1,560 @@ +macro_rules! __ra_macro_fixture0 {($T : ident )=>( int_module ! ($T , # [ stable ( feature = "rust1" , since = "1.0.0" )]);); ($T : ident , # [$attr : meta ])=>( doc_comment ! { concat ! ( "The smallest value that can be represented by this integer type.\nUse [`" , stringify ! ($T ), "::MIN" , "`](../../std/primitive." , stringify ! ($T ), ".html#associatedconstant.MIN) instead.\n\n# Examples\n\n```rust\n// deprecated way\nlet min = std::" , stringify ! ($T ), "::MIN;\n\n// intended way\nlet min = " , stringify ! ($T ), "::MIN;\n```\n" ), # [$attr ] pub const MIN : $T = $T :: MIN ; } doc_comment ! { concat ! ( "The largest value that can be represented by this integer type.\nUse [`" , stringify ! ($T ), "::MAX" , "`](../../std/primitive." , stringify ! ($T ), ".html#associatedconstant.MAX) instead.\n\n# Examples\n\n```rust\n// deprecated way\nlet max = std::" , stringify ! ($T ), "::MAX;\n\n// intended way\nlet max = " , stringify ! ($T ), "::MAX;\n```\n" ), # [$attr ] pub const MAX : $T = $T :: MAX ; })} +macro_rules! __ra_macro_fixture1 {($($ty : ty : add ($addfn : path ), mul / div ($bigty : ident );)*)=>($(impl FullOps for $ty { fn full_add ( self , other : $ty , carry : bool )-> ( bool , $ty ){ let ( v , carry1 )= intrinsics :: add_with_overflow ( self , other ); let ( v , carry2 )= intrinsics :: add_with_overflow ( v , if carry { 1 } else { 0 }); ( carry1 || carry2 , v )} fn full_mul ( self , other : $ty , carry : $ty )-> ($ty , $ty ){ let v = ( self as $bigty )* ( other as $bigty )+ ( carry as $bigty ); (( v >> <$ty >:: BITS ) as $ty , v as $ty )} fn full_mul_add ( self , other : $ty , other2 : $ty , carry : $ty )-> ($ty , $ty ){ let v = ( self as $bigty )* ( other as $bigty )+ ( other2 as $bigty )+ ( carry as $bigty ); (( v >> <$ty >:: BITS ) as $ty , v as $ty )} fn full_div_rem ( self , other : $ty , borrow : $ty )-> ($ty , $ty ){ debug_assert ! ( borrow < other ); let lhs = (( borrow as $bigty )<< <$ty >:: BITS )| ( self as $bigty ); let rhs = other as $bigty ; (( lhs / rhs ) as $ty , ( lhs % rhs ) as $ty )}})* )} +macro_rules! __ra_macro_fixture2 {($name : ident : type =$ty : ty , n =$n : expr )=>{# [ doc = " Stack-allocated arbitrary-precision (up to certain limit) integer." ]# [ doc = "" ]# [ doc = " This is backed by a fixed-size array of given type (\\\"digit\\\")." ]# [ doc = " While the array is not very large (normally some hundred bytes)," ]# [ doc = " copying it recklessly may result in the performance hit." ]# [ doc = " Thus this is intentionally not `Copy`." ]# [ doc = "" ]# [ doc = " All operations available to bignums panic in the case of overflows." ]# [ doc = " The caller is responsible to use large enough bignum types." ] pub struct $name {# [ doc = " One plus the offset to the maximum \\\"digit\\\" in use." ]# [ doc = " This does not decrease, so be aware of the computation order." ]# [ doc = " `base[size..]` should be zero." ] size : usize , # [ doc = " Digits. `[a, b, c, ...]` represents `a + b*2^W + c*2^(2W) + ...`" ]# [ doc = " where `W` is the number of bits in the digit type." ] base : [$ty ; $n ], } impl $name {# [ doc = " Makes a bignum from one digit." ] pub fn from_small ( v : $ty )-> $name { let mut base = [ 0 ; $n ]; base [ 0 ]= v ; $name { size : 1 , base : base }}# [ doc = " Makes a bignum from `u64` value." ] pub fn from_u64 ( mut v : u64 )-> $name { let mut base = [ 0 ; $n ]; let mut sz = 0 ; while v > 0 { base [ sz ]= v as $ty ; v >>= <$ty >:: BITS ; sz += 1 ; }$name { size : sz , base : base }}# [ doc = " Returns the internal digits as a slice `[a, b, c, ...]` such that the numeric" ]# [ doc = " value is `a + b * 2^W + c * 2^(2W) + ...` where `W` is the number of bits in" ]# [ doc = " the digit type." ] pub fn digits (& self )-> & [$ty ]{& self . base [.. self . size ]}# [ doc = " Returns the `i`-th bit where bit 0 is the least significant one." ]# [ doc = " In other words, the bit with weight `2^i`." ] pub fn get_bit (& self , i : usize )-> u8 { let digitbits = <$ty >:: BITS as usize ; let d = i / digitbits ; let b = i % digitbits ; (( self . base [ d ]>> b )& 1 ) as u8 }# [ doc = " Returns `true` if the bignum is zero." ] pub fn is_zero (& self )-> bool { self . digits (). iter (). all (|& v | v == 0 )}# [ doc = " Returns the number of bits necessary to represent this value. Note that zero" ]# [ doc = " is considered to need 0 bits." ] pub fn bit_length (& self )-> usize { let digits = self . digits (); let zeros = digits . iter (). rev (). take_while (|&& x | x == 0 ). count (); let end = digits . len ()- zeros ; let nonzero = & digits [.. end ]; if nonzero . is_empty (){ return 0 ; } let digitbits = <$ty >:: BITS as usize ; let mut i = nonzero . len ()* digitbits - 1 ; while self . get_bit ( i )== 0 { i -= 1 ; } i + 1 }# [ doc = " Adds `other` to itself and returns its own mutable reference." ] pub fn add < 'a > (& 'a mut self , other : &$name )-> & 'a mut $name { use crate :: cmp ; use crate :: num :: bignum :: FullOps ; let mut sz = cmp :: max ( self . size , other . size ); let mut carry = false ; for ( a , b ) in self . base [.. sz ]. iter_mut (). zip (& other . base [.. sz ]){ let ( c , v )= (* a ). full_add (* b , carry ); * a = v ; carry = c ; } if carry { self . base [ sz ]= 1 ; sz += 1 ; } self . size = sz ; self } pub fn add_small (& mut self , other : $ty )-> & mut $name { use crate :: num :: bignum :: FullOps ; let ( mut carry , v )= self . base [ 0 ]. full_add ( other , false ); self . base [ 0 ]= v ; let mut i = 1 ; while carry { let ( c , v )= self . base [ i ]. full_add ( 0 , carry ); self . base [ i ]= v ; carry = c ; i += 1 ; } if i > self . size { self . size = i ; } self }# [ doc = " Subtracts `other` from itself and returns its own mutable reference." ] pub fn sub < 'a > (& 'a mut self , other : &$name )-> & 'a mut $name { use crate :: cmp ; use crate :: num :: bignum :: FullOps ; let sz = cmp :: max ( self . size , other . size ); let mut noborrow = true ; for ( a , b ) in self . base [.. sz ]. iter_mut (). zip (& other . base [.. sz ]){ let ( c , v )= (* a ). full_add (!* b , noborrow ); * a = v ; noborrow = c ; } assert ! ( noborrow ); self . size = sz ; self }# [ doc = " Multiplies itself by a digit-sized `other` and returns its own" ]# [ doc = " mutable reference." ] pub fn mul_small (& mut self , other : $ty )-> & mut $name { use crate :: num :: bignum :: FullOps ; let mut sz = self . size ; let mut carry = 0 ; for a in & mut self . base [.. sz ]{ let ( c , v )= (* a ). full_mul ( other , carry ); * a = v ; carry = c ; } if carry > 0 { self . base [ sz ]= carry ; sz += 1 ; } self . size = sz ; self }# [ doc = " Multiplies itself by `2^bits` and returns its own mutable reference." ] pub fn mul_pow2 (& mut self , bits : usize )-> & mut $name { let digitbits = <$ty >:: BITS as usize ; let digits = bits / digitbits ; let bits = bits % digitbits ; assert ! ( digits < $n ); debug_assert ! ( self . base [$n - digits ..]. iter (). all (|& v | v == 0 )); debug_assert ! ( bits == 0 || ( self . base [$n - digits - 1 ]>> ( digitbits - bits ))== 0 ); for i in ( 0 .. self . size ). rev (){ self . base [ i + digits ]= self . base [ i ]; } for i in 0 .. digits { self . base [ i ]= 0 ; } let mut sz = self . size + digits ; if bits > 0 { let last = sz ; let overflow = self . base [ last - 1 ]>> ( digitbits - bits ); if overflow > 0 { self . base [ last ]= overflow ; sz += 1 ; } for i in ( digits + 1 .. last ). rev (){ self . base [ i ]= ( self . base [ i ]<< bits )| ( self . base [ i - 1 ]>> ( digitbits - bits )); } self . base [ digits ]<<= bits ; } self . size = sz ; self }# [ doc = " Multiplies itself by `5^e` and returns its own mutable reference." ] pub fn mul_pow5 (& mut self , mut e : usize )-> & mut $name { use crate :: mem ; use crate :: num :: bignum :: SMALL_POW5 ; let table_index = mem :: size_of ::<$ty > (). trailing_zeros () as usize ; let ( small_power , small_e )= SMALL_POW5 [ table_index ]; let small_power = small_power as $ty ; while e >= small_e { self . mul_small ( small_power ); e -= small_e ; } let mut rest_power = 1 ; for _ in 0 .. e { rest_power *= 5 ; } self . mul_small ( rest_power ); self }# [ doc = " Multiplies itself by a number described by `other[0] + other[1] * 2^W +" ]# [ doc = " other[2] * 2^(2W) + ...` (where `W` is the number of bits in the digit type)" ]# [ doc = " and returns its own mutable reference." ] pub fn mul_digits < 'a > (& 'a mut self , other : & [$ty ])-> & 'a mut $name { fn mul_inner ( ret : & mut [$ty ; $n ], aa : & [$ty ], bb : & [$ty ])-> usize { use crate :: num :: bignum :: FullOps ; let mut retsz = 0 ; for ( i , & a ) in aa . iter (). enumerate (){ if a == 0 { continue ; } let mut sz = bb . len (); let mut carry = 0 ; for ( j , & b ) in bb . iter (). enumerate (){ let ( c , v )= a . full_mul_add ( b , ret [ i + j ], carry ); ret [ i + j ]= v ; carry = c ; } if carry > 0 { ret [ i + sz ]= carry ; sz += 1 ; } if retsz < i + sz { retsz = i + sz ; }} retsz } let mut ret = [ 0 ; $n ]; let retsz = if self . size < other . len (){ mul_inner (& mut ret , & self . digits (), other )} else { mul_inner (& mut ret , other , & self . digits ())}; self . base = ret ; self . size = retsz ; self }# [ doc = " Divides itself by a digit-sized `other` and returns its own" ]# [ doc = " mutable reference *and* the remainder." ] pub fn div_rem_small (& mut self , other : $ty )-> (& mut $name , $ty ){ use crate :: num :: bignum :: FullOps ; assert ! ( other > 0 ); let sz = self . size ; let mut borrow = 0 ; for a in self . base [.. sz ]. iter_mut (). rev (){ let ( q , r )= (* a ). full_div_rem ( other , borrow ); * a = q ; borrow = r ; }( self , borrow )}# [ doc = " Divide self by another bignum, overwriting `q` with the quotient and `r` with the" ]# [ doc = " remainder." ] pub fn div_rem (& self , d : &$name , q : & mut $name , r : & mut $name ){ assert ! (! d . is_zero ()); let digitbits = <$ty >:: BITS as usize ; for digit in & mut q . base [..]{* digit = 0 ; } for digit in & mut r . base [..]{* digit = 0 ; } r . size = d . size ; q . size = 1 ; let mut q_is_zero = true ; let end = self . bit_length (); for i in ( 0 .. end ). rev (){ r . mul_pow2 ( 1 ); r . base [ 0 ]|= self . get_bit ( i ) as $ty ; if &* r >= d { r . sub ( d ); let digit_idx = i / digitbits ; let bit_idx = i % digitbits ; if q_is_zero { q . size = digit_idx + 1 ; q_is_zero = false ; } q . base [ digit_idx ]|= 1 << bit_idx ; }} debug_assert ! ( q . base [ q . size ..]. iter (). all (|& d | d == 0 )); debug_assert ! ( r . base [ r . size ..]. iter (). all (|& d | d == 0 )); }} impl crate :: cmp :: PartialEq for $name { fn eq (& self , other : &$name )-> bool { self . base [..]== other . base [..]}} impl crate :: cmp :: Eq for $name {} impl crate :: cmp :: PartialOrd for $name { fn partial_cmp (& self , other : &$name )-> crate :: option :: Option < crate :: cmp :: Ordering > { crate :: option :: Option :: Some ( self . cmp ( other ))}} impl crate :: cmp :: Ord for $name { fn cmp (& self , other : &$name )-> crate :: cmp :: Ordering { use crate :: cmp :: max ; let sz = max ( self . size , other . size ); let lhs = self . base [.. sz ]. iter (). cloned (). rev (); let rhs = other . base [.. sz ]. iter (). cloned (). rev (); lhs . cmp ( rhs )}} impl crate :: clone :: Clone for $name { fn clone (& self )-> Self { Self { size : self . size , base : self . base }}} impl crate :: fmt :: Debug for $name { fn fmt (& self , f : & mut crate :: fmt :: Formatter < '_ >)-> crate :: fmt :: Result { let sz = if self . size < 1 { 1 } else { self . size }; let digitlen = <$ty >:: BITS as usize / 4 ; write ! ( f , "{:#x}" , self . base [ sz - 1 ])?; for & v in self . base [.. sz - 1 ]. iter (). rev (){ write ! ( f , "_{:01$x}" , v , digitlen )?; } crate :: result :: Result :: Ok (())}}}; } +macro_rules! __ra_macro_fixture3 {($t : ty )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl FromStr for $t { type Err = ParseFloatError ; # [ doc = " Converts a string in base 10 to a float." ]# [ doc = " Accepts an optional decimal exponent." ]# [ doc = "" ]# [ doc = " This function accepts strings such as" ]# [ doc = "" ]# [ doc = " * \\\'3.14\\\'" ]# [ doc = " * \\\'-3.14\\\'" ]# [ doc = " * \\\'2.5E10\\\', or equivalently, \\\'2.5e10\\\'" ]# [ doc = " * \\\'2.5E-10\\\'" ]# [ doc = " * \\\'5.\\\'" ]# [ doc = " * \\\'.5\\\', or, equivalently, \\\'0.5\\\'" ]# [ doc = " * \\\'inf\\\', \\\'-inf\\\', \\\'NaN\\\'" ]# [ doc = "" ]# [ doc = " Leading and trailing whitespace represent an error." ]# [ doc = "" ]# [ doc = " # Grammar" ]# [ doc = "" ]# [ doc = " All strings that adhere to the following [EBNF] grammar" ]# [ doc = " will result in an [`Ok`] being returned:" ]# [ doc = "" ]# [ doc = " ```txt" ]# [ doc = " Float ::= Sign? ( \\\'inf\\\' | \\\'NaN\\\' | Number )" ]# [ doc = " Number ::= ( Digit+ |" ]# [ doc = " Digit+ \\\'.\\\' Digit* |" ]# [ doc = " Digit* \\\'.\\\' Digit+ ) Exp?" ]# [ doc = " Exp ::= [eE] Sign? Digit+" ]# [ doc = " Sign ::= [+-]" ]# [ doc = " Digit ::= [0-9]" ]# [ doc = " ```" ]# [ doc = "" ]# [ doc = " [EBNF]: https://www.w3.org/TR/REC-xml/#sec-notation" ]# [ doc = "" ]# [ doc = " # Known bugs" ]# [ doc = "" ]# [ doc = " In some situations, some strings that should create a valid float" ]# [ doc = " instead return an error. See [issue #31407] for details." ]# [ doc = "" ]# [ doc = " [issue #31407]: https://github.com/rust-lang/rust/issues/31407" ]# [ doc = "" ]# [ doc = " # Arguments" ]# [ doc = "" ]# [ doc = " * src - A string" ]# [ doc = "" ]# [ doc = " # Return value" ]# [ doc = "" ]# [ doc = " `Err(ParseFloatError)` if the string did not represent a valid" ]# [ doc = " number. Otherwise, `Ok(n)` where `n` is the floating-point" ]# [ doc = " number represented by `src`." ]# [ inline ] fn from_str ( src : & str )-> Result < Self , ParseFloatError > { dec2flt ( src )}}}; } +macro_rules! __ra_macro_fixture4 {($(# [$stability : meta ]$Ty : ident ($Int : ty ); )+ )=>{$(doc_comment ! { concat ! ( "An integer that is known not to equal zero.\n\nThis enables some memory layout optimization.\nFor example, `Option<" , stringify ! ($Ty ), ">` is the same size as `" , stringify ! ($Int ), "`:\n\n```rust\nuse std::mem::size_of;\nassert_eq!(size_of::<Option<core::num::" , stringify ! ($Ty ), ">>(), size_of::<" , stringify ! ($Int ), ">());\n```" ), # [$stability ]# [ derive ( Copy , Clone , Eq , PartialEq , Ord , PartialOrd , Hash )]# [ repr ( transparent )]# [ rustc_layout_scalar_valid_range_start ( 1 )]# [ rustc_nonnull_optimization_guaranteed ] pub struct $Ty ($Int ); } impl $Ty {# [ doc = " Creates a non-zero without checking the value." ]# [ doc = "" ]# [ doc = " # Safety" ]# [ doc = "" ]# [ doc = " The value must not be zero." ]# [$stability ]# [ rustc_const_stable ( feature = "nonzero" , since = "1.34.0" )]# [ inline ] pub const unsafe fn new_unchecked ( n : $Int )-> Self { unsafe { Self ( n )}}# [ doc = " Creates a non-zero if the given value is not zero." ]# [$stability ]# [ rustc_const_stable ( feature = "const_nonzero_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn new ( n : $Int )-> Option < Self > { if n != 0 { Some ( unsafe { Self ( n )})} else { None }}# [ doc = " Returns the value as a primitive type." ]# [$stability ]# [ inline ]# [ rustc_const_stable ( feature = "nonzero" , since = "1.34.0" )] pub const fn get ( self )-> $Int { self . 0 }}# [ stable ( feature = "from_nonzero" , since = "1.31.0" )] impl From <$Ty > for $Int { doc_comment ! { concat ! ( "Converts a `" , stringify ! ($Ty ), "` into an `" , stringify ! ($Int ), "`" ), # [ inline ] fn from ( nonzero : $Ty )-> Self { nonzero . 0 }}}# [ stable ( feature = "nonzero_bitor" , since = "1.45.0" )] impl BitOr for $Ty { type Output = Self ; # [ inline ] fn bitor ( self , rhs : Self )-> Self :: Output { unsafe {$Ty :: new_unchecked ( self . get ()| rhs . get ())}}}# [ stable ( feature = "nonzero_bitor" , since = "1.45.0" )] impl BitOr <$Int > for $Ty { type Output = Self ; # [ inline ] fn bitor ( self , rhs : $Int )-> Self :: Output { unsafe {$Ty :: new_unchecked ( self . get ()| rhs )}}}# [ stable ( feature = "nonzero_bitor" , since = "1.45.0" )] impl BitOr <$Ty > for $Int { type Output = $Ty ; # [ inline ] fn bitor ( self , rhs : $Ty )-> Self :: Output { unsafe {$Ty :: new_unchecked ( self | rhs . get ())}}}# [ stable ( feature = "nonzero_bitor" , since = "1.45.0" )] impl BitOrAssign for $Ty {# [ inline ] fn bitor_assign (& mut self , rhs : Self ){* self = * self | rhs ; }}# [ stable ( feature = "nonzero_bitor" , since = "1.45.0" )] impl BitOrAssign <$Int > for $Ty {# [ inline ] fn bitor_assign (& mut self , rhs : $Int ){* self = * self | rhs ; }} impl_nonzero_fmt ! {# [$stability ]( Debug , Display , Binary , Octal , LowerHex , UpperHex ) for $Ty })+ }} +macro_rules! __ra_macro_fixture5 {($($t : ty )*)=>{$(# [ stable ( feature = "nonzero_parse" , since = "1.35.0" )] impl FromStr for $t { type Err = ParseIntError ; fn from_str ( src : & str )-> Result < Self , Self :: Err > { Self :: new ( from_str_radix ( src , 10 )?). ok_or ( ParseIntError { kind : IntErrorKind :: Zero })}})*}} +macro_rules! __ra_macro_fixture6 {($($t : ident )*)=>($(sh_impl_unsigned ! {$t , usize })*)} +macro_rules! __ra_macro_fixture7 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Add for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn add ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_add ( other . 0 ))}} forward_ref_binop ! { impl Add , add for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl AddAssign for Wrapping <$t > {# [ inline ] fn add_assign (& mut self , other : Wrapping <$t >){* self = * self + other ; }} forward_ref_op_assign ! { impl AddAssign , add_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Sub for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn sub ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_sub ( other . 0 ))}} forward_ref_binop ! { impl Sub , sub for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl SubAssign for Wrapping <$t > {# [ inline ] fn sub_assign (& mut self , other : Wrapping <$t >){* self = * self - other ; }} forward_ref_op_assign ! { impl SubAssign , sub_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Mul for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn mul ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_mul ( other . 0 ))}} forward_ref_binop ! { impl Mul , mul for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl MulAssign for Wrapping <$t > {# [ inline ] fn mul_assign (& mut self , other : Wrapping <$t >){* self = * self * other ; }} forward_ref_op_assign ! { impl MulAssign , mul_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "wrapping_div" , since = "1.3.0" )] impl Div for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn div ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_div ( other . 0 ))}} forward_ref_binop ! { impl Div , div for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl DivAssign for Wrapping <$t > {# [ inline ] fn div_assign (& mut self , other : Wrapping <$t >){* self = * self / other ; }} forward_ref_op_assign ! { impl DivAssign , div_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "wrapping_impls" , since = "1.7.0" )] impl Rem for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn rem ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_rem ( other . 0 ))}} forward_ref_binop ! { impl Rem , rem for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl RemAssign for Wrapping <$t > {# [ inline ] fn rem_assign (& mut self , other : Wrapping <$t >){* self = * self % other ; }} forward_ref_op_assign ! { impl RemAssign , rem_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Not for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn not ( self )-> Wrapping <$t > { Wrapping (! self . 0 )}} forward_ref_unop ! { impl Not , not for Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl BitXor for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn bitxor ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 ^ other . 0 )}} forward_ref_binop ! { impl BitXor , bitxor for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl BitXorAssign for Wrapping <$t > {# [ inline ] fn bitxor_assign (& mut self , other : Wrapping <$t >){* self = * self ^ other ; }} forward_ref_op_assign ! { impl BitXorAssign , bitxor_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl BitOr for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn bitor ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 | other . 0 )}} forward_ref_binop ! { impl BitOr , bitor for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl BitOrAssign for Wrapping <$t > {# [ inline ] fn bitor_assign (& mut self , other : Wrapping <$t >){* self = * self | other ; }} forward_ref_op_assign ! { impl BitOrAssign , bitor_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl BitAnd for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn bitand ( self , other : Wrapping <$t >)-> Wrapping <$t > { Wrapping ( self . 0 & other . 0 )}} forward_ref_binop ! { impl BitAnd , bitand for Wrapping <$t >, Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl BitAndAssign for Wrapping <$t > {# [ inline ] fn bitand_assign (& mut self , other : Wrapping <$t >){* self = * self & other ; }} forward_ref_op_assign ! { impl BitAndAssign , bitand_assign for Wrapping <$t >, Wrapping <$t > }# [ stable ( feature = "wrapping_neg" , since = "1.10.0" )] impl Neg for Wrapping <$t > { type Output = Self ; # [ inline ] fn neg ( self )-> Self { Wrapping ( 0 )- self }} forward_ref_unop ! { impl Neg , neg for Wrapping <$t >, # [ stable ( feature = "wrapping_ref" , since = "1.14.0" )]})*)} +macro_rules! __ra_macro_fixture8 {($($t : ty )*)=>($(impl Wrapping <$t > { doc_comment ! { concat ! ( "Returns the smallest value that can be represented by this integer type.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(<Wrapping<" , stringify ! ($t ), ">>::MIN, Wrapping(" , stringify ! ($t ), "::MIN));\n```" ), # [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const MIN : Self = Self (<$t >:: MIN ); } doc_comment ! { concat ! ( "Returns the largest value that can be represented by this integer type.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(<Wrapping<" , stringify ! ($t ), ">>::MAX, Wrapping(" , stringify ! ($t ), "::MAX));\n```" ), # [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const MAX : Self = Self (<$t >:: MAX ); } doc_comment ! { concat ! ( "Returns the number of ones in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(0b01001100" , stringify ! ($t ), ");\n\nassert_eq!(n.count_ones(), 3);\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn count_ones ( self )-> u32 { self . 0 . count_ones ()}} doc_comment ! { concat ! ( "Returns the number of zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(Wrapping(!0" , stringify ! ($t ), ").count_zeros(), 0);\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn count_zeros ( self )-> u32 { self . 0 . count_zeros ()}} doc_comment ! { concat ! ( "Returns the number of trailing zeros in the binary representation\nof `self`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(0b0101000" , stringify ! ($t ), ");\n\nassert_eq!(n.trailing_zeros(), 3);\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn trailing_zeros ( self )-> u32 { self . 0 . trailing_zeros ()}}# [ doc = " Shifts the bits to the left by a specified amount, `n`," ]# [ doc = " wrapping the truncated bits to the end of the resulting" ]# [ doc = " integer." ]# [ doc = "" ]# [ doc = " Please note this isn\\\'t the same operation as the `<<` shifting" ]# [ doc = " operator!" ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " #![feature(wrapping_int_impl)]" ]# [ doc = " use std::num::Wrapping;" ]# [ doc = "" ]# [ doc = " let n: Wrapping<i64> = Wrapping(0x0123456789ABCDEF);" ]# [ doc = " let m: Wrapping<i64> = Wrapping(-0x76543210FEDCBA99);" ]# [ doc = "" ]# [ doc = " assert_eq!(n.rotate_left(32), m);" ]# [ doc = " ```" ]# [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn rotate_left ( self , n : u32 )-> Self { Wrapping ( self . 0 . rotate_left ( n ))}# [ doc = " Shifts the bits to the right by a specified amount, `n`," ]# [ doc = " wrapping the truncated bits to the beginning of the resulting" ]# [ doc = " integer." ]# [ doc = "" ]# [ doc = " Please note this isn\\\'t the same operation as the `>>` shifting" ]# [ doc = " operator!" ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " #![feature(wrapping_int_impl)]" ]# [ doc = " use std::num::Wrapping;" ]# [ doc = "" ]# [ doc = " let n: Wrapping<i64> = Wrapping(0x0123456789ABCDEF);" ]# [ doc = " let m: Wrapping<i64> = Wrapping(-0xFEDCBA987654322);" ]# [ doc = "" ]# [ doc = " assert_eq!(n.rotate_right(4), m);" ]# [ doc = " ```" ]# [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn rotate_right ( self , n : u32 )-> Self { Wrapping ( self . 0 . rotate_right ( n ))}# [ doc = " Reverses the byte order of the integer." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " #![feature(wrapping_int_impl)]" ]# [ doc = " use std::num::Wrapping;" ]# [ doc = "" ]# [ doc = " let n: Wrapping<i16> = Wrapping(0b0000000_01010101);" ]# [ doc = " assert_eq!(n, Wrapping(85));" ]# [ doc = "" ]# [ doc = " let m = n.swap_bytes();" ]# [ doc = "" ]# [ doc = " assert_eq!(m, Wrapping(0b01010101_00000000));" ]# [ doc = " assert_eq!(m, Wrapping(21760));" ]# [ doc = " ```" ]# [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn swap_bytes ( self )-> Self { Wrapping ( self . 0 . swap_bytes ())}# [ doc = " Reverses the bit pattern of the integer." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Please note that this example is shared between integer types." ]# [ doc = " Which explains why `i16` is used here." ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use std::num::Wrapping;" ]# [ doc = "" ]# [ doc = " let n = Wrapping(0b0000000_01010101i16);" ]# [ doc = " assert_eq!(n, Wrapping(85));" ]# [ doc = "" ]# [ doc = " let m = n.reverse_bits();" ]# [ doc = "" ]# [ doc = " assert_eq!(m.0 as u16, 0b10101010_00000000);" ]# [ doc = " assert_eq!(m, Wrapping(-22016));" ]# [ doc = " ```" ]# [ stable ( feature = "reverse_bits" , since = "1.37.0" )]# [ rustc_const_stable ( feature = "const_reverse_bits" , since = "1.37.0" )]# [ inline ]# [ must_use ] pub const fn reverse_bits ( self )-> Self { Wrapping ( self . 0 . reverse_bits ())} doc_comment ! { concat ! ( "Converts an integer from big endian to the target's endianness.\n\nOn big endian this is a no-op. On little endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(0x1A" , stringify ! ($t ), ");\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(<Wrapping<" , stringify ! ($t ), ">>::from_be(n), n)\n} else {\n assert_eq!(<Wrapping<" , stringify ! ($t ), ">>::from_be(n), n.swap_bytes())\n}\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn from_be ( x : Self )-> Self { Wrapping (<$t >:: from_be ( x . 0 ))}} doc_comment ! { concat ! ( "Converts an integer from little endian to the target's endianness.\n\nOn little endian this is a no-op. On big endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(0x1A" , stringify ! ($t ), ");\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(<Wrapping<" , stringify ! ($t ), ">>::from_le(n), n)\n} else {\n assert_eq!(<Wrapping<" , stringify ! ($t ), ">>::from_le(n), n.swap_bytes())\n}\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn from_le ( x : Self )-> Self { Wrapping (<$t >:: from_le ( x . 0 ))}} doc_comment ! { concat ! ( "Converts `self` to big endian from the target's endianness.\n\nOn big endian this is a no-op. On little endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(0x1A" , stringify ! ($t ), ");\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(n.to_be(), n)\n} else {\n assert_eq!(n.to_be(), n.swap_bytes())\n}\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn to_be ( self )-> Self { Wrapping ( self . 0 . to_be ())}} doc_comment ! { concat ! ( "Converts `self` to little endian from the target's endianness.\n\nOn little endian this is a no-op. On big endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(0x1A" , stringify ! ($t ), ");\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(n.to_le(), n)\n} else {\n assert_eq!(n.to_le(), n.swap_bytes())\n}\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn to_le ( self )-> Self { Wrapping ( self . 0 . to_le ())}} doc_comment ! { concat ! ( "Raises self to the power of `exp`, using exponentiation by squaring.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(Wrapping(3" , stringify ! ($t ), ").pow(4), Wrapping(81));\n```\n\nResults that are too large are wrapped:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(Wrapping(3i8).pow(5), Wrapping(-13));\nassert_eq!(Wrapping(3i8).pow(6), Wrapping(-39));\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub fn pow ( self , exp : u32 )-> Self { Wrapping ( self . 0 . wrapping_pow ( exp ))}}})*)} +macro_rules! __ra_macro_fixture9 {($($t : ty )*)=>($(impl Wrapping <$t > { doc_comment ! { concat ! ( "Returns the number of leading zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(" , stringify ! ($t ), "::MAX) >> 2;\n\nassert_eq!(n.leading_zeros(), 3);\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn leading_zeros ( self )-> u32 { self . 0 . leading_zeros ()}} doc_comment ! { concat ! ( "Computes the absolute value of `self`, wrapping around at\nthe boundary of the type.\n\nThe only case where such wrapping can occur is when one takes the absolute value of the negative\nminimal value for the type this is a positive value that is too large to represent in the type. In\nsuch a case, this function returns `MIN` itself.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(Wrapping(100" , stringify ! ($t ), ").abs(), Wrapping(100));\nassert_eq!(Wrapping(-100" , stringify ! ($t ), ").abs(), Wrapping(100));\nassert_eq!(Wrapping(" , stringify ! ($t ), "::MIN).abs(), Wrapping(" , stringify ! ($t ), "::MIN));\nassert_eq!(Wrapping(-128i8).abs().0 as u8, 128u8);\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub fn abs ( self )-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_abs ())}} doc_comment ! { concat ! ( "Returns a number representing sign of `self`.\n\n - `0` if the number is zero\n - `1` if the number is positive\n - `-1` if the number is negative\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert_eq!(Wrapping(10" , stringify ! ($t ), ").signum(), Wrapping(1));\nassert_eq!(Wrapping(0" , stringify ! ($t ), ").signum(), Wrapping(0));\nassert_eq!(Wrapping(-10" , stringify ! ($t ), ").signum(), Wrapping(-1));\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub fn signum ( self )-> Wrapping <$t > { Wrapping ( self . 0 . signum ())}} doc_comment ! { concat ! ( "Returns `true` if `self` is positive and `false` if the number is zero or\nnegative.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert!(Wrapping(10" , stringify ! ($t ), ").is_positive());\nassert!(!Wrapping(-10" , stringify ! ($t ), ").is_positive());\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn is_positive ( self )-> bool { self . 0 . is_positive ()}} doc_comment ! { concat ! ( "Returns `true` if `self` is negative and `false` if the number is zero or\npositive.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert!(Wrapping(-10" , stringify ! ($t ), ").is_negative());\nassert!(!Wrapping(10" , stringify ! ($t ), ").is_negative());\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn is_negative ( self )-> bool { self . 0 . is_negative ()}}})*)} +macro_rules! __ra_macro_fixture10 {($($t : ty )*)=>($(impl Wrapping <$t > { doc_comment ! { concat ! ( "Returns the number of leading zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nlet n = Wrapping(" , stringify ! ($t ), "::MAX) >> 2;\n\nassert_eq!(n.leading_zeros(), 2);\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub const fn leading_zeros ( self )-> u32 { self . 0 . leading_zeros ()}} doc_comment ! { concat ! ( "Returns `true` if and only if `self == 2^k` for some `k`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_int_impl)]\nuse std::num::Wrapping;\n\nassert!(Wrapping(16" , stringify ! ($t ), ").is_power_of_two());\nassert!(!Wrapping(10" , stringify ! ($t ), ").is_power_of_two());\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_int_impl" , issue = "32463" )] pub fn is_power_of_two ( self )-> bool { self . 0 . is_power_of_two ()}} doc_comment ! { concat ! ( "Returns the smallest power of two greater than or equal to `self`.\n\nWhen return value overflows (i.e., `self > (1 << (N-1))` for type\n`uN`), overflows to `2^N = 0`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_next_power_of_two)]\nuse std::num::Wrapping;\n\nassert_eq!(Wrapping(2" , stringify ! ($t ), ").next_power_of_two(), Wrapping(2));\nassert_eq!(Wrapping(3" , stringify ! ($t ), ").next_power_of_two(), Wrapping(4));\nassert_eq!(Wrapping(200_u8).next_power_of_two(), Wrapping(0));\n```" ), # [ inline ]# [ unstable ( feature = "wrapping_next_power_of_two" , issue = "32463" , reason = "needs decision on wrapping behaviour" )] pub fn next_power_of_two ( self )-> Self { Wrapping ( self . 0 . wrapping_next_power_of_two ())}}})*)} +macro_rules! __ra_macro_fixture11 {($($t : ty )*)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl FromStr for $t { type Err = ParseIntError ; fn from_str ( src : & str )-> Result < Self , ParseIntError > { from_str_radix ( src , 10 )}})*}} +macro_rules! __ra_macro_fixture12 {($($t : ty )*)=>($(impl FromStrRadixHelper for $t {# [ inline ] fn min_value ()-> Self { Self :: MIN }# [ inline ] fn max_value ()-> Self { Self :: MAX }# [ inline ] fn from_u32 ( u : u32 )-> Self { u as Self }# [ inline ] fn checked_mul (& self , other : u32 )-> Option < Self > { Self :: checked_mul (* self , other as Self )}# [ inline ] fn checked_sub (& self , other : u32 )-> Option < Self > { Self :: checked_sub (* self , other as Self )}# [ inline ] fn checked_add (& self , other : u32 )-> Option < Self > { Self :: checked_add (* self , other as Self )}})*)} +macro_rules! __ra_macro_fixture13 {($($Arg : ident ),+)=>{ fnptr_impls_safety_abi ! { extern "Rust" fn ($($Arg ),+)-> Ret , $($Arg ),+ } fnptr_impls_safety_abi ! { extern "C" fn ($($Arg ),+)-> Ret , $($Arg ),+ } fnptr_impls_safety_abi ! { extern "C" fn ($($Arg ),+ , ...)-> Ret , $($Arg ),+ } fnptr_impls_safety_abi ! { unsafe extern "Rust" fn ($($Arg ),+)-> Ret , $($Arg ),+ } fnptr_impls_safety_abi ! { unsafe extern "C" fn ($($Arg ),+)-> Ret , $($Arg ),+ } fnptr_impls_safety_abi ! { unsafe extern "C" fn ($($Arg ),+ , ...)-> Ret , $($Arg ),+ }}; ()=>{ fnptr_impls_safety_abi ! { extern "Rust" fn ()-> Ret , } fnptr_impls_safety_abi ! { extern "C" fn ()-> Ret , } fnptr_impls_safety_abi ! { unsafe extern "Rust" fn ()-> Ret , } fnptr_impls_safety_abi ! { unsafe extern "C" fn ()-> Ret , }}; } +macro_rules! __ra_macro_fixture14 {($($t : ty )*)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Clone for $t {# [ inline ] fn clone (& self )-> Self {* self }})* }} +macro_rules! __ra_macro_fixture15 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl PartialEq for $t {# [ inline ] fn eq (& self , other : &$t )-> bool {(* self )== (* other )}# [ inline ] fn ne (& self , other : &$t )-> bool {(* self )!= (* other )}})*)} +macro_rules! __ra_macro_fixture16 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Eq for $t {})*)} +macro_rules! __ra_macro_fixture17 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl PartialOrd for $t {# [ inline ] fn partial_cmp (& self , other : &$t )-> Option < Ordering > { match ( self <= other , self >= other ){( false , false )=> None , ( false , true )=> Some ( Greater ), ( true , false )=> Some ( Less ), ( true , true )=> Some ( Equal ), }}# [ inline ] fn lt (& self , other : &$t )-> bool {(* self )< (* other )}# [ inline ] fn le (& self , other : &$t )-> bool {(* self )<= (* other )}# [ inline ] fn ge (& self , other : &$t )-> bool {(* self )>= (* other )}# [ inline ] fn gt (& self , other : &$t )-> bool {(* self )> (* other )}})*)} +macro_rules! __ra_macro_fixture18 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl PartialOrd for $t {# [ inline ] fn partial_cmp (& self , other : &$t )-> Option < Ordering > { Some ( self . cmp ( other ))}# [ inline ] fn lt (& self , other : &$t )-> bool {(* self )< (* other )}# [ inline ] fn le (& self , other : &$t )-> bool {(* self )<= (* other )}# [ inline ] fn ge (& self , other : &$t )-> bool {(* self )>= (* other )}# [ inline ] fn gt (& self , other : &$t )-> bool {(* self )> (* other )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Ord for $t {# [ inline ] fn cmp (& self , other : &$t )-> Ordering { if * self < * other { Less } else if * self == * other { Equal } else { Greater }}})*)} +macro_rules! __ra_macro_fixture19 {($Float : ident =>$($Int : ident )+ )=>{# [ unstable ( feature = "convert_float_to_int" , issue = "67057" )] impl private :: Sealed for $Float {}$(# [ unstable ( feature = "convert_float_to_int" , issue = "67057" )] impl FloatToInt <$Int > for $Float {# [ doc ( hidden )]# [ inline ] unsafe fn to_int_unchecked ( self )-> $Int { unsafe { crate :: intrinsics :: float_to_int_unchecked ( self )}}})+ }} +macro_rules! __ra_macro_fixture20 {($target : ty , # [$attr : meta ])=>{ impl_from ! ( bool , $target , # [$attr ], concat ! ( "Converts a `bool` to a `" , stringify ! ($target ), "`. The resulting value is `0` for `false` and `1` for `true`\nvalues.\n\n# Examples\n\n```\nassert_eq!(" , stringify ! ($target ), "::from(true), 1);\nassert_eq!(" , stringify ! ($target ), "::from(false), 0);\n```" )); }; } +macro_rules! __ra_macro_fixture21 {($Small : ty , $Large : ty , # [$attr : meta ], $doc : expr )=>{# [$attr ]# [ doc = $doc ] impl From <$Small > for $Large {# [ inline ] fn from ( small : $Small )-> Self { small as Self }}}; ($Small : ty , $Large : ty , # [$attr : meta ])=>{ impl_from ! ($Small , $Large , # [$attr ], concat ! ( "Converts `" , stringify ! ($Small ), "` to `" , stringify ! ($Large ), "` losslessly." )); }} +macro_rules! __ra_macro_fixture22 {($source : ty , $($target : ty ),*)=>{$(# [ stable ( feature = "try_from" , since = "1.34.0" )] impl TryFrom <$source > for $target { type Error = TryFromIntError ; # [ doc = " Try to create the target number type from a source" ]# [ doc = " number type. This returns an error if the source value" ]# [ doc = " is outside of the range of the target type." ]# [ inline ] fn try_from ( u : $source )-> Result < Self , Self :: Error > { if u > ( Self :: MAX as $source ){ Err ( TryFromIntError (()))} else { Ok ( u as Self )}}})*}} +macro_rules! __ra_macro_fixture23 {($source : ty , $($target : ty ),*)=>{$(# [ stable ( feature = "try_from" , since = "1.34.0" )] impl TryFrom <$source > for $target { type Error = TryFromIntError ; # [ doc = " Try to create the target number type from a source" ]# [ doc = " number type. This returns an error if the source value" ]# [ doc = " is outside of the range of the target type." ]# [ inline ] fn try_from ( u : $source )-> Result < Self , Self :: Error > { let min = Self :: MIN as $source ; let max = Self :: MAX as $source ; if u < min || u > max { Err ( TryFromIntError (()))} else { Ok ( u as Self )}}})*}} +macro_rules! __ra_macro_fixture24 {($source : ty , $($target : ty ),*)=>{$(# [ stable ( feature = "try_from" , since = "1.34.0" )] impl TryFrom <$source > for $target { type Error = TryFromIntError ; # [ doc = " Try to create the target number type from a source" ]# [ doc = " number type. This returns an error if the source value" ]# [ doc = " is outside of the range of the target type." ]# [ inline ] fn try_from ( u : $source )-> Result < Self , Self :: Error > { if u >= 0 { Ok ( u as Self )} else { Err ( TryFromIntError (()))}}})*}} +macro_rules! __ra_macro_fixture25 {($source : ty , $($target : ty ),*)=>{$(# [ stable ( feature = "try_from" , since = "1.34.0" )] impl TryFrom <$source > for $target { type Error = TryFromIntError ; # [ doc = " Try to create the target number type from a source" ]# [ doc = " number type. This returns an error if the source value" ]# [ doc = " is outside of the range of the target type." ]# [ inline ] fn try_from ( value : $source )-> Result < Self , Self :: Error > { Ok ( value as Self )}})*}} +macro_rules! __ra_macro_fixture26 {($mac : ident , $source : ty , $($target : ty ),*)=>{$($mac ! ($target , $source ); )*}} +macro_rules! __ra_macro_fixture27 {($Small : ty , $Large : ty , # [$attr : meta ], $doc : expr )=>{# [$attr ]# [ doc = $doc ] impl From <$Small > for $Large {# [ inline ] fn from ( small : $Small )-> Self { unsafe { Self :: new_unchecked ( small . get (). into ())}}}}; ($Small : ty , $Large : ty , # [$attr : meta ])=>{ nzint_impl_from ! ($Small , $Large , # [$attr ], concat ! ( "Converts `" , stringify ! ($Small ), "` to `" , stringify ! ($Large ), "` losslessly." )); }} +macro_rules! __ra_macro_fixture28 {($Int : ty , $NonZeroInt : ty , # [$attr : meta ], $doc : expr )=>{# [$attr ]# [ doc = $doc ] impl TryFrom <$Int > for $NonZeroInt { type Error = TryFromIntError ; # [ inline ] fn try_from ( value : $Int )-> Result < Self , Self :: Error > { Self :: new ( value ). ok_or ( TryFromIntError (()))}}}; ($Int : ty , $NonZeroInt : ty , # [$attr : meta ])=>{ nzint_impl_try_from_int ! ($Int , $NonZeroInt , # [$attr ], concat ! ( "Attempts to convert `" , stringify ! ($Int ), "` to `" , stringify ! ($NonZeroInt ), "`." )); }} +macro_rules! __ra_macro_fixture29 {($From : ty =>$To : ty , $doc : expr )=>{# [ stable ( feature = "nzint_try_from_nzint_conv" , since = "1.49.0" )]# [ doc = $doc ] impl TryFrom <$From > for $To { type Error = TryFromIntError ; # [ inline ] fn try_from ( value : $From )-> Result < Self , Self :: Error > { TryFrom :: try_from ( value . get ()). map (| v | { unsafe { Self :: new_unchecked ( v )}})}}}; ($To : ty : $($From : ty ),*)=>{$(nzint_impl_try_from_nzint ! ($From =>$To , concat ! ( "Attempts to convert `" , stringify ! ($From ), "` to `" , stringify ! ($To ), "`." , )); )*}; } +macro_rules! __ra_macro_fixture30 {($t : ty , $v : expr , $doc : tt )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Default for $t {# [ inline ]# [ doc = $doc ] fn default ()-> $t {$v }}}} +macro_rules! __ra_macro_fixture31 {($t : ident )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > Hash for $t < T > {# [ inline ] fn hash < H : Hasher > (& self , _: & mut H ){}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > cmp :: PartialEq for $t < T > { fn eq (& self , _other : &$t < T >)-> bool { true }}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > cmp :: Eq for $t < T > {}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > cmp :: PartialOrd for $t < T > { fn partial_cmp (& self , _other : &$t < T >)-> Option < cmp :: Ordering > { Option :: Some ( cmp :: Ordering :: Equal )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > cmp :: Ord for $t < T > { fn cmp (& self , _other : &$t < T >)-> cmp :: Ordering { cmp :: Ordering :: Equal }}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > Copy for $t < T > {}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > Clone for $t < T > { fn clone (& self )-> Self { Self }}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized > Default for $t < T > { fn default ()-> Self { Self }}# [ unstable ( feature = "structural_match" , issue = "31434" )] impl < T : ? Sized > StructuralPartialEq for $t < T > {}# [ unstable ( feature = "structural_match" , issue = "31434" )] impl < T : ? Sized > StructuralEq for $t < T > {}}; } +macro_rules! __ra_macro_fixture32 {($($t : ty )*)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Copy for $t {})* }} +macro_rules! __ra_macro_fixture33 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Add for $t { type Output = $t ; # [ inline ]# [ rustc_inherit_overflow_checks ] fn add ( self , other : $t )-> $t { self + other }} forward_ref_binop ! { impl Add , add for $t , $t })*)} +macro_rules! __ra_macro_fixture34 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Sub for $t { type Output = $t ; # [ inline ]# [ rustc_inherit_overflow_checks ] fn sub ( self , other : $t )-> $t { self - other }} forward_ref_binop ! { impl Sub , sub for $t , $t })*)} +macro_rules! __ra_macro_fixture35 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Mul for $t { type Output = $t ; # [ inline ]# [ rustc_inherit_overflow_checks ] fn mul ( self , other : $t )-> $t { self * other }} forward_ref_binop ! { impl Mul , mul for $t , $t })*)} +macro_rules! __ra_macro_fixture36 {($($t : ty )*)=>($(# [ doc = " This operation rounds towards zero, truncating any" ]# [ doc = " fractional part of the exact result." ]# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Div for $t { type Output = $t ; # [ inline ] fn div ( self , other : $t )-> $t { self / other }} forward_ref_binop ! { impl Div , div for $t , $t })*)} +macro_rules! __ra_macro_fixture37 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Div for $t { type Output = $t ; # [ inline ] fn div ( self , other : $t )-> $t { self / other }} forward_ref_binop ! { impl Div , div for $t , $t })*)} +macro_rules! __ra_macro_fixture38 {($($t : ty )*)=>($(# [ doc = " This operation satisfies `n % d == n - (n / d) * d`. The" ]# [ doc = " result has the same sign as the left operand." ]# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Rem for $t { type Output = $t ; # [ inline ] fn rem ( self , other : $t )-> $t { self % other }} forward_ref_binop ! { impl Rem , rem for $t , $t })*)} +macro_rules! __ra_macro_fixture39 {($($t : ty )*)=>($(# [ doc = " The remainder from the division of two floats." ]# [ doc = "" ]# [ doc = " The remainder has the same sign as the dividend and is computed as:" ]# [ doc = " `x - (x / y).trunc() * y`." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = " ```" ]# [ doc = " let x: f32 = 50.50;" ]# [ doc = " let y: f32 = 8.125;" ]# [ doc = " let remainder = x - (x / y).trunc() * y;" ]# [ doc = "" ]# [ doc = " // The answer to both operations is 1.75" ]# [ doc = " assert_eq!(x % y, remainder);" ]# [ doc = " ```" ]# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Rem for $t { type Output = $t ; # [ inline ] fn rem ( self , other : $t )-> $t { self % other }} forward_ref_binop ! { impl Rem , rem for $t , $t })*)} +macro_rules! __ra_macro_fixture40 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Neg for $t { type Output = $t ; # [ inline ]# [ rustc_inherit_overflow_checks ] fn neg ( self )-> $t {- self }} forward_ref_unop ! { impl Neg , neg for $t })*)} +macro_rules! __ra_macro_fixture41 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl AddAssign for $t {# [ inline ]# [ rustc_inherit_overflow_checks ] fn add_assign (& mut self , other : $t ){* self += other }} forward_ref_op_assign ! { impl AddAssign , add_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture42 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl SubAssign for $t {# [ inline ]# [ rustc_inherit_overflow_checks ] fn sub_assign (& mut self , other : $t ){* self -= other }} forward_ref_op_assign ! { impl SubAssign , sub_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture43 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl MulAssign for $t {# [ inline ]# [ rustc_inherit_overflow_checks ] fn mul_assign (& mut self , other : $t ){* self *= other }} forward_ref_op_assign ! { impl MulAssign , mul_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture44 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl DivAssign for $t {# [ inline ] fn div_assign (& mut self , other : $t ){* self /= other }} forward_ref_op_assign ! { impl DivAssign , div_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture45 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl RemAssign for $t {# [ inline ] fn rem_assign (& mut self , other : $t ){* self %= other }} forward_ref_op_assign ! { impl RemAssign , rem_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture46 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Not for $t { type Output = $t ; # [ inline ] fn not ( self )-> $t {! self }} forward_ref_unop ! { impl Not , not for $t })*)} +macro_rules! __ra_macro_fixture47 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl BitAnd for $t { type Output = $t ; # [ inline ] fn bitand ( self , rhs : $t )-> $t { self & rhs }} forward_ref_binop ! { impl BitAnd , bitand for $t , $t })*)} +macro_rules! __ra_macro_fixture48 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl BitOr for $t { type Output = $t ; # [ inline ] fn bitor ( self , rhs : $t )-> $t { self | rhs }} forward_ref_binop ! { impl BitOr , bitor for $t , $t })*)} +macro_rules! __ra_macro_fixture49 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl BitXor for $t { type Output = $t ; # [ inline ] fn bitxor ( self , other : $t )-> $t { self ^ other }} forward_ref_binop ! { impl BitXor , bitxor for $t , $t })*)} +macro_rules! __ra_macro_fixture50 {($($t : ty )*)=>($(shl_impl ! {$t , u8 } shl_impl ! {$t , u16 } shl_impl ! {$t , u32 } shl_impl ! {$t , u64 } shl_impl ! {$t , u128 } shl_impl ! {$t , usize } shl_impl ! {$t , i8 } shl_impl ! {$t , i16 } shl_impl ! {$t , i32 } shl_impl ! {$t , i64 } shl_impl ! {$t , i128 } shl_impl ! {$t , isize })*)} +macro_rules! __ra_macro_fixture51 {($($t : ty )*)=>($(shr_impl ! {$t , u8 } shr_impl ! {$t , u16 } shr_impl ! {$t , u32 } shr_impl ! {$t , u64 } shr_impl ! {$t , u128 } shr_impl ! {$t , usize } shr_impl ! {$t , i8 } shr_impl ! {$t , i16 } shr_impl ! {$t , i32 } shr_impl ! {$t , i64 } shr_impl ! {$t , i128 } shr_impl ! {$t , isize })*)} +macro_rules! __ra_macro_fixture52 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl BitAndAssign for $t {# [ inline ] fn bitand_assign (& mut self , other : $t ){* self &= other }} forward_ref_op_assign ! { impl BitAndAssign , bitand_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture53 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl BitOrAssign for $t {# [ inline ] fn bitor_assign (& mut self , other : $t ){* self |= other }} forward_ref_op_assign ! { impl BitOrAssign , bitor_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture54 {($($t : ty )+)=>($(# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl BitXorAssign for $t {# [ inline ] fn bitxor_assign (& mut self , other : $t ){* self ^= other }} forward_ref_op_assign ! { impl BitXorAssign , bitxor_assign for $t , $t })+)} +macro_rules! __ra_macro_fixture55 {($($t : ty )*)=>($(shl_assign_impl ! {$t , u8 } shl_assign_impl ! {$t , u16 } shl_assign_impl ! {$t , u32 } shl_assign_impl ! {$t , u64 } shl_assign_impl ! {$t , u128 } shl_assign_impl ! {$t , usize } shl_assign_impl ! {$t , i8 } shl_assign_impl ! {$t , i16 } shl_assign_impl ! {$t , i32 } shl_assign_impl ! {$t , i64 } shl_assign_impl ! {$t , i128 } shl_assign_impl ! {$t , isize })*)} +macro_rules! __ra_macro_fixture56 {($($t : ty )*)=>($(shr_assign_impl ! {$t , u8 } shr_assign_impl ! {$t , u16 } shr_assign_impl ! {$t , u32 } shr_assign_impl ! {$t , u64 } shr_assign_impl ! {$t , u128 } shr_assign_impl ! {$t , usize } shr_assign_impl ! {$t , i8 } shr_assign_impl ! {$t , i16 } shr_assign_impl ! {$t , i32 } shr_assign_impl ! {$t , i64 } shr_assign_impl ! {$t , i128 } shr_assign_impl ! {$t , isize })*)} +macro_rules! __ra_macro_fixture57 {{$n : expr , $t : ident $($ts : ident )*}=>{# [ stable ( since = "1.4.0" , feature = "array_default" )] impl < T > Default for [ T ; $n ] where T : Default { fn default ()-> [ T ; $n ]{[$t :: default (), $($ts :: default ()),*]}} array_impl_default ! {($n - 1 ), $($ts )*}}; {$n : expr ,}=>{# [ stable ( since = "1.4.0" , feature = "array_default" )] impl < T > Default for [ T ; $n ]{ fn default ()-> [ T ; $n ]{[]}}}; } +macro_rules! __ra_macro_fixture58 {($($t : ty ),+)=>{$(# [ unstable ( feature = "c_variadic" , reason = "the `c_variadic` feature has not been properly tested on \\n all supported platforms" , issue = "44930" )] impl sealed_trait :: VaArgSafe for $t {})+ }} +macro_rules! __ra_macro_fixture59 {{ narrower than or same width as usize : $([$u_narrower : ident $i_narrower : ident ]),+; wider than usize : $([$u_wider : ident $i_wider : ident ]),+; }=>{$(# [ allow ( unreachable_patterns )]# [ unstable ( feature = "step_trait" , reason = "recently redesigned" , issue = "42168" )] unsafe impl Step for $u_narrower { step_identical_methods ! (); # [ inline ] fn steps_between ( start : & Self , end : & Self )-> Option < usize > { if * start <= * end { Some ((* end - * start ) as usize )} else { None }}# [ inline ] fn forward_checked ( start : Self , n : usize )-> Option < Self > { match Self :: try_from ( n ){ Ok ( n )=> start . checked_add ( n ), Err (_)=> None , }}# [ inline ] fn backward_checked ( start : Self , n : usize )-> Option < Self > { match Self :: try_from ( n ){ Ok ( n )=> start . checked_sub ( n ), Err (_)=> None , }}}# [ allow ( unreachable_patterns )]# [ unstable ( feature = "step_trait" , reason = "recently redesigned" , issue = "42168" )] unsafe impl Step for $i_narrower { step_identical_methods ! (); # [ inline ] fn steps_between ( start : & Self , end : & Self )-> Option < usize > { if * start <= * end { Some ((* end as isize ). wrapping_sub (* start as isize ) as usize )} else { None }}# [ inline ] fn forward_checked ( start : Self , n : usize )-> Option < Self > { match $u_narrower :: try_from ( n ){ Ok ( n )=>{ let wrapped = start . wrapping_add ( n as Self ); if wrapped >= start { Some ( wrapped )} else { None }} Err (_)=> None , }}# [ inline ] fn backward_checked ( start : Self , n : usize )-> Option < Self > { match $u_narrower :: try_from ( n ){ Ok ( n )=>{ let wrapped = start . wrapping_sub ( n as Self ); if wrapped <= start { Some ( wrapped )} else { None }} Err (_)=> None , }}})+ $(# [ allow ( unreachable_patterns )]# [ unstable ( feature = "step_trait" , reason = "recently redesigned" , issue = "42168" )] unsafe impl Step for $u_wider { step_identical_methods ! (); # [ inline ] fn steps_between ( start : & Self , end : & Self )-> Option < usize > { if * start <= * end { usize :: try_from (* end - * start ). ok ()} else { None }}# [ inline ] fn forward_checked ( start : Self , n : usize )-> Option < Self > { start . checked_add ( n as Self )}# [ inline ] fn backward_checked ( start : Self , n : usize )-> Option < Self > { start . checked_sub ( n as Self )}}# [ allow ( unreachable_patterns )]# [ unstable ( feature = "step_trait" , reason = "recently redesigned" , issue = "42168" )] unsafe impl Step for $i_wider { step_identical_methods ! (); # [ inline ] fn steps_between ( start : & Self , end : & Self )-> Option < usize > { if * start <= * end { match end . checked_sub (* start ){ Some ( result )=> usize :: try_from ( result ). ok (), None => None , }} else { None }}# [ inline ] fn forward_checked ( start : Self , n : usize )-> Option < Self > { start . checked_add ( n as Self )}# [ inline ] fn backward_checked ( start : Self , n : usize )-> Option < Self > { start . checked_sub ( n as Self )}})+ }; } +macro_rules! __ra_macro_fixture60 {($($t : ty )*)=>($(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl ExactSizeIterator for ops :: Range <$t > {})*)} +macro_rules! __ra_macro_fixture61 {($($t : ty )*)=>($(# [ stable ( feature = "inclusive_range" , since = "1.26.0" )] impl ExactSizeIterator for ops :: RangeInclusive <$t > {})*)} +macro_rules! __ra_macro_fixture62 {(@ impls $zero : expr , $one : expr , # [$attr : meta ], $($a : ty )*)=>($(# [$attr ] impl Sum for $a { fn sum < I : Iterator < Item = Self >> ( iter : I )-> Self { iter . fold ($zero , Add :: add )}}# [$attr ] impl Product for $a { fn product < I : Iterator < Item = Self >> ( iter : I )-> Self { iter . fold ($one , Mul :: mul )}}# [$attr ] impl < 'a > Sum <& 'a $a > for $a { fn sum < I : Iterator < Item =& 'a Self >> ( iter : I )-> Self { iter . fold ($zero , Add :: add )}}# [$attr ] impl < 'a > Product <& 'a $a > for $a { fn product < I : Iterator < Item =& 'a Self >> ( iter : I )-> Self { iter . fold ($one , Mul :: mul )}})*); ($($a : ty )*)=>( integer_sum_product ! (@ impls 0 , 1 , # [ stable ( feature = "iter_arith_traits" , since = "1.12.0" )], $($a )*); integer_sum_product ! (@ impls Wrapping ( 0 ), Wrapping ( 1 ), # [ stable ( feature = "wrapping_iter_arith" , since = "1.14.0" )], $(Wrapping <$a >)*); ); } +macro_rules! __ra_macro_fixture63 {($($a : ident )*)=>($(# [ stable ( feature = "iter_arith_traits" , since = "1.12.0" )] impl Sum for $a { fn sum < I : Iterator < Item = Self >> ( iter : I )-> Self { iter . fold ( 0.0 , Add :: add )}}# [ stable ( feature = "iter_arith_traits" , since = "1.12.0" )] impl Product for $a { fn product < I : Iterator < Item = Self >> ( iter : I )-> Self { iter . fold ( 1.0 , Mul :: mul )}}# [ stable ( feature = "iter_arith_traits" , since = "1.12.0" )] impl < 'a > Sum <& 'a $a > for $a { fn sum < I : Iterator < Item =& 'a Self >> ( iter : I )-> Self { iter . fold ( 0.0 , Add :: add )}}# [ stable ( feature = "iter_arith_traits" , since = "1.12.0" )] impl < 'a > Product <& 'a $a > for $a { fn product < I : Iterator < Item =& 'a Self >> ( iter : I )-> Self { iter . fold ( 1.0 , Mul :: mul )}})*)} +macro_rules! __ra_macro_fixture64 {($cfg_cas : meta , $cfg_align : meta , $stable : meta , $stable_cxchg : meta , $stable_debug : meta , $stable_access : meta , $stable_from : meta , $stable_nand : meta , $const_stable : meta , $stable_init_const : meta , $s_int_type : literal , $int_ref : expr , $extra_feature : expr , $min_fn : ident , $max_fn : ident , $align : expr , $atomic_new : expr , $int_type : ident $atomic_type : ident $atomic_init : ident )=>{# [ doc = " An integer type which can be safely shared between threads." ]# [ doc = "" ]# [ doc = " This type has the same in-memory representation as the underlying" ]# [ doc = " integer type, [`" ]# [ doc = $s_int_type ]# [ doc = " `](" ]# [ doc = $int_ref ]# [ doc = " ). For more about the differences between atomic types and" ]# [ doc = " non-atomic types as well as information about the portability of" ]# [ doc = " this type, please see the [module-level documentation]." ]# [ doc = "" ]# [ doc = " **Note:** This type is only available on platforms that support" ]# [ doc = " atomic loads and stores of [`" ]# [ doc = $s_int_type ]# [ doc = " `](" ]# [ doc = $int_ref ]# [ doc = " )." ]# [ doc = "" ]# [ doc = " [module-level documentation]: crate::sync::atomic" ]# [$stable ]# [ repr ( C , align ($align ))] pub struct $atomic_type { v : UnsafeCell <$int_type >, }# [ doc = " An atomic integer initialized to `0`." ]# [$stable_init_const ]# [ rustc_deprecated ( since = "1.34.0" , reason = "the `new` function is now preferred" , suggestion = $atomic_new , )] pub const $atomic_init : $atomic_type = $atomic_type :: new ( 0 ); # [$stable ] impl Default for $atomic_type {# [ inline ] fn default ()-> Self { Self :: new ( Default :: default ())}}# [$stable_from ] impl From <$int_type > for $atomic_type { doc_comment ! { concat ! ( "Converts an `" , stringify ! ($int_type ), "` into an `" , stringify ! ($atomic_type ), "`." ), # [ inline ] fn from ( v : $int_type )-> Self { Self :: new ( v )}}}# [$stable_debug ] impl fmt :: Debug for $atomic_type { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { fmt :: Debug :: fmt (& self . load ( Ordering :: SeqCst ), f )}}# [$stable ] unsafe impl Sync for $atomic_type {} impl $atomic_type { doc_comment ! { concat ! ( "Creates a new atomic integer.\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::" , stringify ! ($atomic_type ), ";\n\nlet atomic_forty_two = " , stringify ! ($atomic_type ), "::new(42);\n```" ), # [ inline ]# [$stable ]# [$const_stable ] pub const fn new ( v : $int_type )-> Self { Self { v : UnsafeCell :: new ( v )}}} doc_comment ! { concat ! ( "Returns a mutable reference to the underlying integer.\n\nThis is safe because the mutable reference guarantees that no other threads are\nconcurrently accessing the atomic data.\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet mut some_var = " , stringify ! ($atomic_type ), "::new(10);\nassert_eq!(*some_var.get_mut(), 10);\n*some_var.get_mut() = 5;\nassert_eq!(some_var.load(Ordering::SeqCst), 5);\n```" ), # [ inline ]# [$stable_access ] pub fn get_mut (& mut self )-> & mut $int_type { self . v . get_mut ()}} doc_comment ! { concat ! ( "Get atomic access to a `&mut " , stringify ! ($int_type ), "`.\n\n" , if_not_8_bit ! {$int_type , concat ! ( "**Note:** This function is only available on targets where `" , stringify ! ($int_type ), "` has an alignment of " , $align , " bytes." )}, "\n\n# Examples\n\n```\n#![feature(atomic_from_mut)]\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet mut some_int = 123;\nlet a = " , stringify ! ($atomic_type ), "::from_mut(&mut some_int);\na.store(100, Ordering::Relaxed);\nassert_eq!(some_int, 100);\n```\n " ), # [ inline ]# [$cfg_align ]# [ unstable ( feature = "atomic_from_mut" , issue = "76314" )] pub fn from_mut ( v : & mut $int_type )-> & Self { use crate :: mem :: align_of ; let []= [(); align_of ::< Self > ()- align_of ::<$int_type > ()]; unsafe {&* ( v as * mut $int_type as * mut Self )}}} doc_comment ! { concat ! ( "Consumes the atomic and returns the contained value.\n\nThis is safe because passing `self` by value guarantees that no other threads are\nconcurrently accessing the atomic data.\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::" , stringify ! ($atomic_type ), ";\n\nlet some_var = " , stringify ! ($atomic_type ), "::new(5);\nassert_eq!(some_var.into_inner(), 5);\n```" ), # [ inline ]# [$stable_access ]# [ rustc_const_unstable ( feature = "const_cell_into_inner" , issue = "78729" )] pub const fn into_inner ( self )-> $int_type { self . v . into_inner ()}} doc_comment ! { concat ! ( "Loads a value from the atomic integer.\n\n`load` takes an [`Ordering`] argument which describes the memory ordering of this operation.\nPossible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].\n\n# Panics\n\nPanics if `order` is [`Release`] or [`AcqRel`].\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet some_var = " , stringify ! ($atomic_type ), "::new(5);\n\nassert_eq!(some_var.load(Ordering::Relaxed), 5);\n```" ), # [ inline ]# [$stable ] pub fn load (& self , order : Ordering )-> $int_type { unsafe { atomic_load ( self . v . get (), order )}}} doc_comment ! { concat ! ( "Stores a value into the atomic integer.\n\n`store` takes an [`Ordering`] argument which describes the memory ordering of this operation.\n Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].\n\n# Panics\n\nPanics if `order` is [`Acquire`] or [`AcqRel`].\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet some_var = " , stringify ! ($atomic_type ), "::new(5);\n\nsome_var.store(10, Ordering::Relaxed);\nassert_eq!(some_var.load(Ordering::Relaxed), 10);\n```" ), # [ inline ]# [$stable ] pub fn store (& self , val : $int_type , order : Ordering ){ unsafe { atomic_store ( self . v . get (), val , order ); }}} doc_comment ! { concat ! ( "Stores a value into the atomic integer, returning the previous value.\n\n`swap` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet some_var = " , stringify ! ($atomic_type ), "::new(5);\n\nassert_eq!(some_var.swap(10, Ordering::Relaxed), 5);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn swap (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_swap ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Stores a value into the atomic integer if the current value is the same as\nthe `current` value.\n\nThe return value is always the previous value. If it is equal to `current`, then the\nvalue was updated.\n\n`compare_and_swap` also takes an [`Ordering`] argument which describes the memory\nordering of this operation. Notice that even when using [`AcqRel`], the operation\nmight fail and hence just perform an `Acquire` load, but not have `Release` semantics.\nUsing [`Acquire`] makes the store part of this operation [`Relaxed`] if it\nhappens, and using [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet some_var = " , stringify ! ($atomic_type ), "::new(5);\n\nassert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);\nassert_eq!(some_var.load(Ordering::Relaxed), 10);\n\nassert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);\nassert_eq!(some_var.load(Ordering::Relaxed), 10);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn compare_and_swap (& self , current : $int_type , new : $int_type , order : Ordering )-> $int_type { match self . compare_exchange ( current , new , order , strongest_failure_ordering ( order )){ Ok ( x )=> x , Err ( x )=> x , }}} doc_comment ! { concat ! ( "Stores a value into the atomic integer if the current value is the same as\nthe `current` value.\n\nThe return value is a result indicating whether the new value was written and\ncontaining the previous value. On success this value is guaranteed to be equal to\n`current`.\n\n`compare_exchange` takes two [`Ordering`] arguments to describe the memory\nordering of this operation. The first describes the required ordering if the\noperation succeeds while the second describes the required ordering when the\noperation fails. Using [`Acquire`] as success ordering makes the store part\nof this operation [`Relaxed`], and using [`Release`] makes the successful load\n[`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]\nand must be equivalent to or weaker than the success ordering.\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet some_var = " , stringify ! ($atomic_type ), "::new(5);\n\nassert_eq!(some_var.compare_exchange(5, 10,\n Ordering::Acquire,\n Ordering::Relaxed),\n Ok(5));\nassert_eq!(some_var.load(Ordering::Relaxed), 10);\n\nassert_eq!(some_var.compare_exchange(6, 12,\n Ordering::SeqCst,\n Ordering::Acquire),\n Err(10));\nassert_eq!(some_var.load(Ordering::Relaxed), 10);\n```" ), # [ inline ]# [$stable_cxchg ]# [$cfg_cas ] pub fn compare_exchange (& self , current : $int_type , new : $int_type , success : Ordering , failure : Ordering )-> Result <$int_type , $int_type > { unsafe { atomic_compare_exchange ( self . v . get (), current , new , success , failure )}}} doc_comment ! { concat ! ( "Stores a value into the atomic integer if the current value is the same as\nthe `current` value.\n\nUnlike [`" , stringify ! ($atomic_type ), "::compare_exchange`], this function is allowed to spuriously fail even\nwhen the comparison succeeds, which can result in more efficient code on some\nplatforms. The return value is a result indicating whether the new value was\nwritten and containing the previous value.\n\n`compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory\nordering of this operation. The first describes the required ordering if the\noperation succeeds while the second describes the required ordering when the\noperation fails. Using [`Acquire`] as success ordering makes the store part\nof this operation [`Relaxed`], and using [`Release`] makes the successful load\n[`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]\nand must be equivalent to or weaker than the success ordering.\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet val = " , stringify ! ($atomic_type ), "::new(4);\n\nlet mut old = val.load(Ordering::Relaxed);\nloop {\n let new = old * 2;\n match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {\n Ok(_) => break,\n Err(x) => old = x,\n }\n}\n```" ), # [ inline ]# [$stable_cxchg ]# [$cfg_cas ] pub fn compare_exchange_weak (& self , current : $int_type , new : $int_type , success : Ordering , failure : Ordering )-> Result <$int_type , $int_type > { unsafe { atomic_compare_exchange_weak ( self . v . get (), current , new , success , failure )}}} doc_comment ! { concat ! ( "Adds to the current value, returning the previous value.\n\nThis operation wraps around on overflow.\n\n`fetch_add` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(0);\nassert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);\nassert_eq!(foo.load(Ordering::SeqCst), 10);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn fetch_add (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_add ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Subtracts from the current value, returning the previous value.\n\nThis operation wraps around on overflow.\n\n`fetch_sub` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(20);\nassert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);\nassert_eq!(foo.load(Ordering::SeqCst), 10);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn fetch_sub (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_sub ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Bitwise \"and\" with the current value.\n\nPerforms a bitwise \"and\" operation on the current value and the argument `val`, and\nsets the new value to the result.\n\nReturns the previous value.\n\n`fetch_and` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(0b101101);\nassert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);\nassert_eq!(foo.load(Ordering::SeqCst), 0b100001);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn fetch_and (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_and ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Bitwise \"nand\" with the current value.\n\nPerforms a bitwise \"nand\" operation on the current value and the argument `val`, and\nsets the new value to the result.\n\nReturns the previous value.\n\n`fetch_nand` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "\nuse std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(0x13);\nassert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);\nassert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));\n```" ), # [ inline ]# [$stable_nand ]# [$cfg_cas ] pub fn fetch_nand (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_nand ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Bitwise \"or\" with the current value.\n\nPerforms a bitwise \"or\" operation on the current value and the argument `val`, and\nsets the new value to the result.\n\nReturns the previous value.\n\n`fetch_or` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(0b101101);\nassert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);\nassert_eq!(foo.load(Ordering::SeqCst), 0b111111);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn fetch_or (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_or ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Bitwise \"xor\" with the current value.\n\nPerforms a bitwise \"xor\" operation on the current value and the argument `val`, and\nsets the new value to the result.\n\nReturns the previous value.\n\n`fetch_xor` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(0b101101);\nassert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);\nassert_eq!(foo.load(Ordering::SeqCst), 0b011110);\n```" ), # [ inline ]# [$stable ]# [$cfg_cas ] pub fn fetch_xor (& self , val : $int_type , order : Ordering )-> $int_type { unsafe { atomic_xor ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Fetches the value, and applies a function to it that returns an optional\nnew value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else\n`Err(previous_value)`.\n\nNote: This may call the function multiple times if the value has been changed from other threads in\nthe meantime, as long as the function returns `Some(_)`, but the function will have been applied\nonly once to the stored value.\n\n`fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.\nThe first describes the required ordering for when the operation finally succeeds while the second\ndescribes the required ordering for loads. These correspond to the success and failure orderings of\n[`" , stringify ! ($atomic_type ), "::compare_exchange`] respectively.\n\nUsing [`Acquire`] as success ordering makes the store part\nof this operation [`Relaxed`], and using [`Release`] makes the final successful load\n[`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]\nand must be equivalent to or weaker than the success ordering.\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```rust\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet x = " , stringify ! ($atomic_type ), "::new(7);\nassert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));\nassert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));\nassert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));\nassert_eq!(x.load(Ordering::SeqCst), 9);\n```" ), # [ inline ]# [ stable ( feature = "no_more_cas" , since = "1.45.0" )]# [$cfg_cas ] pub fn fetch_update < F > (& self , set_order : Ordering , fetch_order : Ordering , mut f : F )-> Result <$int_type , $int_type > where F : FnMut ($int_type )-> Option <$int_type > { let mut prev = self . load ( fetch_order ); while let Some ( next )= f ( prev ){ match self . compare_exchange_weak ( prev , next , set_order , fetch_order ){ x @ Ok (_)=> return x , Err ( next_prev )=> prev = next_prev }} Err ( prev )}} doc_comment ! { concat ! ( "Maximum with the current value.\n\nFinds the maximum of the current value and the argument `val`, and\nsets the new value to the result.\n\nReturns the previous value.\n\n`fetch_max` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(23);\nassert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);\nassert_eq!(foo.load(Ordering::SeqCst), 42);\n```\n\nIf you want to obtain the maximum value in one step, you can use the following:\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(23);\nlet bar = 42;\nlet max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);\nassert!(max_foo == 42);\n```" ), # [ inline ]# [ stable ( feature = "atomic_min_max" , since = "1.45.0" )]# [$cfg_cas ] pub fn fetch_max (& self , val : $int_type , order : Ordering )-> $int_type { unsafe {$max_fn ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Minimum with the current value.\n\nFinds the minimum of the current value and the argument `val`, and\nsets the new value to the result.\n\nReturns the previous value.\n\n`fetch_min` takes an [`Ordering`] argument which describes the memory ordering\nof this operation. All ordering modes are possible. Note that using\n[`Acquire`] makes the store part of this operation [`Relaxed`], and\nusing [`Release`] makes the load part [`Relaxed`].\n\n**Note**: This method is only available on platforms that support atomic\noperations on [`" , $s_int_type , "`](" , $int_ref , ").\n\n# Examples\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(23);\nassert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);\nassert_eq!(foo.load(Ordering::Relaxed), 23);\nassert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);\nassert_eq!(foo.load(Ordering::Relaxed), 22);\n```\n\nIf you want to obtain the minimum value in one step, you can use the following:\n\n```\n" , $extra_feature , "use std::sync::atomic::{" , stringify ! ($atomic_type ), ", Ordering};\n\nlet foo = " , stringify ! ($atomic_type ), "::new(23);\nlet bar = 12;\nlet min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);\nassert_eq!(min_foo, 12);\n```" ), # [ inline ]# [ stable ( feature = "atomic_min_max" , since = "1.45.0" )]# [$cfg_cas ] pub fn fetch_min (& self , val : $int_type , order : Ordering )-> $int_type { unsafe {$min_fn ( self . v . get (), val , order )}}} doc_comment ! { concat ! ( "Returns a mutable pointer to the underlying integer.\n\nDoing non-atomic reads and writes on the resulting integer can be a data race.\nThis method is mostly useful for FFI, where the function signature may use\n`*mut " , stringify ! ($int_type ), "` instead of `&" , stringify ! ($atomic_type ), "`.\n\nReturning an `*mut` pointer from a shared reference to this atomic is safe because the\natomic types work with interior mutability. All modifications of an atomic change the value\nthrough a shared reference, and can do so safely as long as they use atomic operations. Any\nuse of the returned raw pointer requires an `unsafe` block and still has to uphold the same\nrestriction: operations on it must be atomic.\n\n# Examples\n\n```ignore (extern-declaration)\n# fn main() {\n" , $extra_feature , "use std::sync::atomic::" , stringify ! ($atomic_type ), ";\n\nextern {\n fn my_atomic_op(arg: *mut " , stringify ! ($int_type ), ");\n}\n\nlet mut atomic = " , stringify ! ($atomic_type ), "::new(1);\n" , "unsafe {\n my_atomic_op(atomic.as_mut_ptr());\n}\n# }\n```" ), # [ inline ]# [ unstable ( feature = "atomic_mut_ptr" , reason = "recently added" , issue = "66893" )] pub fn as_mut_ptr (& self )-> * mut $int_type { self . v . get ()}}}}} +macro_rules! __ra_macro_fixture65 {($($target_pointer_width : literal $align : literal )* )=>{$(# [ cfg ( target_has_atomic_load_store = "ptr" )]# [ cfg ( target_pointer_width = $target_pointer_width )] atomic_int ! { cfg ( target_has_atomic = "ptr" ), cfg ( target_has_atomic_equal_alignment = "ptr" ), stable ( feature = "rust1" , since = "1.0.0" ), stable ( feature = "extended_compare_and_swap" , since = "1.10.0" ), stable ( feature = "atomic_debug" , since = "1.3.0" ), stable ( feature = "atomic_access" , since = "1.15.0" ), stable ( feature = "atomic_from" , since = "1.23.0" ), stable ( feature = "atomic_nand" , since = "1.27.0" ), rustc_const_stable ( feature = "const_integer_atomics" , since = "1.34.0" ), stable ( feature = "rust1" , since = "1.0.0" ), "isize" , "../../../std/primitive.isize.html" , "" , atomic_min , atomic_max , $align , "AtomicIsize::new(0)" , isize AtomicIsize ATOMIC_ISIZE_INIT }# [ cfg ( target_has_atomic_load_store = "ptr" )]# [ cfg ( target_pointer_width = $target_pointer_width )] atomic_int ! { cfg ( target_has_atomic = "ptr" ), cfg ( target_has_atomic_equal_alignment = "ptr" ), stable ( feature = "rust1" , since = "1.0.0" ), stable ( feature = "extended_compare_and_swap" , since = "1.10.0" ), stable ( feature = "atomic_debug" , since = "1.3.0" ), stable ( feature = "atomic_access" , since = "1.15.0" ), stable ( feature = "atomic_from" , since = "1.23.0" ), stable ( feature = "atomic_nand" , since = "1.27.0" ), rustc_const_stable ( feature = "const_integer_atomics" , since = "1.34.0" ), stable ( feature = "rust1" , since = "1.0.0" ), "usize" , "../../../std/primitive.usize.html" , "" , atomic_umin , atomic_umax , $align , "AtomicUsize::new(0)" , usize AtomicUsize ATOMIC_USIZE_INIT })* }; } +macro_rules! __ra_macro_fixture66 {($ty : ident )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Debug for $ty { fn fmt (& self , fmt : & mut Formatter < '_ >)-> Result { float_to_decimal_common ( fmt , self , true , 1 )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Display for $ty { fn fmt (& self , fmt : & mut Formatter < '_ >)-> Result { float_to_decimal_common ( fmt , self , false , 0 )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl LowerExp for $ty { fn fmt (& self , fmt : & mut Formatter < '_ >)-> Result { float_to_exponential_common ( fmt , self , false )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl UpperExp for $ty { fn fmt (& self , fmt : & mut Formatter < '_ >)-> Result { float_to_exponential_common ( fmt , self , true )}}}; } +macro_rules! __ra_macro_fixture67 {($($t : ident )*)=>($(impl DisplayInt for $t { fn zero ()-> Self { 0 } fn from_u8 ( u : u8 )-> Self { u as Self } fn to_u8 (& self )-> u8 {* self as u8 } fn to_u16 (& self )-> u16 {* self as u16 } fn to_u32 (& self )-> u32 {* self as u32 } fn to_u64 (& self )-> u64 {* self as u64 } fn to_u128 (& self )-> u128 {* self as u128 }})* )} +macro_rules! __ra_macro_fixture68 {($($t : ident )*)=>($(impl DisplayInt for $t { fn zero ()-> Self { 0 } fn from_u8 ( u : u8 )-> Self { u as Self } fn to_u8 (& self )-> u8 {* self as u8 } fn to_u16 (& self )-> u16 {* self as u16 } fn to_u32 (& self )-> u32 {* self as u32 } fn to_u64 (& self )-> u64 {* self as u64 } fn to_u128 (& self )-> u128 {* self as u128 }})* )} +macro_rules! __ra_macro_fixture69 {($T : ident , $base : expr , $prefix : expr , $($x : pat =>$conv : expr ),+)=>{ impl GenericRadix for $T { const BASE : u8 = $base ; const PREFIX : & 'static str = $prefix ; fn digit ( x : u8 )-> u8 { match x {$($x =>$conv ,)+ x => panic ! ( "number not in the range 0..={}: {}" , Self :: BASE - 1 , x ), }}}}} +macro_rules! __ra_macro_fixture70 {($Int : ident , $Uint : ident )=>{ int_base ! { fmt :: Binary for $Int as $Uint -> Binary } int_base ! { fmt :: Octal for $Int as $Uint -> Octal } int_base ! { fmt :: LowerHex for $Int as $Uint -> LowerHex } int_base ! { fmt :: UpperHex for $Int as $Uint -> UpperHex } int_base ! { fmt :: Binary for $Uint as $Uint -> Binary } int_base ! { fmt :: Octal for $Uint as $Uint -> Octal } int_base ! { fmt :: LowerHex for $Uint as $Uint -> LowerHex } int_base ! { fmt :: UpperHex for $Uint as $Uint -> UpperHex }}; } +macro_rules! __ra_macro_fixture71 {($($T : ident )*)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl fmt :: Debug for $T {# [ inline ] fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { if f . debug_lower_hex (){ fmt :: LowerHex :: fmt ( self , f )} else if f . debug_upper_hex (){ fmt :: UpperHex :: fmt ( self , f )} else { fmt :: Display :: fmt ( self , f )}}})*}; } +macro_rules! __ra_macro_fixture72 {($($t : ident ),* as $u : ident via $conv_fn : ident named $name : ident )=>{ fn $name ( mut n : $u , is_nonnegative : bool , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { let mut buf = [ MaybeUninit ::< u8 >:: uninit (); 39 ]; let mut curr = buf . len () as isize ; let buf_ptr = MaybeUninit :: slice_as_mut_ptr (& mut buf ); let lut_ptr = DEC_DIGITS_LUT . as_ptr (); unsafe { assert ! ( crate :: mem :: size_of ::<$u > ()>= 2 ); while n >= 10000 { let rem = ( n % 10000 ) as isize ; n /= 10000 ; let d1 = ( rem / 100 )<< 1 ; let d2 = ( rem % 100 )<< 1 ; curr -= 4 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); ptr :: copy_nonoverlapping ( lut_ptr . offset ( d2 ), buf_ptr . offset ( curr + 2 ), 2 ); } let mut n = n as isize ; if n >= 100 { let d1 = ( n % 100 )<< 1 ; n /= 100 ; curr -= 2 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); } if n < 10 { curr -= 1 ; * buf_ptr . offset ( curr )= ( n as u8 )+ b'0' ; } else { let d1 = n << 1 ; curr -= 2 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); }} let buf_slice = unsafe { str :: from_utf8_unchecked ( slice :: from_raw_parts ( buf_ptr . offset ( curr ), buf . len ()- curr as usize ))}; f . pad_integral ( is_nonnegative , "" , buf_slice )}$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl fmt :: Display for $t {# [ allow ( unused_comparisons )] fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { let is_nonnegative = * self >= 0 ; let n = if is_nonnegative { self .$conv_fn ()} else {(! self .$conv_fn ()). wrapping_add ( 1 )}; $name ( n , is_nonnegative , f )}})* }; } +macro_rules! __ra_macro_fixture73 {($($t : ident ),* as $u : ident via $conv_fn : ident named $name : ident )=>{ fn $name ( mut n : $u , is_nonnegative : bool , upper : bool , f : & mut fmt :: Formatter < '_ > )-> fmt :: Result { let ( mut n , mut exponent , trailing_zeros , added_precision )= { let mut exponent = 0 ; while n % 10 == 0 && n >= 10 { n /= 10 ; exponent += 1 ; } let trailing_zeros = exponent ; let ( added_precision , subtracted_precision )= match f . precision (){ Some ( fmt_prec )=>{ let mut tmp = n ; let mut prec = 0 ; while tmp >= 10 { tmp /= 10 ; prec += 1 ; }( fmt_prec . saturating_sub ( prec ), prec . saturating_sub ( fmt_prec ))} None =>( 0 , 0 )}; for _ in 1 .. subtracted_precision { n /= 10 ; exponent += 1 ; } if subtracted_precision != 0 { let rem = n % 10 ; n /= 10 ; exponent += 1 ; if rem >= 5 { n += 1 ; }}( n , exponent , trailing_zeros , added_precision )}; let mut buf = [ MaybeUninit ::< u8 >:: uninit (); 40 ]; let mut curr = buf . len () as isize ; let buf_ptr = MaybeUninit :: slice_as_mut_ptr (& mut buf ); let lut_ptr = DEC_DIGITS_LUT . as_ptr (); while n >= 100 { let d1 = (( n % 100 ) as isize )<< 1 ; curr -= 2 ; unsafe { ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); } n /= 100 ; exponent += 2 ; } let mut n = n as isize ; if n >= 10 { curr -= 1 ; unsafe {* buf_ptr . offset ( curr )= ( n as u8 % 10_u8 )+ b'0' ; } n /= 10 ; exponent += 1 ; } if exponent != trailing_zeros || added_precision != 0 { curr -= 1 ; unsafe {* buf_ptr . offset ( curr )= b'.' ; }} let buf_slice = unsafe { curr -= 1 ; * buf_ptr . offset ( curr )= ( n as u8 )+ b'0' ; let len = buf . len ()- curr as usize ; slice :: from_raw_parts ( buf_ptr . offset ( curr ), len )}; let mut exp_buf = [ MaybeUninit ::< u8 >:: uninit (); 3 ]; let exp_ptr = MaybeUninit :: slice_as_mut_ptr (& mut exp_buf ); let exp_slice = unsafe {* exp_ptr . offset ( 0 )= if upper { b'E' } else { b'e' }; let len = if exponent < 10 {* exp_ptr . offset ( 1 )= ( exponent as u8 )+ b'0' ; 2 } else { let off = exponent << 1 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( off ), exp_ptr . offset ( 1 ), 2 ); 3 }; slice :: from_raw_parts ( exp_ptr , len )}; let parts = & [ flt2dec :: Part :: Copy ( buf_slice ), flt2dec :: Part :: Zero ( added_precision ), flt2dec :: Part :: Copy ( exp_slice )]; let sign = if ! is_nonnegative { "-" } else if f . sign_plus (){ "+" } else { "" }; let formatted = flt2dec :: Formatted { sign , parts }; f . pad_formatted_parts (& formatted )}$(# [ stable ( feature = "integer_exp_format" , since = "1.42.0" )] impl fmt :: LowerExp for $t {# [ allow ( unused_comparisons )] fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { let is_nonnegative = * self >= 0 ; let n = if is_nonnegative { self .$conv_fn ()} else {(! self .$conv_fn ()). wrapping_add ( 1 )}; $name ( n , is_nonnegative , false , f )}})* $(# [ stable ( feature = "integer_exp_format" , since = "1.42.0" )] impl fmt :: UpperExp for $t {# [ allow ( unused_comparisons )] fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { let is_nonnegative = * self >= 0 ; let n = if is_nonnegative { self .$conv_fn ()} else {(! self .$conv_fn ()). wrapping_add ( 1 )}; $name ( n , is_nonnegative , true , f )}})* }; } +macro_rules! __ra_macro_fixture74 {($($tr : ident ),*)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized + $tr > $tr for & T { fn fmt (& self , f : & mut Formatter < '_ >)-> Result {$tr :: fmt (&** self , f )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T : ? Sized + $tr > $tr for & mut T { fn fmt (& self , f : & mut Formatter < '_ >)-> Result {$tr :: fmt (&** self , f )}})* }} +macro_rules! __ra_macro_fixture75 {()=>(); ($($name : ident ,)+ )=>(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($name : Debug ),+> Debug for ($($name ,)+) where last_type ! ($($name ,)+): ? Sized {# [ allow ( non_snake_case , unused_assignments )] fn fmt (& self , f : & mut Formatter < '_ >)-> Result { let mut builder = f . debug_tuple ( "" ); let ($(ref $name ,)+)= * self ; $(builder . field (&$name ); )+ builder . finish ()}} peel ! {$($name ,)+ })} +macro_rules! __ra_macro_fixture76 {($(($ty : ident , $meth : ident ),)*)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Hash for $ty { fn hash < H : Hasher > (& self , state : & mut H ){ state .$meth (* self )} fn hash_slice < H : Hasher > ( data : & [$ty ], state : & mut H ){ let newlen = data . len ()* mem :: size_of ::<$ty > (); let ptr = data . as_ptr () as * const u8 ; state . write ( unsafe { slice :: from_raw_parts ( ptr , newlen )})}})*}} +macro_rules! __ra_macro_fixture77 {()=>(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Hash for (){ fn hash < H : Hasher > (& self , _state : & mut H ){}}); ($($name : ident )+)=>(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($name : Hash ),+> Hash for ($($name ,)+) where last_type ! ($($name ,)+): ? Sized {# [ allow ( non_snake_case )] fn hash < S : Hasher > (& self , state : & mut S ){ let ($(ref $name ,)+)= * self ; $($name . hash ( state );)+ }}); } +macro_rules! __ra_macro_fixture78 {($([$($p : tt )*]$t : ty ,)*)=>{$(impl <$($p )*> AlwaysApplicableOrd for $t {})* }} +macro_rules! __ra_macro_fixture79 {($traitname : ident , $($ty : ty )*)=>{$(impl $traitname <$ty > for $ty {})* }} +macro_rules! __ra_macro_fixture80 {( struct $name : ident -> $ptr : ty , $elem : ty , $raw_mut : tt , {$($mut_ : tt )?}, {$($extra : tt )*})=>{ macro_rules ! next_unchecked {($self : ident )=>{& $($mut_ )? *$self . post_inc_start ( 1 )}} macro_rules ! next_back_unchecked {($self : ident )=>{& $($mut_ )? *$self . pre_dec_end ( 1 )}} macro_rules ! zst_shrink {($self : ident , $n : ident )=>{$self . end = ($self . end as * $raw_mut u8 ). wrapping_offset (-$n ) as * $raw_mut T ; }} impl < 'a , T > $name < 'a , T > {# [ inline ( always )] fn make_slice (& self )-> & 'a [ T ]{ unsafe { from_raw_parts ( self . ptr . as_ptr (), len ! ( self ))}}# [ inline ( always )] unsafe fn post_inc_start (& mut self , offset : isize )-> * $raw_mut T { if mem :: size_of ::< T > ()== 0 { zst_shrink ! ( self , offset ); self . ptr . as_ptr ()} else { let old = self . ptr . as_ptr (); self . ptr = unsafe { NonNull :: new_unchecked ( self . ptr . as_ptr (). offset ( offset ))}; old }}# [ inline ( always )] unsafe fn pre_dec_end (& mut self , offset : isize )-> * $raw_mut T { if mem :: size_of ::< T > ()== 0 { zst_shrink ! ( self , offset ); self . ptr . as_ptr ()} else { self . end = unsafe { self . end . offset (- offset )}; self . end }}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < T > ExactSizeIterator for $name < '_ , T > {# [ inline ( always )] fn len (& self )-> usize { len ! ( self )}# [ inline ( always )] fn is_empty (& self )-> bool { is_empty ! ( self )}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < 'a , T > Iterator for $name < 'a , T > { type Item = $elem ; # [ inline ] fn next (& mut self )-> Option <$elem > { unsafe { assume (! self . ptr . as_ptr (). is_null ()); if mem :: size_of ::< T > ()!= 0 { assume (! self . end . is_null ()); } if is_empty ! ( self ){ None } else { Some ( next_unchecked ! ( self ))}}}# [ inline ] fn size_hint (& self )-> ( usize , Option < usize >){ let exact = len ! ( self ); ( exact , Some ( exact ))}# [ inline ] fn count ( self )-> usize { len ! ( self )}# [ inline ] fn nth (& mut self , n : usize )-> Option <$elem > { if n >= len ! ( self ){ if mem :: size_of ::< T > ()== 0 { self . end = self . ptr . as_ptr (); } else { unsafe { self . ptr = NonNull :: new_unchecked ( self . end as * mut T ); }} return None ; } unsafe { self . post_inc_start ( n as isize ); Some ( next_unchecked ! ( self ))}}# [ inline ] fn last ( mut self )-> Option <$elem > { self . next_back ()}# [ inline ] fn for_each < F > ( mut self , mut f : F ) where Self : Sized , F : FnMut ( Self :: Item ), { while let Some ( x )= self . next (){ f ( x ); }}# [ inline ] fn all < F > (& mut self , mut f : F )-> bool where Self : Sized , F : FnMut ( Self :: Item )-> bool , { while let Some ( x )= self . next (){ if ! f ( x ){ return false ; }} true }# [ inline ] fn any < F > (& mut self , mut f : F )-> bool where Self : Sized , F : FnMut ( Self :: Item )-> bool , { while let Some ( x )= self . next (){ if f ( x ){ return true ; }} false }# [ inline ] fn find < P > (& mut self , mut predicate : P )-> Option < Self :: Item > where Self : Sized , P : FnMut (& Self :: Item )-> bool , { while let Some ( x )= self . next (){ if predicate (& x ){ return Some ( x ); }} None }# [ inline ] fn find_map < B , F > (& mut self , mut f : F )-> Option < B > where Self : Sized , F : FnMut ( Self :: Item )-> Option < B >, { while let Some ( x )= self . next (){ if let Some ( y )= f ( x ){ return Some ( y ); }} None }# [ inline ]# [ rustc_inherit_overflow_checks ] fn position < P > (& mut self , mut predicate : P )-> Option < usize > where Self : Sized , P : FnMut ( Self :: Item )-> bool , { let n = len ! ( self ); let mut i = 0 ; while let Some ( x )= self . next (){ if predicate ( x ){ unsafe { assume ( i < n )}; return Some ( i ); } i += 1 ; } None }# [ inline ] fn rposition < P > (& mut self , mut predicate : P )-> Option < usize > where P : FnMut ( Self :: Item )-> bool , Self : Sized + ExactSizeIterator + DoubleEndedIterator { let n = len ! ( self ); let mut i = n ; while let Some ( x )= self . next_back (){ i -= 1 ; if predicate ( x ){ unsafe { assume ( i < n )}; return Some ( i ); }} None }# [ doc ( hidden )] unsafe fn __iterator_get_unchecked (& mut self , idx : usize )-> Self :: Item { unsafe {& $($mut_ )? * self . ptr . as_ptr (). add ( idx )}}$($extra )* }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < 'a , T > DoubleEndedIterator for $name < 'a , T > {# [ inline ] fn next_back (& mut self )-> Option <$elem > { unsafe { assume (! self . ptr . as_ptr (). is_null ()); if mem :: size_of ::< T > ()!= 0 { assume (! self . end . is_null ()); } if is_empty ! ( self ){ None } else { Some ( next_back_unchecked ! ( self ))}}}# [ inline ] fn nth_back (& mut self , n : usize )-> Option <$elem > { if n >= len ! ( self ){ self . end = self . ptr . as_ptr (); return None ; } unsafe { self . pre_dec_end ( n as isize ); Some ( next_back_unchecked ! ( self ))}}}# [ stable ( feature = "fused" , since = "1.26.0" )] impl < T > FusedIterator for $name < '_ , T > {}# [ unstable ( feature = "trusted_len" , issue = "37572" )] unsafe impl < T > TrustedLen for $name < '_ , T > {}}} +macro_rules! __ra_macro_fixture81 {($name : ident : $elem : ident , $iter_of : ty )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl < 'a , $elem , P > Iterator for $name < 'a , $elem , P > where P : FnMut (& T )-> bool , { type Item = $iter_of ; # [ inline ] fn next (& mut self )-> Option <$iter_of > { self . inner . next ()}# [ inline ] fn size_hint (& self )-> ( usize , Option < usize >){ self . inner . size_hint ()}}# [ stable ( feature = "fused" , since = "1.26.0" )] impl < 'a , $elem , P > FusedIterator for $name < 'a , $elem , P > where P : FnMut (& T )-> bool {}}; } +macro_rules! __ra_macro_fixture82 {( clone $t : ident with |$s : ident | $e : expr )=>{ impl < 'a , P > Clone for $t < 'a , P > where P : Pattern < 'a , Searcher : Clone >, { fn clone (& self )-> Self { let $s = self ; $e }}}; } +macro_rules! __ra_macro_fixture83 {{ forward : $(# [$forward_iterator_attribute : meta ])* struct $forward_iterator : ident ; reverse : $(# [$reverse_iterator_attribute : meta ])* struct $reverse_iterator : ident ; stability : $(# [$common_stability_attribute : meta ])* internal : $internal_iterator : ident yielding ($iterty : ty ); delegate $($t : tt )* }=>{$(# [$forward_iterator_attribute ])* $(# [$common_stability_attribute ])* pub struct $forward_iterator < 'a , P : Pattern < 'a >> ( pub ( super )$internal_iterator < 'a , P >); $(# [$common_stability_attribute ])* impl < 'a , P > fmt :: Debug for $forward_iterator < 'a , P > where P : Pattern < 'a , Searcher : fmt :: Debug >, { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { f . debug_tuple ( stringify ! ($forward_iterator )). field (& self . 0 ). finish ()}}$(# [$common_stability_attribute ])* impl < 'a , P : Pattern < 'a >> Iterator for $forward_iterator < 'a , P > { type Item = $iterty ; # [ inline ] fn next (& mut self )-> Option <$iterty > { self . 0 . next ()}}$(# [$common_stability_attribute ])* impl < 'a , P > Clone for $forward_iterator < 'a , P > where P : Pattern < 'a , Searcher : Clone >, { fn clone (& self )-> Self {$forward_iterator ( self . 0 . clone ())}}$(# [$reverse_iterator_attribute ])* $(# [$common_stability_attribute ])* pub struct $reverse_iterator < 'a , P : Pattern < 'a >> ( pub ( super )$internal_iterator < 'a , P >); $(# [$common_stability_attribute ])* impl < 'a , P > fmt :: Debug for $reverse_iterator < 'a , P > where P : Pattern < 'a , Searcher : fmt :: Debug >, { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { f . debug_tuple ( stringify ! ($reverse_iterator )). field (& self . 0 ). finish ()}}$(# [$common_stability_attribute ])* impl < 'a , P > Iterator for $reverse_iterator < 'a , P > where P : Pattern < 'a , Searcher : ReverseSearcher < 'a >>, { type Item = $iterty ; # [ inline ] fn next (& mut self )-> Option <$iterty > { self . 0 . next_back ()}}$(# [$common_stability_attribute ])* impl < 'a , P > Clone for $reverse_iterator < 'a , P > where P : Pattern < 'a , Searcher : Clone >, { fn clone (& self )-> Self {$reverse_iterator ( self . 0 . clone ())}}# [ stable ( feature = "fused" , since = "1.26.0" )] impl < 'a , P : Pattern < 'a >> FusedIterator for $forward_iterator < 'a , P > {}# [ stable ( feature = "fused" , since = "1.26.0" )] impl < 'a , P > FusedIterator for $reverse_iterator < 'a , P > where P : Pattern < 'a , Searcher : ReverseSearcher < 'a >>, {} generate_pattern_iterators ! ($($t )* with $(# [$common_stability_attribute ])*, $forward_iterator , $reverse_iterator , $iterty ); }; { double ended ; with $(# [$common_stability_attribute : meta ])*, $forward_iterator : ident , $reverse_iterator : ident , $iterty : ty }=>{$(# [$common_stability_attribute ])* impl < 'a , P > DoubleEndedIterator for $forward_iterator < 'a , P > where P : Pattern < 'a , Searcher : DoubleEndedSearcher < 'a >>, {# [ inline ] fn next_back (& mut self )-> Option <$iterty > { self . 0 . next_back ()}}$(# [$common_stability_attribute ])* impl < 'a , P > DoubleEndedIterator for $reverse_iterator < 'a , P > where P : Pattern < 'a , Searcher : DoubleEndedSearcher < 'a >>, {# [ inline ] fn next_back (& mut self )-> Option <$iterty > { self . 0 . next ()}}}; { single ended ; with $(# [$common_stability_attribute : meta ])*, $forward_iterator : ident , $reverse_iterator : ident , $iterty : ty }=>{}} +macro_rules! __ra_macro_fixture84 {($($Name : ident ),+)=>{$(# [ stable ( feature = "str_escape" , since = "1.34.0" )] impl < 'a > fmt :: Display for $Name < 'a > { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { self . clone (). try_for_each (| c | f . write_char ( c ))}}# [ stable ( feature = "str_escape" , since = "1.34.0" )] impl < 'a > Iterator for $Name < 'a > { type Item = char ; # [ inline ] fn next (& mut self )-> Option < char > { self . inner . next ()}# [ inline ] fn size_hint (& self )-> ( usize , Option < usize >){ self . inner . size_hint ()}# [ inline ] fn try_fold < Acc , Fold , R > (& mut self , init : Acc , fold : Fold )-> R where Self : Sized , Fold : FnMut ( Acc , Self :: Item )-> R , R : Try < Ok = Acc >{ self . inner . try_fold ( init , fold )}# [ inline ] fn fold < Acc , Fold > ( self , init : Acc , fold : Fold )-> Acc where Fold : FnMut ( Acc , Self :: Item )-> Acc , { self . inner . fold ( init , fold )}}# [ stable ( feature = "str_escape" , since = "1.34.0" )] impl < 'a > FusedIterator for $Name < 'a > {})+}} +macro_rules! __ra_macro_fixture85 {($($(# [$attr : meta ])* struct $Name : ident impl $(<$($lifetime : lifetime ),+> )? Fn = |$($arg : ident : $ArgTy : ty ),*| -> $ReturnTy : ty $body : block ; )+)=>{$($(# [$attr ])* struct $Name ; impl $(<$($lifetime ),+> )? Fn < ($($ArgTy , )*)> for $Name {# [ inline ] extern "rust-call" fn call (& self , ($($arg , )*): ($($ArgTy , )*))-> $ReturnTy {$body }} impl $(<$($lifetime ),+> )? FnMut < ($($ArgTy , )*)> for $Name {# [ inline ] extern "rust-call" fn call_mut (& mut self , ($($arg , )*): ($($ArgTy , )*))-> $ReturnTy { Fn :: call (&* self , ($($arg , )*))}} impl $(<$($lifetime ),+> )? FnOnce < ($($ArgTy , )*)> for $Name { type Output = $ReturnTy ; # [ inline ] extern "rust-call" fn call_once ( self , ($($arg , )*): ($($ArgTy , )*))-> $ReturnTy { Fn :: call (& self , ($($arg , )*))}})+ }} +macro_rules! __ra_macro_fixture86 {($($Tuple : ident {$(($idx : tt )-> $T : ident )+ })+)=>{$(# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($T : PartialEq ),+> PartialEq for ($($T ,)+) where last_type ! ($($T ,)+): ? Sized {# [ inline ] fn eq (& self , other : & ($($T ,)+))-> bool {$(self .$idx == other .$idx )&&+ }# [ inline ] fn ne (& self , other : & ($($T ,)+))-> bool {$(self .$idx != other .$idx )||+ }}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($T : Eq ),+> Eq for ($($T ,)+) where last_type ! ($($T ,)+): ? Sized {}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($T : PartialOrd + PartialEq ),+> PartialOrd for ($($T ,)+) where last_type ! ($($T ,)+): ? Sized {# [ inline ] fn partial_cmp (& self , other : & ($($T ,)+))-> Option < Ordering > { lexical_partial_cmp ! ($(self .$idx , other .$idx ),+)}# [ inline ] fn lt (& self , other : & ($($T ,)+))-> bool { lexical_ord ! ( lt , $(self .$idx , other .$idx ),+)}# [ inline ] fn le (& self , other : & ($($T ,)+))-> bool { lexical_ord ! ( le , $(self .$idx , other .$idx ),+)}# [ inline ] fn ge (& self , other : & ($($T ,)+))-> bool { lexical_ord ! ( ge , $(self .$idx , other .$idx ),+)}# [ inline ] fn gt (& self , other : & ($($T ,)+))-> bool { lexical_ord ! ( gt , $(self .$idx , other .$idx ),+)}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($T : Ord ),+> Ord for ($($T ,)+) where last_type ! ($($T ,)+): ? Sized {# [ inline ] fn cmp (& self , other : & ($($T ,)+))-> Ordering { lexical_cmp ! ($(self .$idx , other .$idx ),+)}}# [ stable ( feature = "rust1" , since = "1.0.0" )] impl <$($T : Default ),+> Default for ($($T ,)+){# [ inline ] fn default ()-> ($($T ,)+){($({let x : $T = Default :: default (); x },)+)}})+ }} +macro_rules! __ra_macro_fixture87 {($x : expr , $($tt : tt )*)=>{# [ doc = $x ]$($tt )* }; } +macro_rules! __ra_macro_fixture88 {($x : expr , $($tt : tt )*)=>{# [ doc = $x ]$($tt )* }; } +macro_rules! __ra_macro_fixture89 {(# [$stability : meta ]($($Trait : ident ),+ ) for $Ty : ident )=>{$(# [$stability ] impl fmt ::$Trait for $Ty {# [ inline ] fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { self . get (). fmt ( f )}})+ }} +macro_rules! __ra_macro_fixture90 {($t : ident , $f : ident )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Shl <$f > for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn shl ( self , other : $f )-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_shl (( other & self :: shift_max ::$t as $f ) as u32 ))}} forward_ref_binop ! { impl Shl , shl for Wrapping <$t >, $f , # [ stable ( feature = "wrapping_ref_ops" , since = "1.39.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl ShlAssign <$f > for Wrapping <$t > {# [ inline ] fn shl_assign (& mut self , other : $f ){* self = * self << other ; }} forward_ref_op_assign ! { impl ShlAssign , shl_assign for Wrapping <$t >, $f }# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Shr <$f > for Wrapping <$t > { type Output = Wrapping <$t >; # [ inline ] fn shr ( self , other : $f )-> Wrapping <$t > { Wrapping ( self . 0 . wrapping_shr (( other & self :: shift_max ::$t as $f ) as u32 ))}} forward_ref_binop ! { impl Shr , shr for Wrapping <$t >, $f , # [ stable ( feature = "wrapping_ref_ops" , since = "1.39.0" )]}# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl ShrAssign <$f > for Wrapping <$t > {# [ inline ] fn shr_assign (& mut self , other : $f ){* self = * self >> other ; }} forward_ref_op_assign ! { impl ShrAssign , shr_assign for Wrapping <$t >, $f }}; } +macro_rules! __ra_macro_fixture91 {( impl $imp : ident , $method : ident for $t : ty , $u : ty )=>{ forward_ref_binop ! ( impl $imp , $method for $t , $u , # [ stable ( feature = "rust1" , since = "1.0.0" )]); }; ( impl $imp : ident , $method : ident for $t : ty , $u : ty , # [$attr : meta ])=>{# [$attr ] impl < 'a > $imp <$u > for & 'a $t { type Output = <$t as $imp <$u >>:: Output ; # [ inline ] fn $method ( self , other : $u )-> <$t as $imp <$u >>:: Output {$imp ::$method (* self , other )}}# [$attr ] impl $imp <&$u > for $t { type Output = <$t as $imp <$u >>:: Output ; # [ inline ] fn $method ( self , other : &$u )-> <$t as $imp <$u >>:: Output {$imp ::$method ( self , * other )}}# [$attr ] impl $imp <&$u > for &$t { type Output = <$t as $imp <$u >>:: Output ; # [ inline ] fn $method ( self , other : &$u )-> <$t as $imp <$u >>:: Output {$imp ::$method (* self , * other )}}}} +macro_rules! __ra_macro_fixture92 {( impl $imp : ident , $method : ident for $t : ty , $u : ty )=>{ forward_ref_op_assign ! ( impl $imp , $method for $t , $u , # [ stable ( feature = "op_assign_builtins_by_ref" , since = "1.22.0" )]); }; ( impl $imp : ident , $method : ident for $t : ty , $u : ty , # [$attr : meta ])=>{# [$attr ] impl $imp <&$u > for $t {# [ inline ] fn $method (& mut self , other : &$u ){$imp ::$method ( self , * other ); }}}} +macro_rules! __ra_macro_fixture93 {( impl $imp : ident , $method : ident for $t : ty )=>{ forward_ref_unop ! ( impl $imp , $method for $t , # [ stable ( feature = "rust1" , since = "1.0.0" )]); }; ( impl $imp : ident , $method : ident for $t : ty , # [$attr : meta ])=>{# [$attr ] impl $imp for &$t { type Output = <$t as $imp >:: Output ; # [ inline ] fn $method ( self )-> <$t as $imp >:: Output {$imp ::$method (* self )}}}} +macro_rules! __ra_macro_fixture94 {($FnTy : ty , $($Arg : ident ),*)=>{# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> PartialEq for $FnTy {# [ inline ] fn eq (& self , other : & Self )-> bool {* self as usize == * other as usize }}# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> Eq for $FnTy {}# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> PartialOrd for $FnTy {# [ inline ] fn partial_cmp (& self , other : & Self )-> Option < Ordering > {(* self as usize ). partial_cmp (& (* other as usize ))}}# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> Ord for $FnTy {# [ inline ] fn cmp (& self , other : & Self )-> Ordering {(* self as usize ). cmp (& (* other as usize ))}}# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> hash :: Hash for $FnTy { fn hash < HH : hash :: Hasher > (& self , state : & mut HH ){ state . write_usize (* self as usize )}}# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> fmt :: Pointer for $FnTy { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { fmt :: Pointer :: fmt (& (* self as usize as * const ()), f )}}# [ stable ( feature = "fnptr_impls" , since = "1.4.0" )] impl < Ret , $($Arg ),*> fmt :: Debug for $FnTy { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result { fmt :: Pointer :: fmt (& (* self as usize as * const ()), f )}}}} +macro_rules! __ra_macro_fixture95 {($t : ty , $f : ty )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Shl <$f > for $t { type Output = $t ; # [ inline ]# [ rustc_inherit_overflow_checks ] fn shl ( self , other : $f )-> $t { self << other }} forward_ref_binop ! { impl Shl , shl for $t , $f }}; } +macro_rules! __ra_macro_fixture96 {($t : ty , $f : ty )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl Shr <$f > for $t { type Output = $t ; # [ inline ]# [ rustc_inherit_overflow_checks ] fn shr ( self , other : $f )-> $t { self >> other }} forward_ref_binop ! { impl Shr , shr for $t , $f }}; } +macro_rules! __ra_macro_fixture97 {($t : ty , $f : ty )=>{# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl ShlAssign <$f > for $t {# [ inline ]# [ rustc_inherit_overflow_checks ] fn shl_assign (& mut self , other : $f ){* self <<= other }} forward_ref_op_assign ! { impl ShlAssign , shl_assign for $t , $f }}; } +macro_rules! __ra_macro_fixture98 {($t : ty , $f : ty )=>{# [ stable ( feature = "op_assign_traits" , since = "1.8.0" )] impl ShrAssign <$f > for $t {# [ inline ]# [ rustc_inherit_overflow_checks ] fn shr_assign (& mut self , other : $f ){* self >>= other }} forward_ref_op_assign ! { impl ShrAssign , shr_assign for $t , $f }}; } +macro_rules! __ra_macro_fixture99 {( fmt ::$Trait : ident for $T : ident as $U : ident -> $Radix : ident )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )] impl fmt ::$Trait for $T { fn fmt (& self , f : & mut fmt :: Formatter < '_ >)-> fmt :: Result {$Radix . fmt_int (* self as $U , f )}}}; } +macro_rules! __ra_macro_fixture100 {($name : ident , $($other : ident ,)*)=>( tuple ! {$($other ,)* })} +macro_rules! __ra_macro_fixture101 {{ unsafe fn $name : ident : $adjacent_kv : ident }=>{# [ doc = " Given a leaf edge handle into an owned tree, returns a handle to the next KV," ]# [ doc = " while deallocating any node left behind yet leaving the corresponding edge" ]# [ doc = " in its parent node dangling." ]# [ doc = "" ]# [ doc = " # Safety" ]# [ doc = " - The leaf edge must not be the last one in the direction travelled." ]# [ doc = " - The node carrying the next KV returned must not have been deallocated by a" ]# [ doc = " previous call on any handle obtained for this tree." ] unsafe fn $name < K , V > ( leaf_edge : Handle < NodeRef < marker :: Owned , K , V , marker :: Leaf >, marker :: Edge >, )-> Handle < NodeRef < marker :: Owned , K , V , marker :: LeafOrInternal >, marker :: KV > { let mut edge = leaf_edge . forget_node_type (); loop { edge = match edge .$adjacent_kv (){ Ok ( internal_kv )=> return internal_kv , Err ( last_edge )=>{ unsafe { let parent_edge = last_edge . into_node (). deallocate_and_ascend (); unwrap_unchecked ( parent_edge ). forget_node_type ()}}}}}}; } +macro_rules! __ra_macro_fixture102 {([$($vars : tt )*]$lhs : ty , $rhs : ty , $($constraints : tt )*)=>{# [ stable ( feature = "vec_deque_partial_eq_slice" , since = "1.17.0" )] impl < A , B , $($vars )*> PartialEq <$rhs > for $lhs where A : PartialEq < B >, $($constraints )* { fn eq (& self , other : &$rhs )-> bool { if self . len ()!= other . len (){ return false ; } let ( sa , sb )= self . as_slices (); let ( oa , ob )= other [..]. split_at ( sa . len ()); sa == oa && sb == ob }}}} +macro_rules! __ra_macro_fixture103 {($lhs : ty , $rhs : ty )=>{# [ stable ( feature = "rust1" , since = "1.0.0" )]# [ allow ( unused_lifetimes )] impl < 'a , 'b > PartialEq <$rhs > for $lhs {# [ inline ] fn eq (& self , other : &$rhs )-> bool { PartialEq :: eq (& self [..], & other [..])}# [ inline ] fn ne (& self , other : &$rhs )-> bool { PartialEq :: ne (& self [..], & other [..])}}# [ stable ( feature = "rust1" , since = "1.0.0" )]# [ allow ( unused_lifetimes )] impl < 'a , 'b > PartialEq <$lhs > for $rhs {# [ inline ] fn eq (& self , other : &$lhs )-> bool { PartialEq :: eq (& self [..], & other [..])}# [ inline ] fn ne (& self , other : &$lhs )-> bool { PartialEq :: ne (& self [..], & other [..])}}}; } +macro_rules! __ra_macro_fixture104 {($t : ty , $is_zero : expr )=>{ unsafe impl IsZero for $t {# [ inline ] fn is_zero (& self )-> bool {$is_zero (* self )}}}; } +macro_rules! __ra_macro_fixture105 {([$($vars : tt )*]$lhs : ty , $rhs : ty $(where $ty : ty : $bound : ident )?, # [$stability : meta ])=>{# [$stability ] impl < A , B , $($vars )*> PartialEq <$rhs > for $lhs where A : PartialEq < B >, $($ty : $bound )? {# [ inline ] fn eq (& self , other : &$rhs )-> bool { self [..]== other [..]}# [ inline ] fn ne (& self , other : &$rhs )-> bool { self [..]!= other [..]}}}} +macro_rules! __ra_macro_fixture106 {('owned : $($oty : ident ,)* 'interned : $($ity : ident ,)* )=>{# [ repr ( C )]# [ allow ( non_snake_case )] pub struct HandleCounters {$($oty : AtomicUsize ,)* $($ity : AtomicUsize ,)* } impl HandleCounters { extern "C" fn get ()-> & 'static Self { static COUNTERS : HandleCounters = HandleCounters {$($oty : AtomicUsize :: new ( 1 ),)* $($ity : AtomicUsize :: new ( 1 ),)* }; & COUNTERS }}# [ repr ( C )]# [ allow ( non_snake_case )] pub ( super ) struct HandleStore < S : server :: Types > {$($oty : handle :: OwnedStore < S ::$oty >,)* $($ity : handle :: InternedStore < S ::$ity >,)* } impl < S : server :: Types > HandleStore < S > { pub ( super ) fn new ( handle_counters : & 'static HandleCounters )-> Self { HandleStore {$($oty : handle :: OwnedStore :: new (& handle_counters .$oty ),)* $($ity : handle :: InternedStore :: new (& handle_counters .$ity ),)* }}}$(# [ repr ( C )] pub ( crate ) struct $oty ( handle :: Handle ); impl ! Send for $oty {} impl ! Sync for $oty {} impl Drop for $oty { fn drop (& mut self ){$oty ( self . 0 ). drop (); }} impl < S > Encode < S > for $oty { fn encode ( self , w : & mut Writer , s : & mut S ){ let handle = self . 0 ; mem :: forget ( self ); handle . encode ( w , s ); }} impl < S : server :: Types > DecodeMut < '_ , '_ , HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$oty , $oty > { fn decode ( r : & mut Reader < '_ >, s : & mut HandleStore < server :: MarkedTypes < S >>)-> Self { s .$oty . take ( handle :: Handle :: decode ( r , & mut ()))}} impl < S > Encode < S > for &$oty { fn encode ( self , w : & mut Writer , s : & mut S ){ self . 0 . encode ( w , s ); }} impl < S : server :: Types > Decode < '_ , 's , HandleStore < server :: MarkedTypes < S >>> for & 's Marked < S ::$oty , $oty > { fn decode ( r : & mut Reader < '_ >, s : & 's HandleStore < server :: MarkedTypes < S >>)-> Self {& s .$oty [ handle :: Handle :: decode ( r , & mut ())]}} impl < S > Encode < S > for & mut $oty { fn encode ( self , w : & mut Writer , s : & mut S ){ self . 0 . encode ( w , s ); }} impl < S : server :: Types > DecodeMut < '_ , 's , HandleStore < server :: MarkedTypes < S >>> for & 's mut Marked < S ::$oty , $oty > { fn decode ( r : & mut Reader < '_ >, s : & 's mut HandleStore < server :: MarkedTypes < S >> )-> Self {& mut s .$oty [ handle :: Handle :: decode ( r , & mut ())]}} impl < S : server :: Types > Encode < HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$oty , $oty > { fn encode ( self , w : & mut Writer , s : & mut HandleStore < server :: MarkedTypes < S >>){ s .$oty . alloc ( self ). encode ( w , s ); }} impl < S > DecodeMut < '_ , '_ , S > for $oty { fn decode ( r : & mut Reader < '_ >, s : & mut S )-> Self {$oty ( handle :: Handle :: decode ( r , s ))}})* $(# [ repr ( C )]# [ derive ( Copy , Clone , PartialEq , Eq , Hash )] pub ( crate ) struct $ity ( handle :: Handle ); impl ! Send for $ity {} impl ! Sync for $ity {} impl < S > Encode < S > for $ity { fn encode ( self , w : & mut Writer , s : & mut S ){ self . 0 . encode ( w , s ); }} impl < S : server :: Types > DecodeMut < '_ , '_ , HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$ity , $ity > { fn decode ( r : & mut Reader < '_ >, s : & mut HandleStore < server :: MarkedTypes < S >>)-> Self { s .$ity . copy ( handle :: Handle :: decode ( r , & mut ()))}} impl < S : server :: Types > Encode < HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$ity , $ity > { fn encode ( self , w : & mut Writer , s : & mut HandleStore < server :: MarkedTypes < S >>){ s .$ity . alloc ( self ). encode ( w , s ); }} impl < S > DecodeMut < '_ , '_ , S > for $ity { fn decode ( r : & mut Reader < '_ >, s : & mut S )-> Self {$ity ( handle :: Handle :: decode ( r , s ))}})* }} +macro_rules! __ra_macro_fixture107 {($S : ident , $self : ident , $m : ident )=>{$m ! { FreeFunctions { fn drop ($self : $S :: FreeFunctions ); fn track_env_var ( var : & str , value : Option <& str >); }, TokenStream { fn drop ($self : $S :: TokenStream ); fn clone ($self : &$S :: TokenStream )-> $S :: TokenStream ; fn new ()-> $S :: TokenStream ; fn is_empty ($self : &$S :: TokenStream )-> bool ; fn from_str ( src : & str )-> $S :: TokenStream ; fn to_string ($self : &$S :: TokenStream )-> String ; fn from_token_tree ( tree : TokenTree <$S :: Group , $S :: Punct , $S :: Ident , $S :: Literal >, )-> $S :: TokenStream ; fn into_iter ($self : $S :: TokenStream )-> $S :: TokenStreamIter ; }, TokenStreamBuilder { fn drop ($self : $S :: TokenStreamBuilder ); fn new ()-> $S :: TokenStreamBuilder ; fn push ($self : & mut $S :: TokenStreamBuilder , stream : $S :: TokenStream ); fn build ($self : $S :: TokenStreamBuilder )-> $S :: TokenStream ; }, TokenStreamIter { fn drop ($self : $S :: TokenStreamIter ); fn clone ($self : &$S :: TokenStreamIter )-> $S :: TokenStreamIter ; fn next ($self : & mut $S :: TokenStreamIter , )-> Option < TokenTree <$S :: Group , $S :: Punct , $S :: Ident , $S :: Literal >>; }, Group { fn drop ($self : $S :: Group ); fn clone ($self : &$S :: Group )-> $S :: Group ; fn new ( delimiter : Delimiter , stream : $S :: TokenStream )-> $S :: Group ; fn delimiter ($self : &$S :: Group )-> Delimiter ; fn stream ($self : &$S :: Group )-> $S :: TokenStream ; fn span ($self : &$S :: Group )-> $S :: Span ; fn span_open ($self : &$S :: Group )-> $S :: Span ; fn span_close ($self : &$S :: Group )-> $S :: Span ; fn set_span ($self : & mut $S :: Group , span : $S :: Span ); }, Punct { fn new ( ch : char , spacing : Spacing )-> $S :: Punct ; fn as_char ($self : $S :: Punct )-> char ; fn spacing ($self : $S :: Punct )-> Spacing ; fn span ($self : $S :: Punct )-> $S :: Span ; fn with_span ($self : $S :: Punct , span : $S :: Span )-> $S :: Punct ; }, Ident { fn new ( string : & str , span : $S :: Span , is_raw : bool )-> $S :: Ident ; fn span ($self : $S :: Ident )-> $S :: Span ; fn with_span ($self : $S :: Ident , span : $S :: Span )-> $S :: Ident ; }, Literal { fn drop ($self : $S :: Literal ); fn clone ($self : &$S :: Literal )-> $S :: Literal ; fn debug_kind ($self : &$S :: Literal )-> String ; fn symbol ($self : &$S :: Literal )-> String ; fn suffix ($self : &$S :: Literal )-> Option < String >; fn integer ( n : & str )-> $S :: Literal ; fn typed_integer ( n : & str , kind : & str )-> $S :: Literal ; fn float ( n : & str )-> $S :: Literal ; fn f32 ( n : & str )-> $S :: Literal ; fn f64 ( n : & str )-> $S :: Literal ; fn string ( string : & str )-> $S :: Literal ; fn character ( ch : char )-> $S :: Literal ; fn byte_string ( bytes : & [ u8 ])-> $S :: Literal ; fn span ($self : &$S :: Literal )-> $S :: Span ; fn set_span ($self : & mut $S :: Literal , span : $S :: Span ); fn subspan ($self : &$S :: Literal , start : Bound < usize >, end : Bound < usize >, )-> Option <$S :: Span >; }, SourceFile { fn drop ($self : $S :: SourceFile ); fn clone ($self : &$S :: SourceFile )-> $S :: SourceFile ; fn eq ($self : &$S :: SourceFile , other : &$S :: SourceFile )-> bool ; fn path ($self : &$S :: SourceFile )-> String ; fn is_real ($self : &$S :: SourceFile )-> bool ; }, MultiSpan { fn drop ($self : $S :: MultiSpan ); fn new ()-> $S :: MultiSpan ; fn push ($self : & mut $S :: MultiSpan , span : $S :: Span ); }, Diagnostic { fn drop ($self : $S :: Diagnostic ); fn new ( level : Level , msg : & str , span : $S :: MultiSpan )-> $S :: Diagnostic ; fn sub ($self : & mut $S :: Diagnostic , level : Level , msg : & str , span : $S :: MultiSpan , ); fn emit ($self : $S :: Diagnostic ); }, Span { fn debug ($self : $S :: Span )-> String ; fn def_site ()-> $S :: Span ; fn call_site ()-> $S :: Span ; fn mixed_site ()-> $S :: Span ; fn source_file ($self : $S :: Span )-> $S :: SourceFile ; fn parent ($self : $S :: Span )-> Option <$S :: Span >; fn source ($self : $S :: Span )-> $S :: Span ; fn start ($self : $S :: Span )-> LineColumn ; fn end ($self : $S :: Span )-> LineColumn ; fn join ($self : $S :: Span , other : $S :: Span )-> Option <$S :: Span >; fn resolved_at ($self : $S :: Span , at : $S :: Span )-> $S :: Span ; fn source_text ($self : $S :: Span )-> Option < String >; }, }}; } +macro_rules! __ra_macro_fixture108 {( le $ty : ty )=>{ impl < S > Encode < S > for $ty { fn encode ( self , w : & mut Writer , _: & mut S ){ w . write_all (& self . to_le_bytes ()). unwrap (); }} impl < S > DecodeMut < '_ , '_ , S > for $ty { fn decode ( r : & mut Reader < '_ >, _: & mut S )-> Self { const N : usize = :: std :: mem :: size_of ::<$ty > (); let mut bytes = [ 0 ; N ]; bytes . copy_from_slice (& r [.. N ]); * r = & r [ N ..]; Self :: from_le_bytes ( bytes )}}}; ( struct $name : ident {$($field : ident ),* $(,)? })=>{ impl < S > Encode < S > for $name { fn encode ( self , w : & mut Writer , s : & mut S ){$(self .$field . encode ( w , s );)* }} impl < S > DecodeMut < '_ , '_ , S > for $name { fn decode ( r : & mut Reader < '_ >, s : & mut S )-> Self {$name {$($field : DecodeMut :: decode ( r , s )),* }}}}; ( enum $name : ident $(<$($T : ident ),+>)? {$($variant : ident $(($field : ident ))*),* $(,)? })=>{ impl < S , $($($T : Encode < S >),+)?> Encode < S > for $name $(<$($T ),+>)? { fn encode ( self , w : & mut Writer , s : & mut S ){# [ allow ( non_upper_case_globals )] mod tag {# [ repr ( u8 )] enum Tag {$($variant ),* }$(pub const $variant : u8 = Tag ::$variant as u8 ;)* } match self {$($name ::$variant $(($field ))* =>{ tag ::$variant . encode ( w , s ); $($field . encode ( w , s );)* })* }}} impl < S , $($($T : for < 's > DecodeMut < 'a , 's , S >),+)?> DecodeMut < 'a , '_ , S > for $name $(<$($T ),+>)? { fn decode ( r : & mut Reader < 'a >, s : & mut S )-> Self {# [ allow ( non_upper_case_globals )] mod tag {# [ repr ( u8 )] enum Tag {$($variant ),* }$(pub const $variant : u8 = Tag ::$variant as u8 ;)* } match u8 :: decode ( r , s ){$(tag ::$variant =>{$(let $field = DecodeMut :: decode ( r , s );)* $name ::$variant $(($field ))* })* _ => unreachable ! (), }}}}} +macro_rules! __ra_macro_fixture109 {($($ty : ty ),* $(,)?)=>{$(impl Mark for $ty { type Unmarked = Self ; fn mark ( unmarked : Self :: Unmarked )-> Self { unmarked }} impl Unmark for $ty { type Unmarked = Self ; fn unmark ( self )-> Self :: Unmarked { self }})* }} +macro_rules! __ra_macro_fixture110 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )*;)* }),* $(,)?)=>{$(impl $name {$(pub ( crate ) fn $method ($($arg : $arg_ty ),*)$(-> $ret_ty )* { Bridge :: with (| bridge | { let mut b = bridge . cached_buffer . take (); b . clear (); api_tags :: Method ::$name ( api_tags ::$name ::$method ). encode (& mut b , & mut ()); reverse_encode ! ( b ; $($arg ),*); b = bridge . dispatch . call ( b ); let r = Result ::<_, PanicMessage >:: decode (& mut & b [..], & mut ()); bridge . cached_buffer = b ; r . unwrap_or_else (| e | panic :: resume_unwind ( e . into ()))})})* })* }} +macro_rules! __ra_macro_fixture111 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )?;)* }),* $(,)?)=>{ pub trait Types {$(associated_item ! ( type $name );)* }$(pub trait $name : Types {$(associated_item ! ( fn $method (& mut self , $($arg : $arg_ty ),*)$(-> $ret_ty )?);)* })* pub trait Server : Types $(+ $name )* {} impl < S : Types $(+ $name )*> Server for S {}}} +macro_rules! __ra_macro_fixture112 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )?;)* }),* $(,)?)=>{ impl < S : Types > Types for MarkedTypes < S > {$(type $name = Marked < S ::$name , client ::$name >;)* }$(impl < S : $name > $name for MarkedTypes < S > {$(fn $method (& mut self , $($arg : $arg_ty ),*)$(-> $ret_ty )? {<_>:: mark ($name ::$method (& mut self . 0 , $($arg . unmark ()),*))})* })* }} +macro_rules! __ra_macro_fixture113 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )?;)* }),* $(,)?)=>{ pub trait DispatcherTrait {$(type $name ;)* fn dispatch (& mut self , b : Buffer < u8 >)-> Buffer < u8 >; } impl < S : Server > DispatcherTrait for Dispatcher < MarkedTypes < S >> {$(type $name = < MarkedTypes < S > as Types >::$name ;)* fn dispatch (& mut self , mut b : Buffer < u8 >)-> Buffer < u8 > { let Dispatcher { handle_store , server }= self ; let mut reader = & b [..]; match api_tags :: Method :: decode (& mut reader , & mut ()){$(api_tags :: Method ::$name ( m )=> match m {$(api_tags ::$name ::$method =>{ let mut call_method = || { reverse_decode ! ( reader , handle_store ; $($arg : $arg_ty ),*); $name ::$method ( server , $($arg ),*)}; let r = if thread :: panicking (){ Ok ( call_method ())} else { panic :: catch_unwind ( panic :: AssertUnwindSafe ( call_method )). map_err ( PanicMessage :: from )}; b . clear (); r . encode (& mut b , handle_store ); })* }),* } b }}}} +macro_rules! __ra_macro_fixture114 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )*;)* }),* $(,)?)=>{$(pub ( super ) enum $name {$($method ),* } rpc_encode_decode ! ( enum $name {$($method ),* }); )* pub ( super ) enum Method {$($name ($name )),* } rpc_encode_decode ! ( enum Method {$($name ( m )),* }); }} +macro_rules! __ra_macro_fixture115 {($(if # [ cfg ($meta : meta )]{$($tokens : tt )* }) else * else {$($tokens2 : tt )* })=>{$crate :: cfg_if ! {@ __items (); $((($meta )($($tokens )*)), )* (()($($tokens2 )*)), }}; ( 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 )*)), )* (()()), }}; (@ __items ($($not : meta ,)*); )=>{}; (@ __items ($($not : meta ,)*); (($($m : meta ),*)($($tokens : tt )*)), $($rest : tt )*)=>{# [ cfg ( all ($($m ,)* not ( any ($($not ),*))))]$crate :: cfg_if ! {@ __identity $($tokens )* }$crate :: cfg_if ! {@ __items ($($not ,)* $($m ,)*); $($rest )* }}; (@ __identity $($tokens : tt )*)=>{$($tokens )* }; } +macro_rules! __ra_macro_fixture116 {($lhs : ty , $rhs : ty )=>{# [ stable ( feature = "cmp_os_str" , since = "1.8.0" )] impl < 'a , 'b > PartialEq <$rhs > for $lhs {# [ inline ] fn eq (& self , other : &$rhs )-> bool {< OsStr as PartialEq >:: eq ( self , other )}}# [ stable ( feature = "cmp_os_str" , since = "1.8.0" )] impl < 'a , 'b > PartialEq <$lhs > for $rhs {# [ inline ] fn eq (& self , other : &$lhs )-> bool {< OsStr as PartialEq >:: eq ( self , other )}}# [ stable ( feature = "cmp_os_str" , since = "1.8.0" )] impl < 'a , 'b > PartialOrd <$rhs > for $lhs {# [ inline ] fn partial_cmp (& self , other : &$rhs )-> Option < cmp :: Ordering > {< OsStr as PartialOrd >:: partial_cmp ( self , other )}}# [ stable ( feature = "cmp_os_str" , since = "1.8.0" )] impl < 'a , 'b > PartialOrd <$lhs > for $rhs {# [ inline ] fn partial_cmp (& self , other : &$lhs )-> Option < cmp :: Ordering > {< OsStr as PartialOrd >:: partial_cmp ( self , other )}}}; } +macro_rules! __ra_macro_fixture117 {()=>{}; ($(# [$attr : meta ])* $vis : vis static $name : ident : $t : ty = $init : expr ; $($rest : tt )*)=>($crate :: __thread_local_inner ! ($(# [$attr ])* $vis $name , $t , $init ); $crate :: thread_local ! ($($rest )*); ); ($(# [$attr : meta ])* $vis : vis static $name : ident : $t : ty = $init : expr )=>($crate :: __thread_local_inner ! ($(# [$attr ])* $vis $name , $t , $init ); ); } +macro_rules! __ra_macro_fixture118 {($($t : ty )*)=>($(impl ReadNumberHelper for $t { const ZERO : Self = 0 ; # [ inline ] fn checked_mul (& self , other : u32 )-> Option < Self > { Self :: checked_mul (* self , other . try_into (). ok ()?)}# [ inline ] fn checked_add (& self , other : u32 )-> Option < Self > { Self :: checked_add (* self , other . try_into (). ok ()?)}})*)} +macro_rules! __ra_macro_fixture119 {($lhs : ty , $rhs : ty )=>{# [ stable ( feature = "partialeq_path" , since = "1.6.0" )] impl < 'a , 'b > PartialEq <$rhs > for $lhs {# [ inline ] fn eq (& self , other : &$rhs )-> bool {< Path as PartialEq >:: eq ( self , other )}}# [ stable ( feature = "partialeq_path" , since = "1.6.0" )] impl < 'a , 'b > PartialEq <$lhs > for $rhs {# [ inline ] fn eq (& self , other : &$lhs )-> bool {< Path as PartialEq >:: eq ( self , other )}}# [ stable ( feature = "cmp_path" , since = "1.8.0" )] impl < 'a , 'b > PartialOrd <$rhs > for $lhs {# [ inline ] fn partial_cmp (& self , other : &$rhs )-> Option < cmp :: Ordering > {< Path as PartialOrd >:: partial_cmp ( self , other )}}# [ stable ( feature = "cmp_path" , since = "1.8.0" )] impl < 'a , 'b > PartialOrd <$lhs > for $rhs {# [ inline ] fn partial_cmp (& self , other : &$lhs )-> Option < cmp :: Ordering > {< Path as PartialOrd >:: partial_cmp ( self , other )}}}; } +macro_rules! __ra_macro_fixture120 {($lhs : ty , $rhs : ty )=>{# [ stable ( feature = "cmp_path" , since = "1.8.0" )] impl < 'a , 'b > PartialEq <$rhs > for $lhs {# [ inline ] fn eq (& self , other : &$rhs )-> bool {< Path as PartialEq >:: eq ( self , other . as_ref ())}}# [ stable ( feature = "cmp_path" , since = "1.8.0" )] impl < 'a , 'b > PartialEq <$lhs > for $rhs {# [ inline ] fn eq (& self , other : &$lhs )-> bool {< Path as PartialEq >:: eq ( self . as_ref (), other )}}# [ stable ( feature = "cmp_path" , since = "1.8.0" )] impl < 'a , 'b > PartialOrd <$rhs > for $lhs {# [ inline ] fn partial_cmp (& self , other : &$rhs )-> Option < cmp :: Ordering > {< Path as PartialOrd >:: partial_cmp ( self , other . as_ref ())}}# [ stable ( feature = "cmp_path" , since = "1.8.0" )] impl < 'a , 'b > PartialOrd <$lhs > for $rhs {# [ inline ] fn partial_cmp (& self , other : &$lhs )-> Option < cmp :: Ordering > {< Path as PartialOrd >:: partial_cmp ( self . as_ref (), other )}}}; } +macro_rules! __ra_macro_fixture121 {(@ key $t : ty , $init : expr )=>{{# [ inline ] fn __init ()-> $t {$init } unsafe fn __getit ()-> $crate :: option :: Option <& 'static $t > {# [ cfg ( all ( target_arch = "wasm32" , not ( target_feature = "atomics" )))] static __KEY : $crate :: thread :: __StaticLocalKeyInner <$t > = $crate :: thread :: __StaticLocalKeyInner :: new (); # [ thread_local ]# [ cfg ( all ( target_thread_local , not ( all ( target_arch = "wasm32" , not ( target_feature = "atomics" ))), ))] static __KEY : $crate :: thread :: __FastLocalKeyInner <$t > = $crate :: thread :: __FastLocalKeyInner :: new (); # [ cfg ( all ( not ( target_thread_local ), not ( all ( target_arch = "wasm32" , not ( target_feature = "atomics" ))), ))] static __KEY : $crate :: thread :: __OsLocalKeyInner <$t > = $crate :: thread :: __OsLocalKeyInner :: new (); # [ allow ( unused_unsafe )] unsafe { __KEY . get ( __init )}} unsafe {$crate :: thread :: LocalKey :: new ( __getit )}}}; ($(# [$attr : meta ])* $vis : vis $name : ident , $t : ty , $init : expr )=>{$(# [$attr ])* $vis const $name : $crate :: thread :: LocalKey <$t > = $crate :: __thread_local_inner ! (@ key $t , $init ); }} +macro_rules! __ra_macro_fixture122 {({$($then_tt : tt )* } else {$($else_tt : tt )* })=>{ cfg_if :: cfg_if ! { if # [ cfg ( all ( target_os = "linux" , target_env = "gnu" ))]{$($then_tt )* } else {$($else_tt )* }}}; ($($block_inner : tt )*)=>{# [ cfg ( all ( target_os = "linux" , target_env = "gnu" ))]{$($block_inner )* }}; } +macro_rules! __ra_macro_fixture123 {($($t : ident )*)=>($(impl IsMinusOne for $t { fn is_minus_one (& self )-> bool {* self == - 1 }})*)} +macro_rules! __ra_macro_fixture124 {($(if # [ cfg ($($meta : meta ),*)]{$($it : item )* }) else * else {$($it2 : item )* })=>{ cfg_if ! {@ __items (); $((($($meta ),*)($($it )*)), )* (()($($it2 )*)), }}; ( if # [ cfg ($($i_met : meta ),*)]{$($i_it : item )* }$(else if # [ cfg ($($e_met : meta ),*)]{$($e_it : item )* })* )=>{ cfg_if ! {@ __items (); (($($i_met ),*)($($i_it )*)), $((($($e_met ),*)($($e_it )*)), )* (()()), }}; (@ __items ($($not : meta ,)*); )=>{}; (@ __items ($($not : meta ,)*); (($($m : meta ),*)($($it : item )*)), $($rest : tt )*)=>{ cfg_if ! {@ __apply cfg ( all ($($m ,)* not ( any ($($not ),*)))), $($it )* } cfg_if ! {@ __items ($($not ,)* $($m ,)*); $($rest )* }}; (@ __apply $m : meta , $($it : item )*)=>{$(# [$m ]$it )* }; } +macro_rules! __ra_macro_fixture125 {($bench_macro : ident , $bench_ahash_serial : ident , $bench_std_serial : ident , $bench_ahash_highbits : ident , $bench_std_highbits : ident , $bench_ahash_random : ident , $bench_std_random : ident )=>{$bench_macro ! ($bench_ahash_serial , AHashMap , 0 ..); $bench_macro ! ($bench_std_serial , StdHashMap , 0 ..); $bench_macro ! ($bench_ahash_highbits , AHashMap , ( 0 ..). map ( usize :: swap_bytes )); $bench_macro ! ($bench_std_highbits , StdHashMap , ( 0 ..). map ( usize :: swap_bytes )); $bench_macro ! ($bench_ahash_random , AHashMap , RandomKeys :: new ()); $bench_macro ! ($bench_std_random , StdHashMap , RandomKeys :: new ()); }; } +macro_rules! __ra_macro_fixture126 {($name : ident , $maptype : ident , $keydist : expr )=>{# [ bench ] fn $name ( b : & mut Bencher ){ let mut m = $maptype :: with_capacity_and_hasher ( SIZE , Default :: default ()); b . iter (|| { m . clear (); for i in ($keydist ). take ( SIZE ){ m . insert ( i , i ); } black_box (& mut m ); })}}; } +macro_rules! __ra_macro_fixture127 {($name : ident , $maptype : ident , $keydist : expr )=>{# [ bench ] fn $name ( b : & mut Bencher ){ let mut base = $maptype :: default (); for i in ($keydist ). take ( SIZE ){ base . insert ( i , i ); } let skip = $keydist . skip ( SIZE ); b . iter (|| { let mut m = base . clone (); let mut add_iter = skip . clone (); let mut remove_iter = $keydist ; for ( add , remove ) in (& mut add_iter ). zip (& mut remove_iter ). take ( SIZE ){ m . insert ( add , add ); black_box ( m . remove (& remove )); } black_box ( m ); })}}; } +macro_rules! __ra_macro_fixture128 {($name : ident , $maptype : ident , $keydist : expr )=>{# [ bench ] fn $name ( b : & mut Bencher ){ let mut m = $maptype :: default (); for i in $keydist . take ( SIZE ){ m . insert ( i , i ); } b . iter (|| { for i in $keydist . take ( SIZE ){ black_box ( m . get (& i )); }})}}; } +macro_rules! __ra_macro_fixture129 {($name : ident , $maptype : ident , $keydist : expr )=>{# [ bench ] fn $name ( b : & mut Bencher ){ let mut m = $maptype :: default (); let mut iter = $keydist ; for i in (& mut iter ). take ( SIZE ){ m . insert ( i , i ); } b . iter (|| { for i in (& mut iter ). take ( SIZE ){ black_box ( m . get (& i )); }})}}; } +macro_rules! __ra_macro_fixture130 {($name : ident , $maptype : ident , $keydist : expr )=>{# [ bench ] fn $name ( b : & mut Bencher ){ let mut m = $maptype :: default (); for i in ($keydist ). take ( SIZE ){ m . insert ( i , i ); } b . iter (|| { for i in & m { black_box ( i ); }})}}; } +macro_rules! __ra_macro_fixture131 {($(if # [ cfg ($($meta : meta ),*)]{$($it : item )* }) else * else {$($it2 : item )* })=>{ cfg_if ! {@ __items (); $((($($meta ),*)($($it )*)), )* (()($($it2 )*)), }}; ( if # [ cfg ($($i_met : meta ),*)]{$($i_it : item )* }$(else if # [ cfg ($($e_met : meta ),*)]{$($e_it : item )* })* )=>{ cfg_if ! {@ __items (); (($($i_met ),*)($($i_it )*)), $((($($e_met ),*)($($e_it )*)), )* (()()), }}; (@ __items ($($not : meta ,)*); )=>{}; (@ __items ($($not : meta ,)*); (($($m : meta ),*)($($it : item )*)), $($rest : tt )*)=>{ cfg_if ! {@ __apply cfg ( all ($($m ,)* not ( any ($($not ),*)))), $($it )* } cfg_if ! {@ __items ($($not ,)* $($m ,)*); $($rest )* }}; (@ __apply $m : meta , $($it : item )*)=>{$(# [$m ]$it )* }; } +macro_rules! __ra_macro_fixture132 {($($(# [$attr : meta ])* pub $t : ident $i : ident {$($field : tt )* })*)=>($(s ! ( it : $(# [$attr ])* pub $t $i {$($field )* }); )*); ( it : $(# [$attr : meta ])* pub union $i : ident {$($field : tt )* })=>( compile_error ! ( "unions cannot derive extra traits, use s_no_extra_traits instead" ); ); ( it : $(# [$attr : meta ])* pub struct $i : ident {$($field : tt )* })=>( __item ! {# [ repr ( C )]# [ cfg_attr ( feature = "extra_traits" , derive ( Debug , Eq , Hash , PartialEq ))]# [ allow ( deprecated )]$(# [$attr ])* pub struct $i {$($field )* }}# [ allow ( deprecated )] impl :: Copy for $i {}# [ allow ( deprecated )] impl :: Clone for $i { fn clone (& self )-> $i {* self }}); } +macro_rules! __ra_macro_fixture133 {($i : item )=>{$i }; } +macro_rules! __ra_macro_fixture134 {($($(# [$attr : meta ])* pub $t : ident $i : ident {$($field : tt )* })*)=>($(s_no_extra_traits ! ( it : $(# [$attr ])* pub $t $i {$($field )* }); )*); ( it : $(# [$attr : meta ])* pub union $i : ident {$($field : tt )* })=>( cfg_if ! { if # [ cfg ( libc_union )]{ __item ! {# [ repr ( C )]$(# [$attr ])* pub union $i {$($field )* }} impl :: Copy for $i {} impl :: Clone for $i { fn clone (& self )-> $i {* self }}}}); ( it : $(# [$attr : meta ])* pub struct $i : ident {$($field : tt )* })=>( __item ! {# [ repr ( C )]$(# [$attr ])* pub struct $i {$($field )* }}# [ allow ( deprecated )] impl :: Copy for $i {}# [ allow ( deprecated )] impl :: Clone for $i { fn clone (& self )-> $i {* self }}); } +macro_rules! __ra_macro_fixture135 {($($(# [$attr : meta ])* pub const $name : ident : $t1 : ty = $t2 : ident {$($field : tt )* };)*)=>($(# [ cfg ( libc_align )]$(# [$attr ])* pub const $name : $t1 = $t2 {$($field )* }; # [ cfg ( not ( libc_align ))]$(# [$attr ])* pub const $name : $t1 = $t2 {$($field )* __align : [], }; )*)} +macro_rules! __ra_macro_fixture136 {($($args : tt )* )=>{$(define_ioctl ! ($args ); )* }} +macro_rules! __ra_macro_fixture137 {({$name : ident , $ioctl : ident , $arg_type : ty })=>{ pub unsafe fn $name ( fd : c_int , arg : $arg_type )-> c_int { untyped_ioctl ( fd , bindings ::$ioctl , arg )}}; } +macro_rules! __ra_macro_fixture138 {($($T : ty ),*)=>{$(impl IdentFragment for $T { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { fmt :: Display :: fmt ( self , f )}})* }} +macro_rules! __ra_macro_fixture139 {($($t : ident =>$name : ident )*)=>($(impl ToTokens for $t { fn to_tokens (& self , tokens : & mut TokenStream ){ tokens . append ( Literal ::$name (* self )); }})*)} +macro_rules! __ra_macro_fixture140 {($($l : tt )*)=>{$(impl < 'q , T : 'q > RepAsIteratorExt < 'q > for [ T ; $l ]{ type Iter = slice :: Iter < 'q , T >; fn quote_into_iter (& 'q self )-> ( Self :: Iter , HasIter ){( self . iter (), HasIter )}})* }} +macro_rules! __ra_macro_fixture141 {($name : ident $spanned : ident $char1 : tt )=>{ pub fn $name ( tokens : & mut TokenStream ){ tokens . append ( Punct :: new ($char1 , Spacing :: Alone )); } pub fn $spanned ( tokens : & mut TokenStream , span : Span ){ let mut punct = Punct :: new ($char1 , Spacing :: Alone ); punct . set_span ( span ); tokens . append ( punct ); }}; ($name : ident $spanned : ident $char1 : tt $char2 : tt )=>{ pub fn $name ( tokens : & mut TokenStream ){ tokens . append ( Punct :: new ($char1 , Spacing :: Joint )); tokens . append ( Punct :: new ($char2 , Spacing :: Alone )); } pub fn $spanned ( tokens : & mut TokenStream , span : Span ){ let mut punct = Punct :: new ($char1 , Spacing :: Joint ); punct . set_span ( span ); tokens . append ( punct ); let mut punct = Punct :: new ($char2 , Spacing :: Alone ); punct . set_span ( span ); tokens . append ( punct ); }}; ($name : ident $spanned : ident $char1 : tt $char2 : tt $char3 : tt )=>{ pub fn $name ( tokens : & mut TokenStream ){ tokens . append ( Punct :: new ($char1 , Spacing :: Joint )); tokens . append ( Punct :: new ($char2 , Spacing :: Joint )); tokens . append ( Punct :: new ($char3 , Spacing :: Alone )); } pub fn $spanned ( tokens : & mut TokenStream , span : Span ){ let mut punct = Punct :: new ($char1 , Spacing :: Joint ); punct . set_span ( span ); tokens . append ( punct ); let mut punct = Punct :: new ($char2 , Spacing :: Joint ); punct . set_span ( span ); tokens . append ( punct ); let mut punct = Punct :: new ($char3 , Spacing :: Alone ); punct . set_span ( span ); tokens . append ( punct ); }}; } +macro_rules! __ra_macro_fixture142 {($display : tt $name : ty )=>{# [ cfg ( feature = "parsing" )] impl Token for $name { fn peek ( cursor : Cursor )-> bool { fn peek ( input : ParseStream )-> bool {<$name as Parse >:: parse ( input ). is_ok ()} peek_impl ( cursor , peek )} fn display ()-> & 'static str {$display }}# [ cfg ( feature = "parsing" )] impl private :: Sealed for $name {}}; } +macro_rules! __ra_macro_fixture143 {($display : tt $ty : ident $get : ident )=>{# [ cfg ( feature = "parsing" )] impl Token for $ty { fn peek ( cursor : Cursor )-> bool { cursor .$get (). is_some ()} fn display ()-> & 'static str {$display }}# [ cfg ( feature = "parsing" )] impl private :: Sealed for $ty {}}; } +macro_rules! __ra_macro_fixture144 {($($token : tt pub struct $name : ident /$len : tt # [$doc : meta ])*)=>{$(# [ repr ( C )]# [$doc ]# [ doc = "" ]# [ doc = " Don\\\'t try to remember the name of this type — use the" ]# [ doc = " [`Token!`] macro instead." ]# [ doc = "" ]# [ doc = " [`Token!`]: crate::token" ] pub struct $name { pub spans : [ Span ; $len ], }# [ doc ( hidden )]# [ allow ( non_snake_case )] pub fn $name < S : IntoSpans < [ Span ; $len ]>> ( spans : S )-> $name {$name { spans : spans . into_spans (), }} impl std :: default :: Default for $name { fn default ()-> Self {$name { spans : [ Span :: call_site (); $len ], }}}# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Copy for $name {}# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Clone for $name { fn clone (& self )-> Self {* self }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Debug for $name { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { f . write_str ( stringify ! ($name ))}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl cmp :: Eq for $name {}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl PartialEq for $name { fn eq (& self , _other : &$name )-> bool { true }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Hash for $name { fn hash < H : Hasher > (& self , _state : & mut H ){}} impl_deref_if_len_is_1 ! ($name /$len ); )* }; } +macro_rules! __ra_macro_fixture145 {($($token : tt pub struct $name : ident # [$doc : meta ])*)=>{$(# [$doc ]# [ doc = "" ]# [ doc = " Don\\\'t try to remember the name of this type — use the" ]# [ doc = " [`Token!`] macro instead." ]# [ doc = "" ]# [ doc = " [`Token!`]: crate::token" ] pub struct $name { pub span : Span , }# [ doc ( hidden )]# [ allow ( non_snake_case )] pub fn $name < S : IntoSpans < [ Span ; 1 ]>> ( span : S )-> $name {$name { span : span . into_spans ()[ 0 ], }} impl std :: default :: Default for $name { fn default ()-> Self {$name { span : Span :: call_site (), }}}# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Copy for $name {}# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Clone for $name { fn clone (& self )-> Self {* self }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Debug for $name { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { f . write_str ( stringify ! ($name ))}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl cmp :: Eq for $name {}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl PartialEq for $name { fn eq (& self , _other : &$name )-> bool { true }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Hash for $name { fn hash < H : Hasher > (& self , _state : & mut H ){}}# [ cfg ( feature = "printing" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "printing" )))] impl ToTokens for $name { fn to_tokens (& self , tokens : & mut TokenStream ){ printing :: keyword ($token , self . span , tokens ); }}# [ cfg ( feature = "parsing" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "parsing" )))] impl Parse for $name { fn parse ( input : ParseStream )-> Result < Self > { Ok ($name { span : parsing :: keyword ( input , $token )?, })}}# [ cfg ( feature = "parsing" )] impl Token for $name { fn peek ( cursor : Cursor )-> bool { parsing :: peek_keyword ( cursor , $token )} fn display ()-> & 'static str { concat ! ( "`" , $token , "`" )}}# [ cfg ( feature = "parsing" )] impl private :: Sealed for $name {})* }; } +macro_rules! __ra_macro_fixture146 {($($token : tt pub struct $name : ident /$len : tt # [$doc : meta ])*)=>{$(define_punctuation_structs ! {$token pub struct $name /$len # [$doc ]}# [ cfg ( feature = "printing" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "printing" )))] impl ToTokens for $name { fn to_tokens (& self , tokens : & mut TokenStream ){ printing :: punct ($token , & self . spans , tokens ); }}# [ cfg ( feature = "parsing" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "parsing" )))] impl Parse for $name { fn parse ( input : ParseStream )-> Result < Self > { Ok ($name { spans : parsing :: punct ( input , $token )?, })}}# [ cfg ( feature = "parsing" )] impl Token for $name { fn peek ( cursor : Cursor )-> bool { parsing :: peek_punct ( cursor , $token )} fn display ()-> & 'static str { concat ! ( "`" , $token , "`" )}}# [ cfg ( feature = "parsing" )] impl private :: Sealed for $name {})* }; } +macro_rules! __ra_macro_fixture147 {($($token : tt pub struct $name : ident # [$doc : meta ])*)=>{$(# [$doc ] pub struct $name { pub span : Span , }# [ doc ( hidden )]# [ allow ( non_snake_case )] pub fn $name < S : IntoSpans < [ Span ; 1 ]>> ( span : S )-> $name {$name { span : span . into_spans ()[ 0 ], }} impl std :: default :: Default for $name { fn default ()-> Self {$name { span : Span :: call_site (), }}}# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Copy for $name {}# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Clone for $name { fn clone (& self )-> Self {* self }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Debug for $name { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { f . write_str ( stringify ! ($name ))}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl cmp :: Eq for $name {}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl PartialEq for $name { fn eq (& self , _other : &$name )-> bool { true }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Hash for $name { fn hash < H : Hasher > (& self , _state : & mut H ){}} impl $name {# [ cfg ( feature = "printing" )] pub fn surround < F > (& self , tokens : & mut TokenStream , f : F ) where F : FnOnce (& mut TokenStream ), { printing :: delim ($token , self . span , tokens , f ); }}# [ cfg ( feature = "parsing" )] impl private :: Sealed for $name {})* }; } +macro_rules! __ra_macro_fixture148 {($token : ident )=>{ impl From < Token ! [$token ]> for Ident { fn from ( token : Token ! [$token ])-> Ident { Ident :: new ( stringify ! ($token ), token . span )}}}; } +macro_rules! __ra_macro_fixture149 {([$($attrs_pub : tt )*] struct $name : ident # full $($rest : tt )* )=>{# [ cfg ( feature = "full" )]$($attrs_pub )* struct $name $($rest )* # [ cfg ( not ( feature = "full" ))]$($attrs_pub )* struct $name { _noconstruct : :: std :: marker :: PhantomData <:: proc_macro2 :: Span >, }# [ cfg ( all ( not ( feature = "full" ), feature = "printing" ))] impl :: quote :: ToTokens for $name { fn to_tokens (& self , _: & mut :: proc_macro2 :: TokenStream ){ unreachable ! ()}}}; ([$($attrs_pub : tt )*] struct $name : ident $($rest : tt )* )=>{$($attrs_pub )* struct $name $($rest )* }; ($($t : tt )*)=>{ strip_attrs_pub ! ( ast_struct ! ($($t )*)); }; } +macro_rules! __ra_macro_fixture150 {([$($attrs_pub : tt )*] enum $name : ident # no_visit $($rest : tt )* )=>( ast_enum ! ([$($attrs_pub )*] enum $name $($rest )*); ); ([$($attrs_pub : tt )*] enum $name : ident $($rest : tt )* )=>($($attrs_pub )* enum $name $($rest )* ); ($($t : tt )*)=>{ strip_attrs_pub ! ( ast_enum ! ($($t )*)); }; } +macro_rules! __ra_macro_fixture151 {($(# [$enum_attr : meta ])* $pub : ident $enum : ident $name : ident #$tag : ident $body : tt $($remaining : tt )* )=>{ ast_enum ! ($(# [$enum_attr ])* $pub $enum $name #$tag $body ); ast_enum_of_structs_impl ! ($pub $enum $name $body $($remaining )*); }; ($(# [$enum_attr : meta ])* $pub : ident $enum : ident $name : ident $body : tt $($remaining : tt )* )=>{ ast_enum ! ($(# [$enum_attr ])* $pub $enum $name $body ); ast_enum_of_structs_impl ! ($pub $enum $name $body $($remaining )*); }; } +macro_rules! __ra_macro_fixture152 {($ident : ident )=>{# [ allow ( non_camel_case_types )] pub struct $ident { pub span : $crate :: __private :: Span , }# [ doc ( hidden )]# [ allow ( dead_code , non_snake_case )] pub fn $ident < __S : $crate :: __private :: IntoSpans < [$crate :: __private :: Span ; 1 ]>> ( span : __S , )-> $ident {$ident { span : $crate :: __private :: IntoSpans :: into_spans ( span )[ 0 ], }} impl $crate :: __private :: Default for $ident { fn default ()-> Self {$ident { span : $crate :: __private :: Span :: call_site (), }}}$crate :: impl_parse_for_custom_keyword ! ($ident ); $crate :: impl_to_tokens_for_custom_keyword ! ($ident ); $crate :: impl_clone_for_custom_keyword ! ($ident ); $crate :: impl_extra_traits_for_custom_keyword ! ($ident ); }; } +macro_rules! __ra_macro_fixture153 {($($expr_type : ty , $variant : ident , $msg : expr , )* )=>{$(# [ cfg ( all ( feature = "full" , feature = "printing" ))]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "parsing" )))] impl Parse for $expr_type { fn parse ( input : ParseStream )-> Result < Self > { let mut expr : Expr = input . parse ()?; loop { match expr { Expr ::$variant ( inner )=> return Ok ( inner ), Expr :: Group ( next )=> expr = * next . expr , _ => return Err ( Error :: new_spanned ( expr , $msg )), }}}})* }; } +macro_rules! __ra_macro_fixture154 {($ty : ident )=>{# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl < 'a > Clone for $ty < 'a > { fn clone (& self )-> Self {$ty ( self . 0 )}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl < 'a > Debug for $ty < 'a > { fn fmt (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . debug_tuple ( stringify ! ($ty )). field ( self . 0 ). finish ()}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl < 'a > Eq for $ty < 'a > {}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl < 'a > PartialEq for $ty < 'a > { fn eq (& self , other : & Self )-> bool { self . 0 == other . 0 }}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl < 'a > Hash for $ty < 'a > { fn hash < H : Hasher > (& self , state : & mut H ){ self . 0 . hash ( state ); }}}; } +macro_rules! __ra_macro_fixture155 {($ty : ident )=>{# [ cfg ( feature = "clone-impls" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "clone-impls" )))] impl Clone for $ty { fn clone (& self )-> Self {$ty { repr : self . repr . clone (), }}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl PartialEq for $ty { fn eq (& self , other : & Self )-> bool { self . repr . token . to_string ()== other . repr . token . to_string ()}}# [ cfg ( feature = "extra-traits" )]# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "extra-traits" )))] impl Hash for $ty { fn hash < H > (& self , state : & mut H ) where H : Hasher , { self . repr . token . to_string (). hash ( state ); }}# [ cfg ( feature = "parsing" )]# [ doc ( hidden )]# [ allow ( non_snake_case )] pub fn $ty ( marker : lookahead :: TokenMarker )-> $ty { match marker {}}}; } +macro_rules! __ra_macro_fixture156 {($name : ident / 1 )=>{ impl Deref for $name { type Target = WithSpan ; fn deref (& self )-> & Self :: Target { unsafe {&* ( self as * const Self as * const WithSpan )}}} impl DerefMut for $name { fn deref_mut (& mut self )-> & mut Self :: Target { unsafe {& mut * ( self as * mut Self as * mut WithSpan )}}}}; ($name : ident /$len : tt )=>{}; } +macro_rules! __ra_macro_fixture157 {($($await_rule : tt )*)=>{# [ doc = " A type-macro that expands to the name of the Rust type representation of a" ]# [ doc = " given token." ]# [ doc = "" ]# [ doc = " See the [token module] documentation for details and examples." ]# [ doc = "" ]# [ doc = " [token module]: crate::token" ]# [ macro_export ] macro_rules ! Token {[ abstract ]=>{$crate :: token :: Abstract }; [ as ]=>{$crate :: token :: As }; [ async ]=>{$crate :: token :: Async }; [ auto ]=>{$crate :: token :: Auto }; $($await_rule =>{$crate :: token :: Await };)* [ become ]=>{$crate :: token :: Become }; [ box ]=>{$crate :: token :: Box }; [ break ]=>{$crate :: token :: Break }; [ const ]=>{$crate :: token :: Const }; [ continue ]=>{$crate :: token :: Continue }; [ crate ]=>{$crate :: token :: Crate }; [ default ]=>{$crate :: token :: Default }; [ do ]=>{$crate :: token :: Do }; [ dyn ]=>{$crate :: token :: Dyn }; [ else ]=>{$crate :: token :: Else }; [ enum ]=>{$crate :: token :: Enum }; [ extern ]=>{$crate :: token :: Extern }; [ final ]=>{$crate :: token :: Final }; [ fn ]=>{$crate :: token :: Fn }; [ for ]=>{$crate :: token :: For }; [ if ]=>{$crate :: token :: If }; [ impl ]=>{$crate :: token :: Impl }; [ in ]=>{$crate :: token :: In }; [ let ]=>{$crate :: token :: Let }; [ loop ]=>{$crate :: token :: Loop }; [ macro ]=>{$crate :: token :: Macro }; [ match ]=>{$crate :: token :: Match }; [ mod ]=>{$crate :: token :: Mod }; [ move ]=>{$crate :: token :: Move }; [ mut ]=>{$crate :: token :: Mut }; [ override ]=>{$crate :: token :: Override }; [ priv ]=>{$crate :: token :: Priv }; [ pub ]=>{$crate :: token :: Pub }; [ ref ]=>{$crate :: token :: Ref }; [ return ]=>{$crate :: token :: Return }; [ Self ]=>{$crate :: token :: SelfType }; [ self ]=>{$crate :: token :: SelfValue }; [ static ]=>{$crate :: token :: Static }; [ struct ]=>{$crate :: token :: Struct }; [ super ]=>{$crate :: token :: Super }; [ trait ]=>{$crate :: token :: Trait }; [ try ]=>{$crate :: token :: Try }; [ type ]=>{$crate :: token :: Type }; [ typeof ]=>{$crate :: token :: Typeof }; [ union ]=>{$crate :: token :: Union }; [ unsafe ]=>{$crate :: token :: Unsafe }; [ unsized ]=>{$crate :: token :: Unsized }; [ use ]=>{$crate :: token :: Use }; [ virtual ]=>{$crate :: token :: Virtual }; [ where ]=>{$crate :: token :: Where }; [ while ]=>{$crate :: token :: While }; [ yield ]=>{$crate :: token :: Yield }; [+]=>{$crate :: token :: Add }; [+=]=>{$crate :: token :: AddEq }; [&]=>{$crate :: token :: And }; [&&]=>{$crate :: token :: AndAnd }; [&=]=>{$crate :: token :: AndEq }; [@]=>{$crate :: token :: At }; [!]=>{$crate :: token :: Bang }; [^]=>{$crate :: token :: Caret }; [^=]=>{$crate :: token :: CaretEq }; [:]=>{$crate :: token :: Colon }; [::]=>{$crate :: token :: Colon2 }; [,]=>{$crate :: token :: Comma }; [/]=>{$crate :: token :: Div }; [/=]=>{$crate :: token :: DivEq }; [$]=>{$crate :: token :: Dollar }; [.]=>{$crate :: token :: Dot }; [..]=>{$crate :: token :: Dot2 }; [...]=>{$crate :: token :: Dot3 }; [..=]=>{$crate :: token :: DotDotEq }; [=]=>{$crate :: token :: Eq }; [==]=>{$crate :: token :: EqEq }; [>=]=>{$crate :: token :: Ge }; [>]=>{$crate :: token :: Gt }; [<=]=>{$crate :: token :: Le }; [<]=>{$crate :: token :: Lt }; [*=]=>{$crate :: token :: MulEq }; [!=]=>{$crate :: token :: Ne }; [|]=>{$crate :: token :: Or }; [|=]=>{$crate :: token :: OrEq }; [||]=>{$crate :: token :: OrOr }; [#]=>{$crate :: token :: Pound }; [?]=>{$crate :: token :: Question }; [->]=>{$crate :: token :: RArrow }; [<-]=>{$crate :: token :: LArrow }; [%]=>{$crate :: token :: Rem }; [%=]=>{$crate :: token :: RemEq }; [=>]=>{$crate :: token :: FatArrow }; [;]=>{$crate :: token :: Semi }; [<<]=>{$crate :: token :: Shl }; [<<=]=>{$crate :: token :: ShlEq }; [>>]=>{$crate :: token :: Shr }; [>>=]=>{$crate :: token :: ShrEq }; [*]=>{$crate :: token :: Star }; [-]=>{$crate :: token :: Sub }; [-=]=>{$crate :: token :: SubEq }; [~]=>{$crate :: token :: Tilde }; [_]=>{$crate :: token :: Underscore }; }}; } +macro_rules! __ra_macro_fixture158 {($mac : ident ! ($(# [$m : meta ])* $pub : ident $($t : tt )*))=>{ check_keyword_matches ! ( pub $pub ); $mac ! ([$(# [$m ])* $pub ]$($t )*); }; } +macro_rules! __ra_macro_fixture159 {($pub : ident $enum : ident $name : ident {$($(# [$variant_attr : meta ])* $variant : ident $(($($member : ident )::+))*, )* }$($remaining : tt )* )=>{ check_keyword_matches ! ( pub $pub ); check_keyword_matches ! ( enum $enum ); $($(ast_enum_from_struct ! ($name ::$variant , $($member )::+); )*)* # [ cfg ( feature = "printing" )] generate_to_tokens ! {$($remaining )* () tokens $name {$($variant $($($member )::+)*,)* }}}; } +macro_rules! __ra_macro_fixture160 {($ident : ident )=>{ impl $crate :: token :: CustomToken for $ident { fn peek ( cursor : $crate :: buffer :: Cursor )-> $crate :: __private :: bool { if let Some (( ident , _rest ))= cursor . ident (){ ident == stringify ! ($ident )} else { false }} fn display ()-> & 'static $crate :: __private :: str { concat ! ( "`" , stringify ! ($ident ), "`" )}} impl $crate :: parse :: Parse for $ident { fn parse ( input : $crate :: parse :: ParseStream )-> $crate :: parse :: Result <$ident > { input . step (| cursor | { if let $crate :: __private :: Some (( ident , rest ))= cursor . ident (){ if ident == stringify ! ($ident ){ return $crate :: __private :: Ok (($ident { span : ident . span ()}, rest )); }}$crate :: __private :: Err ( cursor . error ( concat ! ( "expected `" , stringify ! ($ident ), "`" )))})}}}; } +macro_rules! __ra_macro_fixture161 {($ident : ident )=>{ impl $crate :: __private :: ToTokens for $ident { fn to_tokens (& self , tokens : & mut $crate :: __private :: TokenStream2 ){ let ident = $crate :: Ident :: new ( stringify ! ($ident ), self . span ); $crate :: __private :: TokenStreamExt :: append ( tokens , ident ); }}}; } +macro_rules! __ra_macro_fixture162 {($ident : ident )=>{ impl $crate :: __private :: Copy for $ident {} impl $crate :: __private :: Clone for $ident { fn clone (& self )-> Self {* self }}}; } +macro_rules! __ra_macro_fixture163 {($ident : ident )=>{ impl $crate :: __private :: Debug for $ident { fn fmt (& self , f : & mut $crate :: __private :: Formatter )-> $crate :: __private :: fmt :: Result {$crate :: __private :: Formatter :: write_str ( f , concat ! ( "Keyword [" , stringify ! ($ident ), "]" ), )}} impl $crate :: __private :: Eq for $ident {} impl $crate :: __private :: PartialEq for $ident { fn eq (& self , _other : & Self )-> $crate :: __private :: bool { true }} impl $crate :: __private :: Hash for $ident { fn hash < __H : $crate :: __private :: Hasher > (& self , _state : & mut __H ){}}}; } +macro_rules! __ra_macro_fixture164 {( struct struct )=>{}; ( enum enum )=>{}; ( pub pub )=>{}; } +macro_rules! __ra_macro_fixture165 {($name : ident :: Verbatim , $member : ident )=>{}; ($name : ident ::$variant : ident , crate :: private )=>{}; ($name : ident ::$variant : ident , $member : ident )=>{ impl From <$member > for $name { fn from ( e : $member )-> $name {$name ::$variant ( e )}}}; } +macro_rules! __ra_macro_fixture166 {( do_not_generate_to_tokens $($foo : tt )*)=>(); (($($arms : tt )*)$tokens : ident $name : ident {$variant : ident , $($next : tt )*})=>{ generate_to_tokens ! (($($arms )* $name ::$variant =>{})$tokens $name {$($next )* }); }; (($($arms : tt )*)$tokens : ident $name : ident {$variant : ident $member : ident , $($next : tt )*})=>{ generate_to_tokens ! (($($arms )* $name ::$variant ( _e )=> _e . to_tokens ($tokens ),)$tokens $name {$($next )* }); }; (($($arms : tt )*)$tokens : ident $name : ident {$variant : ident crate :: private , $($next : tt )*})=>{ generate_to_tokens ! (($($arms )* $name ::$variant (_)=> unreachable ! (),)$tokens $name {$($next )* }); }; (($($arms : tt )*)$tokens : ident $name : ident {})=>{# [ cfg_attr ( doc_cfg , doc ( cfg ( feature = "printing" )))] impl :: quote :: ToTokens for $name { fn to_tokens (& self , $tokens : & mut :: proc_macro2 :: TokenStream ){ match self {$($arms )* }}}}; } +macro_rules! __ra_macro_fixture167 {($(# [$attr : meta ])* static ref $N : ident : $T : ty = $e : expr ; $($t : tt )*)=>{ __lazy_static_internal ! ($(# [$attr ])* () static ref $N : $T = $e ; $($t )*); }; ($(# [$attr : meta ])* pub static ref $N : ident : $T : ty = $e : expr ; $($t : tt )*)=>{ __lazy_static_internal ! ($(# [$attr ])* ( pub ) static ref $N : $T = $e ; $($t )*); }; ($(# [$attr : meta ])* pub ($($vis : tt )+) static ref $N : ident : $T : ty = $e : expr ; $($t : tt )*)=>{ __lazy_static_internal ! ($(# [$attr ])* ( pub ($($vis )+)) static ref $N : $T = $e ; $($t )*); }; ()=>()} +macro_rules! __ra_macro_fixture168 {($($record : ident ($($whatever : tt )+ )),+ )=>{$(impl_value ! {$record ($($whatever )+ )})+ }} +macro_rules! __ra_macro_fixture169 {($($len : tt ),+ )=>{$(impl < 'a > private :: ValidLen < 'a > for [(& 'a Field , Option <& 'a ( dyn Value + 'a )>); $len ]{})+ }} +macro_rules! __ra_macro_fixture170 {($(# [$attr : meta ])* ($($vis : tt )*) static ref $N : ident : $T : ty = $e : expr ; $($t : tt )*)=>{ __lazy_static_internal ! (@ MAKE TY , $(# [$attr ])*, ($($vis )*), $N ); __lazy_static_internal ! (@ TAIL , $N : $T = $e ); lazy_static ! ($($t )*); }; (@ TAIL , $N : ident : $T : ty = $e : expr )=>{ impl $crate :: __Deref for $N { type Target = $T ; fn deref (& self )-> &$T {# [ inline ( always )] fn __static_ref_initialize ()-> $T {$e }# [ inline ( always )] fn __stability ()-> & 'static $T { __lazy_static_create ! ( LAZY , $T ); LAZY . get ( __static_ref_initialize )} __stability ()}} impl $crate :: LazyStatic for $N { fn initialize ( lazy : & Self ){ let _ = &** lazy ; }}}; (@ MAKE TY , $(# [$attr : meta ])*, ($($vis : tt )*), $N : ident )=>{# [ allow ( missing_copy_implementations )]# [ allow ( non_camel_case_types )]# [ allow ( dead_code )]$(# [$attr ])* $($vis )* struct $N { __private_field : ()}# [ doc ( hidden )]$($vis )* static $N : $N = $N { __private_field : ()}; }; ()=>()} +macro_rules! __ra_macro_fixture171 {($record : ident ($($value_ty : tt ),+ ))=>{$(impl_one_value ! ($value_ty , | this : $value_ty | this , $record ); )+ }; ($record : ident ($($value_ty : tt ),+ as $as_ty : ty ))=>{$(impl_one_value ! ($value_ty , | this : $value_ty | this as $as_ty , $record ); )+ }; } +macro_rules! __ra_macro_fixture172 {( bool , $op : expr , $record : ident )=>{ impl_one_value ! ( normal , bool , $op , $record ); }; ($value_ty : tt , $op : expr , $record : ident )=>{ impl_one_value ! ( normal , $value_ty , $op , $record ); impl_one_value ! ( nonzero , $value_ty , $op , $record ); }; ( normal , $value_ty : tt , $op : expr , $record : ident )=>{ impl $crate :: sealed :: Sealed for $value_ty {} impl $crate :: field :: Value for $value_ty { fn record (& self , key : &$crate :: field :: Field , visitor : & mut dyn $crate :: field :: Visit ){ visitor .$record ( key , $op (* self ))}}}; ( nonzero , $value_ty : tt , $op : expr , $record : ident )=>{# [ allow ( clippy :: useless_attribute , unused )] use num ::*; impl $crate :: sealed :: Sealed for ty_to_nonzero ! ($value_ty ){} impl $crate :: field :: Value for ty_to_nonzero ! ($value_ty ){ fn record (& self , key : &$crate :: field :: Field , visitor : & mut dyn $crate :: field :: Visit ){ visitor .$record ( key , $op ( self . get ()))}}}; } +macro_rules! __ra_macro_fixture173 {($(# [ doc $($doc : tt )*])* # [ project = $proj_mut_ident : ident ]# [ project_ref = $proj_ref_ident : ident ]# [ project_replace = $proj_replace_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[$proj_mut_ident ][$proj_ref_ident ][$proj_replace_ident ]$(# [ doc $($doc )*])* $($tt )* }}; ($(# [ doc $($doc : tt )*])* # [ project = $proj_mut_ident : ident ]# [ project_ref = $proj_ref_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[$proj_mut_ident ][$proj_ref_ident ][]$(# [ doc $($doc )*])* $($tt )* }}; ($(# [ doc $($doc : tt )*])* # [ project = $proj_mut_ident : ident ]# [ project_replace = $proj_replace_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[$proj_mut_ident ][][$proj_replace_ident ]$(# [ doc $($doc )*])* $($tt )* }}; ($(# [ doc $($doc : tt )*])* # [ project_ref = $proj_ref_ident : ident ]# [ project_replace = $proj_replace_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[][$proj_ref_ident ][$proj_replace_ident ]$(# [ doc $($doc )*])* $($tt )* }}; ($(# [ doc $($doc : tt )*])* # [ project = $proj_mut_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[$proj_mut_ident ][][]$(# [ doc $($doc )*])* $($tt )* }}; ($(# [ doc $($doc : tt )*])* # [ project_ref = $proj_ref_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[][$proj_ref_ident ][]$(# [ doc $($doc )*])* $($tt )* }}; ($(# [ doc $($doc : tt )*])* # [ project_replace = $proj_replace_ident : ident ]$($tt : tt )* )=>{$crate :: __pin_project_internal ! {[][][$proj_replace_ident ]$(# [ doc $($doc )*])* $($tt )* }}; ($($tt : tt )* )=>{$crate :: __pin_project_internal ! {[][][]$($tt )* }}; } +macro_rules! __ra_macro_fixture174 {(@ struct => internal ; [$($proj_mut_ident : ident )?][$($proj_ref_ident : ident )?][$($proj_replace_ident : ident )?][$proj_vis : vis ][$(# [$attrs : meta ])* $vis : vis struct $ident : ident ][$($def_generics : tt )*][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )*)?]{$($(# [$pin : ident ])? $field_vis : vis $field : ident : $field_ty : ty ),+ })=>{$(# [$attrs ])* $vis struct $ident $($def_generics )* $(where $($where_clause )*)? {$($field_vis $field : $field_ty ),+ }$crate :: __pin_project_internal ! {@ struct => make_proj_ty => named ; [$proj_vis ][$($proj_mut_ident )?][ make_proj_field_mut ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}$crate :: __pin_project_internal ! {@ struct => make_proj_ty => named ; [$proj_vis ][$($proj_ref_ident )?][ make_proj_field_ref ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}$crate :: __pin_project_internal ! {@ struct => make_proj_replace_ty => named ; [$proj_vis ][$($proj_replace_ident )?][ make_proj_field_replace ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}# [ allow ( explicit_outlives_requirements )]# [ allow ( single_use_lifetimes )]# [ allow ( clippy :: unknown_clippy_lints )]# [ allow ( clippy :: redundant_pub_crate )]# [ allow ( clippy :: used_underscore_binding )] const _: ()= {$crate :: __pin_project_internal ! {@ struct => make_proj_ty => unnamed ; [$proj_vis ][$($proj_mut_ident )?][ Projection ][ make_proj_field_mut ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}$crate :: __pin_project_internal ! {@ struct => make_proj_ty => unnamed ; [$proj_vis ][$($proj_ref_ident )?][ ProjectionRef ][ make_proj_field_ref ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}$crate :: __pin_project_internal ! {@ struct => make_proj_replace_ty => unnamed ; [$proj_vis ][$($proj_replace_ident )?][ ProjectionReplace ][ make_proj_field_replace ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }} impl <$($impl_generics )*> $ident <$($ty_generics )*> $(where $($where_clause )*)? {$crate :: __pin_project_internal ! {@ struct => make_proj_method ; [$proj_vis ][$($proj_mut_ident )?][ Projection ][ project get_unchecked_mut mut ][$($ty_generics )*]{$($(# [$pin ])? $field_vis $field ),+ }}$crate :: __pin_project_internal ! {@ struct => make_proj_method ; [$proj_vis ][$($proj_ref_ident )?][ ProjectionRef ][ project_ref get_ref ][$($ty_generics )*]{$($(# [$pin ])? $field_vis $field ),+ }}$crate :: __pin_project_internal ! {@ struct => make_proj_replace_method ; [$proj_vis ][$($proj_replace_ident )?][ ProjectionReplace ][$($ty_generics )*]{$($(# [$pin ])? $field_vis $field ),+ }}}$crate :: __pin_project_internal ! {@ make_unpin_impl ; [$vis $ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]$($field : $crate :: __pin_project_internal ! (@ make_unpin_bound ; $(# [$pin ])? $field_ty )),+ }$crate :: __pin_project_internal ! {@ make_drop_impl ; [$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]}# [ forbid ( safe_packed_borrows )] fn __assert_not_repr_packed <$($impl_generics )*> ( this : &$ident <$($ty_generics )*>)$(where $($where_clause )*)? {$(let _ = & this .$field ; )+ }}; }; (@ enum => internal ; [$($proj_mut_ident : ident )?][$($proj_ref_ident : ident )?][$($proj_replace_ident : ident )?][$proj_vis : vis ][$(# [$attrs : meta ])* $vis : vis enum $ident : ident ][$($def_generics : tt )*][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )*)?]{$($(# [$variant_attrs : meta ])* $variant : ident $({$($(# [$pin : ident ])? $field : ident : $field_ty : ty ),+ })? ),+ })=>{$(# [$attrs ])* $vis enum $ident $($def_generics )* $(where $($where_clause )*)? {$($(# [$variant_attrs ])* $variant $({$($field : $field_ty ),+ })? ),+ }$crate :: __pin_project_internal ! {@ enum => make_proj_ty ; [$proj_vis ][$($proj_mut_ident )?][ make_proj_field_mut ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($variant $({$($(# [$pin ])? $field : $field_ty ),+ })? ),+ }}$crate :: __pin_project_internal ! {@ enum => make_proj_ty ; [$proj_vis ][$($proj_ref_ident )?][ make_proj_field_ref ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($variant $({$($(# [$pin ])? $field : $field_ty ),+ })? ),+ }}$crate :: __pin_project_internal ! {@ enum => make_proj_replace_ty ; [$proj_vis ][$($proj_replace_ident )?][ make_proj_field_replace ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]{$($variant $({$($(# [$pin ])? $field : $field_ty ),+ })? ),+ }}# [ allow ( single_use_lifetimes )]# [ allow ( clippy :: unknown_clippy_lints )]# [ allow ( clippy :: used_underscore_binding )] const _: ()= { impl <$($impl_generics )*> $ident <$($ty_generics )*> $(where $($where_clause )*)? {$crate :: __pin_project_internal ! {@ enum => make_proj_method ; [$proj_vis ][$($proj_mut_ident )?][ project get_unchecked_mut mut ][$($ty_generics )*]{$($variant $({$($(# [$pin ])? $field ),+ })? ),+ }}$crate :: __pin_project_internal ! {@ enum => make_proj_method ; [$proj_vis ][$($proj_ref_ident )?][ project_ref get_ref ][$($ty_generics )*]{$($variant $({$($(# [$pin ])? $field ),+ })? ),+ }}$crate :: __pin_project_internal ! {@ enum => make_proj_replace_method ; [$proj_vis ][$($proj_replace_ident )?][$($ty_generics )*]{$($variant $({$($(# [$pin ])? $field ),+ })? ),+ }}}$crate :: __pin_project_internal ! {@ make_unpin_impl ; [$vis $ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]$($variant : ($($($crate :: __pin_project_internal ! (@ make_unpin_bound ; $(# [$pin ])? $field_ty )),+ )?)),+ }$crate :: __pin_project_internal ! {@ make_drop_impl ; [$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]}}; }; (@ struct => make_proj_ty => unnamed ; [$proj_vis : vis ][$_proj_ty_ident : ident ][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{}; (@ struct => make_proj_ty => unnamed ; [$proj_vis : vis ][][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{$crate :: __pin_project_internal ! {@ struct => make_proj_ty => named ; [$proj_vis ][$proj_ty_ident ][$make_proj_field ][$ident ][$($impl_generics )*][$($ty_generics )*][$(where $($where_clause )*)?]$($field )* }}; (@ struct => make_proj_ty => named ; [$proj_vis : vis ][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]{$($(# [$pin : ident ])? $field_vis : vis $field : ident : $field_ty : ty ),+ })=>{# [ allow ( dead_code )]# [ allow ( single_use_lifetimes )]# [ allow ( clippy :: unknown_clippy_lints )]# [ allow ( clippy :: mut_mut )]# [ allow ( clippy :: redundant_pub_crate )]# [ allow ( clippy :: ref_option_ref )]# [ allow ( clippy :: type_repetition_in_bounds )]$proj_vis struct $proj_ty_ident < '__pin , $($impl_generics )*> where $ident <$($ty_generics )*>: '__pin $(, $($where_clause )*)? {$($field_vis $field : $crate :: __pin_project_internal ! (@$make_proj_field ; $(# [$pin ])? $field_ty )),+ }}; (@ struct => make_proj_ty => named ; [$proj_vis : vis ][][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{}; (@ struct => make_proj_replace_ty => unnamed ; [$proj_vis : vis ][$_proj_ty_ident : ident ][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{}; (@ struct => make_proj_replace_ty => unnamed ; [$proj_vis : vis ][][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{}; (@ struct => make_proj_replace_ty => named ; [$proj_vis : vis ][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]{$($(# [$pin : ident ])? $field_vis : vis $field : ident : $field_ty : ty ),+ })=>{# [ allow ( dead_code )]# [ allow ( single_use_lifetimes )]# [ allow ( clippy :: mut_mut )]# [ allow ( clippy :: redundant_pub_crate )]# [ allow ( clippy :: type_repetition_in_bounds )]$proj_vis struct $proj_ty_ident <$($impl_generics )*> where $($($where_clause )*)? {$($field_vis $field : $crate :: __pin_project_internal ! (@$make_proj_field ; $(# [$pin ])? $field_ty )),+ }}; (@ struct => make_proj_replace_ty => named ; [$proj_vis : vis ][][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{}; (@ enum => make_proj_ty ; [$proj_vis : vis ][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]{$($variant : ident $({$($(# [$pin : ident ])? $field : ident : $field_ty : ty ),+ })? ),+ })=>{# [ allow ( dead_code )]# [ allow ( single_use_lifetimes )]# [ allow ( clippy :: unknown_clippy_lints )]# [ allow ( clippy :: mut_mut )]# [ allow ( clippy :: redundant_pub_crate )]# [ allow ( clippy :: ref_option_ref )]# [ allow ( clippy :: type_repetition_in_bounds )]$proj_vis enum $proj_ty_ident < '__pin , $($impl_generics )*> where $ident <$($ty_generics )*>: '__pin $(, $($where_clause )*)? {$($variant $({$($field : $crate :: __pin_project_internal ! (@$make_proj_field ; $(# [$pin ])? $field_ty )),+ })? ),+ }}; (@ enum => make_proj_ty ; [$proj_vis : vis ][][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($variant : tt )* )=>{}; (@ enum => make_proj_replace_ty ; [$proj_vis : vis ][$proj_ty_ident : ident ][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]{$($variant : ident $({$($(# [$pin : ident ])? $field : ident : $field_ty : ty ),+ })? ),+ })=>{# [ allow ( dead_code )]# [ allow ( single_use_lifetimes )]# [ allow ( clippy :: mut_mut )]# [ allow ( clippy :: redundant_pub_crate )]# [ allow ( clippy :: type_repetition_in_bounds )]$proj_vis enum $proj_ty_ident <$($impl_generics )*> where $($($where_clause )*)? {$($variant $({$($field : $crate :: __pin_project_internal ! (@$make_proj_field ; $(# [$pin ])? $field_ty )),+ })? ),+ }}; (@ enum => make_proj_replace_ty ; [$proj_vis : vis ][][$make_proj_field : ident ][$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($variant : tt )* )=>{}; (@ make_proj_replace_block ; [$($proj_path : tt )+]{$($(# [$pin : ident ])? $field_vis : vis $field : ident ),+ })=>{ let result = $($proj_path )* {$($field : $crate :: __pin_project_internal ! (@ make_replace_field_proj ; $(# [$pin ])? $field )),+ }; {($($crate :: __pin_project_internal ! (@ make_unsafe_drop_in_place_guard ; $(# [$pin ])? $field ), )* ); } result }; (@ make_proj_replace_block ; [$($proj_path : tt )+])=>{$($proj_path )* }; (@ struct => make_proj_method ; [$proj_vis : vis ][$proj_ty_ident : ident ][$_proj_ty_ident : ident ][$method_ident : ident $get_method : ident $($mut : ident )?][$($ty_generics : tt )*]{$($(# [$pin : ident ])? $field_vis : vis $field : ident ),+ })=>{$proj_vis fn $method_ident < '__pin > ( self : $crate :: __private :: Pin <& '__pin $($mut )? Self >, )-> $proj_ty_ident < '__pin , $($ty_generics )*> { unsafe { let Self {$($field ),* }= self .$get_method (); $proj_ty_ident {$($field : $crate :: __pin_project_internal ! (@ make_unsafe_field_proj ; $(# [$pin ])? $field )),+ }}}}; (@ struct => make_proj_method ; [$proj_vis : vis ][][$proj_ty_ident : ident ][$method_ident : ident $get_method : ident $($mut : ident )?][$($ty_generics : tt )*]$($variant : tt )* )=>{$crate :: __pin_project_internal ! {@ struct => make_proj_method ; [$proj_vis ][$proj_ty_ident ][$proj_ty_ident ][$method_ident $get_method $($mut )?][$($ty_generics )*]$($variant )* }}; (@ struct => make_proj_replace_method ; [$proj_vis : vis ][$proj_ty_ident : ident ][$_proj_ty_ident : ident ][$($ty_generics : tt )*]{$($(# [$pin : ident ])? $field_vis : vis $field : ident ),+ })=>{$proj_vis fn project_replace ( self : $crate :: __private :: Pin <& mut Self >, replacement : Self , )-> $proj_ty_ident <$($ty_generics )*> { unsafe { let __self_ptr : * mut Self = self . get_unchecked_mut (); let __guard = $crate :: __private :: UnsafeOverwriteGuard { target : __self_ptr , value : $crate :: __private :: ManuallyDrop :: new ( replacement ), }; let Self {$($field ),* }= & mut * __self_ptr ; $crate :: __pin_project_internal ! {@ make_proj_replace_block ; [$proj_ty_ident ]{$($(# [$pin ])? $field ),+ }}}}}; (@ struct => make_proj_replace_method ; [$proj_vis : vis ][][$proj_ty_ident : ident ][$($ty_generics : tt )*]$($variant : tt )* )=>{}; (@ enum => make_proj_method ; [$proj_vis : vis ][$proj_ty_ident : ident ][$method_ident : ident $get_method : ident $($mut : ident )?][$($ty_generics : tt )*]{$($variant : ident $({$($(# [$pin : ident ])? $field : ident ),+ })? ),+ })=>{$proj_vis fn $method_ident < '__pin > ( self : $crate :: __private :: Pin <& '__pin $($mut )? Self >, )-> $proj_ty_ident < '__pin , $($ty_generics )*> { unsafe { match self .$get_method (){$(Self ::$variant $({$($field ),+ })? =>{$proj_ty_ident ::$variant $({$($field : $crate :: __pin_project_internal ! (@ make_unsafe_field_proj ; $(# [$pin ])? $field )),+ })? }),+ }}}}; (@ enum => make_proj_method ; [$proj_vis : vis ][][$method_ident : ident $get_method : ident $($mut : ident )?][$($ty_generics : tt )*]$($variant : tt )* )=>{}; (@ enum => make_proj_replace_method ; [$proj_vis : vis ][$proj_ty_ident : ident ][$($ty_generics : tt )*]{$($variant : ident $({$($(# [$pin : ident ])? $field : ident ),+ })? ),+ })=>{$proj_vis fn project_replace ( self : $crate :: __private :: Pin <& mut Self >, replacement : Self , )-> $proj_ty_ident <$($ty_generics )*> { unsafe { let __self_ptr : * mut Self = self . get_unchecked_mut (); let __guard = $crate :: __private :: UnsafeOverwriteGuard { target : __self_ptr , value : $crate :: __private :: ManuallyDrop :: new ( replacement ), }; match & mut * __self_ptr {$(Self ::$variant $({$($field ),+ })? =>{$crate :: __pin_project_internal ! {@ make_proj_replace_block ; [$proj_ty_ident :: $variant ]$({$($(# [$pin ])? $field ),+ })? }}),+ }}}}; (@ enum => make_proj_replace_method ; [$proj_vis : vis ][][$($ty_generics : tt )*]$($variant : tt )* )=>{}; (@ make_unpin_impl ; [$vis : vis $ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?]$($field : tt )* )=>{# [ allow ( non_snake_case )]$vis struct __Origin < '__pin , $($impl_generics )*> $(where $($where_clause )*)? { __dummy_lifetime : $crate :: __private :: PhantomData <& '__pin ()>, $($field )* } impl < '__pin , $($impl_generics )*> $crate :: __private :: Unpin for $ident <$($ty_generics )*> where __Origin < '__pin , $($ty_generics )*>: $crate :: __private :: Unpin $(, $($where_clause )*)? {}}; (@ make_drop_impl ; [$ident : ident ][$($impl_generics : tt )*][$($ty_generics : tt )*][$(where $($where_clause : tt )* )?])=>{ trait MustNotImplDrop {}# [ allow ( clippy :: drop_bounds , drop_bounds )] impl < T : $crate :: __private :: Drop > MustNotImplDrop for T {} impl <$($impl_generics )*> MustNotImplDrop for $ident <$($ty_generics )*> $(where $($where_clause )*)? {}}; (@ make_unpin_bound ; # [ pin ]$field_ty : ty )=>{$field_ty }; (@ make_unpin_bound ; $field_ty : ty )=>{$crate :: __private :: AlwaysUnpin <$field_ty > }; (@ make_unsafe_field_proj ; # [ pin ]$field : ident )=>{$crate :: __private :: Pin :: new_unchecked ($field )}; (@ make_unsafe_field_proj ; $field : ident )=>{$field }; (@ make_replace_field_proj ; # [ pin ]$field : ident )=>{$crate :: __private :: PhantomData }; (@ make_replace_field_proj ; $field : ident )=>{$crate :: __private :: ptr :: read ($field )}; (@ make_unsafe_drop_in_place_guard ; # [ pin ]$field : ident )=>{$crate :: __private :: UnsafeDropInPlaceGuard ($field )}; (@ make_unsafe_drop_in_place_guard ; $field : ident )=>{()}; (@ make_proj_field_mut ; # [ pin ]$field_ty : ty )=>{$crate :: __private :: Pin <& '__pin mut ($field_ty )> }; (@ make_proj_field_mut ; $field_ty : ty )=>{& '__pin mut ($field_ty )}; (@ make_proj_field_ref ; # [ pin ]$field_ty : ty )=>{$crate :: __private :: Pin <& '__pin ($field_ty )> }; (@ make_proj_field_ref ; $field_ty : ty )=>{& '__pin ($field_ty )}; (@ make_proj_field_replace ; # [ pin ]$field_ty : ty )=>{$crate :: __private :: PhantomData <$field_ty > }; (@ make_proj_field_replace ; $field_ty : ty )=>{$field_ty }; ([$($proj_mut_ident : ident )?][$($proj_ref_ident : ident )?][$($proj_replace_ident : ident )?]$(# [$attrs : meta ])* pub struct $ident : ident $(< $($lifetime : lifetime $(: $lifetime_bound : lifetime )? ),* $(,)? $($generics : ident $(: $generics_bound : path )? $(: ?$generics_unsized_bound : path )? $(: $generics_lifetime_bound : lifetime )? $(= $generics_default : ty )? ),* $(,)? >)? $(where $($where_clause_ty : ty $(: $where_clause_bound : path )? $(: ?$where_clause_unsized_bound : path )? $(: $where_clause_lifetime_bound : lifetime )? ),* $(,)? )? {$($(# [$pin : ident ])? $field_vis : vis $field : ident : $field_ty : ty ),+ $(,)? })=>{$crate :: __pin_project_internal ! {@ struct => internal ; [$($proj_mut_ident )?][$($proj_ref_ident )?][$($proj_replace_ident )?][ pub ( crate )][$(# [$attrs ])* pub struct $ident ][$(< $($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? $(= $generics_default )? ),* >)?][$($($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? ),* )?][$($($lifetime ,)* $($generics ),* )?][$(where $($where_clause_ty $(: $where_clause_bound )? $(: ?$where_clause_unsized_bound )? $(: $where_clause_lifetime_bound )? ),* )?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}}; ([$($proj_mut_ident : ident )?][$($proj_ref_ident : ident )?][$($proj_replace_ident : ident )?]$(# [$attrs : meta ])* $vis : vis struct $ident : ident $(< $($lifetime : lifetime $(: $lifetime_bound : lifetime )? ),* $(,)? $($generics : ident $(: $generics_bound : path )? $(: ?$generics_unsized_bound : path )? $(: $generics_lifetime_bound : lifetime )? $(= $generics_default : ty )? ),* $(,)? >)? $(where $($where_clause_ty : ty $(: $where_clause_bound : path )? $(: ?$where_clause_unsized_bound : path )? $(: $where_clause_lifetime_bound : lifetime )? ),* $(,)? )? {$($(# [$pin : ident ])? $field_vis : vis $field : ident : $field_ty : ty ),+ $(,)? })=>{$crate :: __pin_project_internal ! {@ struct => internal ; [$($proj_mut_ident )?][$($proj_ref_ident )?][$($proj_replace_ident )?][$vis ][$(# [$attrs ])* $vis struct $ident ][$(< $($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? $(= $generics_default )? ),* >)?][$($($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? ),* )?][$($($lifetime ,)* $($generics ),* )?][$(where $($where_clause_ty $(: $where_clause_bound )? $(: ?$where_clause_unsized_bound )? $(: $where_clause_lifetime_bound )? ),* )?]{$($(# [$pin ])? $field_vis $field : $field_ty ),+ }}}; ([$($proj_mut_ident : ident )?][$($proj_ref_ident : ident )?][$($proj_replace_ident : ident )?]$(# [$attrs : meta ])* pub enum $ident : ident $(< $($lifetime : lifetime $(: $lifetime_bound : lifetime )? ),* $(,)? $($generics : ident $(: $generics_bound : path )? $(: ?$generics_unsized_bound : path )? $(: $generics_lifetime_bound : lifetime )? $(= $generics_default : ty )? ),* $(,)? >)? $(where $($where_clause_ty : ty $(: $where_clause_bound : path )? $(: ?$where_clause_unsized_bound : path )? $(: $where_clause_lifetime_bound : lifetime )? ),* $(,)? )? {$($(# [$variant_attrs : meta ])* $variant : ident $({$($(# [$pin : ident ])? $field : ident : $field_ty : ty ),+ $(,)? })? ),+ $(,)? })=>{$crate :: __pin_project_internal ! {@ enum => internal ; [$($proj_mut_ident )?][$($proj_ref_ident )?][$($proj_replace_ident )?][ pub ( crate )][$(# [$attrs ])* pub enum $ident ][$(< $($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? $(= $generics_default )? ),* >)?][$($($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? ),* )?][$($($lifetime ,)* $($generics ),* )?][$(where $($where_clause_ty $(: $where_clause_bound )? $(: ?$where_clause_unsized_bound )? $(: $where_clause_lifetime_bound )? ),* )?]{$($(# [$variant_attrs ])* $variant $({$($(# [$pin ])? $field : $field_ty ),+ })? ),+ }}}; ([$($proj_mut_ident : ident )?][$($proj_ref_ident : ident )?][$($proj_replace_ident : ident )?]$(# [$attrs : meta ])* $vis : vis enum $ident : ident $(< $($lifetime : lifetime $(: $lifetime_bound : lifetime )? ),* $(,)? $($generics : ident $(: $generics_bound : path )? $(: ?$generics_unsized_bound : path )? $(: $generics_lifetime_bound : lifetime )? $(= $generics_default : ty )? ),* $(,)? >)? $(where $($where_clause_ty : ty $(: $where_clause_bound : path )? $(: ?$where_clause_unsized_bound : path )? $(: $where_clause_lifetime_bound : lifetime )? ),* $(,)? )? {$($(# [$variant_attrs : meta ])* $variant : ident $({$($(# [$pin : ident ])? $field : ident : $field_ty : ty ),+ $(,)? })? ),+ $(,)? })=>{$crate :: __pin_project_internal ! {@ enum => internal ; [$($proj_mut_ident )?][$($proj_ref_ident )?][$($proj_replace_ident )?][$vis ][$(# [$attrs ])* $vis enum $ident ][$(< $($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? $(= $generics_default )? ),* >)?][$($($lifetime $(: $lifetime_bound )? ,)* $($generics $(: $generics_bound )? $(: ?$generics_unsized_bound )? $(: $generics_lifetime_bound )? ),* )?][$($($lifetime ,)* $($generics ),* )?][$(where $($where_clause_ty $(: $where_clause_bound )? $(: ?$where_clause_unsized_bound )? $(: $where_clause_lifetime_bound )? ),* )?]{$($(# [$variant_attrs ])* $variant $({$($(# [$pin ])? $field : $field_ty ),+ })? ),+ }}}; } +macro_rules! __ra_macro_fixture175 {($t : ty , $example : tt )=>{ impl AtomicCell <$t > {# [ doc = " Increments the current value by `val` and returns the previous value." ]# [ doc = "" ]# [ doc = " The addition wraps on overflow." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_add(3), 7);" ]# [ doc = " assert_eq!(a.load(), 10);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_add (& self , val : $t )-> $t { if can_transmute ::<$t , atomic :: AtomicUsize > (){ let a = unsafe {&* ( self . value . get () as * const atomic :: AtomicUsize )}; a . fetch_add ( val as usize , Ordering :: AcqRel ) as $t } else { let _guard = lock ( self . value . get () as usize ). write (); let value = unsafe {& mut * ( self . value . get ())}; let old = * value ; * value = value . wrapping_add ( val ); old }}# [ doc = " Decrements the current value by `val` and returns the previous value." ]# [ doc = "" ]# [ doc = " The subtraction wraps on overflow." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_sub(3), 7);" ]# [ doc = " assert_eq!(a.load(), 4);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_sub (& self , val : $t )-> $t { if can_transmute ::<$t , atomic :: AtomicUsize > (){ let a = unsafe {&* ( self . value . get () as * const atomic :: AtomicUsize )}; a . fetch_sub ( val as usize , Ordering :: AcqRel ) as $t } else { let _guard = lock ( self . value . get () as usize ). write (); let value = unsafe {& mut * ( self . value . get ())}; let old = * value ; * value = value . wrapping_sub ( val ); old }}# [ doc = " Applies bitwise \\\"and\\\" to the current value and returns the previous value." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_and(3), 7);" ]# [ doc = " assert_eq!(a.load(), 3);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_and (& self , val : $t )-> $t { if can_transmute ::<$t , atomic :: AtomicUsize > (){ let a = unsafe {&* ( self . value . get () as * const atomic :: AtomicUsize )}; a . fetch_and ( val as usize , Ordering :: AcqRel ) as $t } else { let _guard = lock ( self . value . get () as usize ). write (); let value = unsafe {& mut * ( self . value . get ())}; let old = * value ; * value &= val ; old }}# [ doc = " Applies bitwise \\\"or\\\" to the current value and returns the previous value." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_or(16), 7);" ]# [ doc = " assert_eq!(a.load(), 23);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_or (& self , val : $t )-> $t { if can_transmute ::<$t , atomic :: AtomicUsize > (){ let a = unsafe {&* ( self . value . get () as * const atomic :: AtomicUsize )}; a . fetch_or ( val as usize , Ordering :: AcqRel ) as $t } else { let _guard = lock ( self . value . get () as usize ). write (); let value = unsafe {& mut * ( self . value . get ())}; let old = * value ; * value |= val ; old }}# [ doc = " Applies bitwise \\\"xor\\\" to the current value and returns the previous value." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_xor(2), 7);" ]# [ doc = " assert_eq!(a.load(), 5);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_xor (& self , val : $t )-> $t { if can_transmute ::<$t , atomic :: AtomicUsize > (){ let a = unsafe {&* ( self . value . get () as * const atomic :: AtomicUsize )}; a . fetch_xor ( val as usize , Ordering :: AcqRel ) as $t } else { let _guard = lock ( self . value . get () as usize ). write (); let value = unsafe {& mut * ( self . value . get ())}; let old = * value ; * value ^= val ; old }}}}; ($t : ty , $atomic : ty , $example : tt )=>{ impl AtomicCell <$t > {# [ doc = " Increments the current value by `val` and returns the previous value." ]# [ doc = "" ]# [ doc = " The addition wraps on overflow." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_add(3), 7);" ]# [ doc = " assert_eq!(a.load(), 10);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_add (& self , val : $t )-> $t { let a = unsafe {&* ( self . value . get () as * const $atomic )}; a . fetch_add ( val , Ordering :: AcqRel )}# [ doc = " Decrements the current value by `val` and returns the previous value." ]# [ doc = "" ]# [ doc = " The subtraction wraps on overflow." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_sub(3), 7);" ]# [ doc = " assert_eq!(a.load(), 4);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_sub (& self , val : $t )-> $t { let a = unsafe {&* ( self . value . get () as * const $atomic )}; a . fetch_sub ( val , Ordering :: AcqRel )}# [ doc = " Applies bitwise \\\"and\\\" to the current value and returns the previous value." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_and(3), 7);" ]# [ doc = " assert_eq!(a.load(), 3);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_and (& self , val : $t )-> $t { let a = unsafe {&* ( self . value . get () as * const $atomic )}; a . fetch_and ( val , Ordering :: AcqRel )}# [ doc = " Applies bitwise \\\"or\\\" to the current value and returns the previous value." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_or(16), 7);" ]# [ doc = " assert_eq!(a.load(), 23);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_or (& self , val : $t )-> $t { let a = unsafe {&* ( self . value . get () as * const $atomic )}; a . fetch_or ( val , Ordering :: AcqRel )}# [ doc = " Applies bitwise \\\"xor\\\" to the current value and returns the previous value." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " use crossbeam_utils::atomic::AtomicCell;" ]# [ doc = "" ]# [ doc = $example ]# [ doc = "" ]# [ doc = " assert_eq!(a.fetch_xor(2), 7);" ]# [ doc = " assert_eq!(a.load(), 5);" ]# [ doc = " ```" ]# [ inline ] pub fn fetch_xor (& self , val : $t )-> $t { let a = unsafe {&* ( self . value . get () as * const $atomic )}; a . fetch_xor ( val , Ordering :: AcqRel )}}}; } +macro_rules! __ra_macro_fixture176 {($atomic : ident , $val : ty )=>{ impl AtomicConsume for :: core :: sync :: atomic ::$atomic { type Val = $val ; impl_consume ! (); }}; } +macro_rules! __ra_macro_fixture177 {($t : ty , $min : expr , $max : expr )=>{ impl Bounded for $t {# [ inline ] fn min_value ()-> $t {$min }# [ inline ] fn max_value ()-> $t {$max }}}; } +macro_rules! __ra_macro_fixture178 {($m : ident )=>{ for_each_tuple_ ! {$m !! A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , }}; } +macro_rules! __ra_macro_fixture179 {($T : ident )=>{ impl ToPrimitive for $T { impl_to_primitive_int_to_int ! {$T : fn to_isize -> isize ; fn to_i8 -> i8 ; fn to_i16 -> i16 ; fn to_i32 -> i32 ; fn to_i64 -> i64 ; # [ cfg ( has_i128 )] fn to_i128 -> i128 ; } impl_to_primitive_int_to_uint ! {$T : fn to_usize -> usize ; fn to_u8 -> u8 ; fn to_u16 -> u16 ; fn to_u32 -> u32 ; fn to_u64 -> u64 ; # [ cfg ( has_i128 )] fn to_u128 -> u128 ; }# [ inline ] fn to_f32 (& self )-> Option < f32 > { Some (* self as f32 )}# [ inline ] fn to_f64 (& self )-> Option < f64 > { Some (* self as f64 )}}}; } +macro_rules! __ra_macro_fixture180 {($T : ident )=>{ impl ToPrimitive for $T { impl_to_primitive_uint_to_int ! {$T : fn to_isize -> isize ; fn to_i8 -> i8 ; fn to_i16 -> i16 ; fn to_i32 -> i32 ; fn to_i64 -> i64 ; # [ cfg ( has_i128 )] fn to_i128 -> i128 ; } impl_to_primitive_uint_to_uint ! {$T : fn to_usize -> usize ; fn to_u8 -> u8 ; fn to_u16 -> u16 ; fn to_u32 -> u32 ; fn to_u64 -> u64 ; # [ cfg ( has_i128 )] fn to_u128 -> u128 ; }# [ inline ] fn to_f32 (& self )-> Option < f32 > { Some (* self as f32 )}# [ inline ] fn to_f64 (& self )-> Option < f64 > { Some (* self as f64 )}}}; } +macro_rules! __ra_macro_fixture181 {($T : ident )=>{ impl ToPrimitive for $T { impl_to_primitive_float_to_signed_int ! {$T : fn to_isize -> isize ; fn to_i8 -> i8 ; fn to_i16 -> i16 ; fn to_i32 -> i32 ; fn to_i64 -> i64 ; # [ cfg ( has_i128 )] fn to_i128 -> i128 ; } impl_to_primitive_float_to_unsigned_int ! {$T : fn to_usize -> usize ; fn to_u8 -> u8 ; fn to_u16 -> u16 ; fn to_u32 -> u32 ; fn to_u64 -> u64 ; # [ cfg ( has_i128 )] fn to_u128 -> u128 ; } impl_to_primitive_float_to_float ! {$T : fn to_f32 -> f32 ; fn to_f64 -> f64 ; }}}; } +macro_rules! __ra_macro_fixture182 {($T : ty , $to_ty : ident )=>{# [ allow ( deprecated )] impl FromPrimitive for $T {# [ inline ] fn from_isize ( n : isize )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_i8 ( n : i8 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_i16 ( n : i16 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_i32 ( n : i32 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_i64 ( n : i64 )-> Option <$T > { n .$to_ty ()}# [ cfg ( has_i128 )]# [ inline ] fn from_i128 ( n : i128 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_usize ( n : usize )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_u8 ( n : u8 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_u16 ( n : u16 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_u32 ( n : u32 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_u64 ( n : u64 )-> Option <$T > { n .$to_ty ()}# [ cfg ( has_i128 )]# [ inline ] fn from_u128 ( n : u128 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_f32 ( n : f32 )-> Option <$T > { n .$to_ty ()}# [ inline ] fn from_f64 ( n : f64 )-> Option <$T > { n .$to_ty ()}}}; } +macro_rules! __ra_macro_fixture183 {($T : ty , $conv : ident )=>{ impl NumCast for $T {# [ inline ]# [ allow ( deprecated )] fn from < N : ToPrimitive > ( n : N )-> Option <$T > { n .$conv ()}}}; } +macro_rules! __ra_macro_fixture184 {(@ $T : ty =>$(# [$cfg : meta ])* impl $U : ty )=>{$(# [$cfg ])* impl AsPrimitive <$U > for $T {# [ inline ] fn as_ ( self )-> $U { self as $U }}}; (@ $T : ty =>{$($U : ty ),* })=>{$(impl_as_primitive ! (@ $T => impl $U ); )*}; ($T : ty =>{$($U : ty ),* })=>{ impl_as_primitive ! (@ $T =>{$($U ),* }); impl_as_primitive ! (@ $T =>{ u8 , u16 , u32 , u64 , usize }); impl_as_primitive ! (@ $T =># [ cfg ( has_i128 )] impl u128 ); impl_as_primitive ! (@ $T =>{ i8 , i16 , i32 , i64 , isize }); impl_as_primitive ! (@ $T =># [ cfg ( has_i128 )] impl i128 ); }; } +macro_rules! __ra_macro_fixture185 {($(# [$doc : meta ]$constant : ident ,)+)=>(# [ allow ( non_snake_case )] pub trait FloatConst {$(# [$doc ] fn $constant ()-> Self ;)+ # [ doc = "Return the full circle constant `Ï„`." ]# [ inline ] fn TAU ()-> Self where Self : Sized + Add < Self , Output = Self >{ Self :: PI ()+ Self :: PI ()}# [ doc = "Return `log10(2.0)`." ]# [ inline ] fn LOG10_2 ()-> Self where Self : Sized + Div < Self , Output = Self >{ Self :: LN_2 ()/ Self :: LN_10 ()}# [ doc = "Return `log2(10.0)`." ]# [ inline ] fn LOG2_10 ()-> Self where Self : Sized + Div < Self , Output = Self >{ Self :: LN_10 ()/ Self :: LN_2 ()}} float_const_impl ! {@ float f32 , $($constant ,)+ } float_const_impl ! {@ float f64 , $($constant ,)+ }); (@ float $T : ident , $($constant : ident ,)+)=>( impl FloatConst for $T { constant ! {$($constant ()-> $T :: consts ::$constant ; )+ TAU ()-> 6.28318530717958647692528676655900577 ; LOG10_2 ()-> 0.301029995663981195213738894724493027 ; LOG2_10 ()-> 3.32192809488736234787031942948939018 ; }}); } +macro_rules! __ra_macro_fixture186 {($t : ty , $v : expr )=>{ impl Zero for $t {# [ inline ] fn zero ()-> $t {$v }# [ inline ] fn is_zero (& self )-> bool {* self == $v }}}; } +macro_rules! __ra_macro_fixture187 {($t : ty , $v : expr )=>{ impl One for $t {# [ inline ] fn one ()-> $t {$v }# [ inline ] fn is_one (& self )-> bool {* self == $v }}}; } +macro_rules! __ra_macro_fixture188 {($T : ty , $S : ty , $U : ty )=>{ impl PrimInt for $T {# [ inline ] fn count_ones ( self )-> u32 {<$T >:: count_ones ( self )}# [ inline ] fn count_zeros ( self )-> u32 {<$T >:: count_zeros ( self )}# [ inline ] fn leading_zeros ( self )-> u32 {<$T >:: leading_zeros ( self )}# [ inline ] fn trailing_zeros ( self )-> u32 {<$T >:: trailing_zeros ( self )}# [ inline ] fn rotate_left ( self , n : u32 )-> Self {<$T >:: rotate_left ( self , n )}# [ inline ] fn rotate_right ( self , n : u32 )-> Self {<$T >:: rotate_right ( self , n )}# [ inline ] fn signed_shl ( self , n : u32 )-> Self {(( self as $S )<< n ) as $T }# [ inline ] fn signed_shr ( self , n : u32 )-> Self {(( self as $S )>> n ) as $T }# [ inline ] fn unsigned_shl ( self , n : u32 )-> Self {(( self as $U )<< n ) as $T }# [ inline ] fn unsigned_shr ( self , n : u32 )-> Self {(( self as $U )>> n ) as $T }# [ inline ] fn swap_bytes ( self )-> Self {<$T >:: swap_bytes ( self )}# [ inline ] fn from_be ( x : Self )-> Self {<$T >:: from_be ( x )}# [ inline ] fn from_le ( x : Self )-> Self {<$T >:: from_le ( x )}# [ inline ] fn to_be ( self )-> Self {<$T >:: to_be ( self )}# [ inline ] fn to_le ( self )-> Self {<$T >:: to_le ( self )}# [ inline ] fn pow ( self , exp : u32 )-> Self {<$T >:: pow ( self , exp )}}}; } +macro_rules! __ra_macro_fixture189 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self , v : &$t )-> Option <$t > {<$t >::$method (* self , * v )}}}; } +macro_rules! __ra_macro_fixture190 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self )-> Option <$t > {<$t >::$method (* self )}}}; } +macro_rules! __ra_macro_fixture191 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self , rhs : u32 )-> Option <$t > {<$t >::$method (* self , rhs )}}}; } +macro_rules! __ra_macro_fixture192 {($trait_name : ident for $($t : ty )*)=>{$(impl $trait_name for $t { type Output = Self ; # [ inline ] fn mul_add ( self , a : Self , b : Self )-> Self :: Output {( self * a )+ b }})*}} +macro_rules! __ra_macro_fixture193 {($trait_name : ident for $($t : ty )*)=>{$(impl $trait_name for $t {# [ inline ] fn mul_add_assign (& mut self , a : Self , b : Self ){* self = (* self * a )+ b }})*}} +macro_rules! __ra_macro_fixture194 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self , v : & Self )-> ( Self , bool ){<$t >::$method (* self , * v )}}}; } +macro_rules! __ra_macro_fixture195 {($trait_name : ident for $($t : ty )*)=>{$(impl $trait_name for $t {# [ inline ] fn saturating_add ( self , v : Self )-> Self { Self :: saturating_add ( self , v )}# [ inline ] fn saturating_sub ( self , v : Self )-> Self { Self :: saturating_sub ( self , v )}})*}} +macro_rules! __ra_macro_fixture196 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self , v : & Self )-> Self {<$t >::$method (* self , * v )}}}; } +macro_rules! __ra_macro_fixture197 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self , v : & Self )-> Self {<$t >::$method (* self , * v )}}}; ($trait_name : ident , $method : ident , $t : ty , $rhs : ty )=>{ impl $trait_name <$rhs > for $t {# [ inline ] fn $method (& self , v : &$rhs )-> Self {<$t >::$method (* self , * v )}}}; } +macro_rules! __ra_macro_fixture198 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self )-> $t {<$t >::$method (* self )}}}; } +macro_rules! __ra_macro_fixture199 {($trait_name : ident , $method : ident , $t : ty )=>{ impl $trait_name for $t {# [ inline ] fn $method (& self , rhs : u32 )-> $t {<$t >::$method (* self , rhs )}}}; } +macro_rules! __ra_macro_fixture200 {($t : ty )=>{ pow_impl ! ($t , u8 ); pow_impl ! ($t , usize ); }; ($t : ty , $rhs : ty )=>{ pow_impl ! ($t , $rhs , usize , pow ); }; ($t : ty , $rhs : ty , $desired_rhs : ty , $method : expr )=>{ impl Pow <$rhs > for $t { type Output = $t ; # [ inline ] fn pow ( self , rhs : $rhs )-> $t {($method )( self , <$desired_rhs >:: from ( rhs ))}} impl < 'a > Pow <& 'a $rhs > for $t { type Output = $t ; # [ inline ] fn pow ( self , rhs : & 'a $rhs )-> $t {($method )( self , <$desired_rhs >:: from (* rhs ))}} impl < 'a > Pow <$rhs > for & 'a $t { type Output = $t ; # [ inline ] fn pow ( self , rhs : $rhs )-> $t {($method )(* self , <$desired_rhs >:: from ( rhs ))}} impl < 'a , 'b > Pow <& 'a $rhs > for & 'b $t { type Output = $t ; # [ inline ] fn pow ( self , rhs : & 'a $rhs )-> $t {($method )(* self , <$desired_rhs >:: from (* rhs ))}}}; } +macro_rules! __ra_macro_fixture201 {($($t : ty )*)=>($(impl Signed for $t {# [ inline ] fn abs (& self )-> $t { if self . is_negative (){-* self } else {* self }}# [ inline ] fn abs_sub (& self , other : &$t )-> $t { if * self <= * other { 0 } else {* self - * other }}# [ inline ] fn signum (& self )-> $t { match * self { n if n > 0 => 1 , 0 => 0 , _ =>- 1 , }}# [ inline ] fn is_positive (& self )-> bool {* self > 0 }# [ inline ] fn is_negative (& self )-> bool {* self < 0 }})*)} +macro_rules! __ra_macro_fixture202 {($t : ty )=>{ impl Signed for $t {# [ doc = " Computes the absolute value. Returns `NAN` if the number is `NAN`." ]# [ inline ] fn abs (& self )-> $t { FloatCore :: abs (* self )}# [ doc = " The positive difference of two numbers. Returns `0.0` if the number is" ]# [ doc = " less than or equal to `other`, otherwise the difference between`self`" ]# [ doc = " and `other` is returned." ]# [ inline ] fn abs_sub (& self , other : &$t )-> $t { if * self <= * other { 0. } else {* self - * other }}# [ doc = " # Returns" ]# [ doc = "" ]# [ doc = " - `1.0` if the number is positive, `+0.0` or `INFINITY`" ]# [ doc = " - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`" ]# [ doc = " - `NAN` if the number is NaN" ]# [ inline ] fn signum (& self )-> $t { FloatCore :: signum (* self )}# [ doc = " Returns `true` if the number is positive, including `+0.0` and `INFINITY`" ]# [ inline ] fn is_positive (& self )-> bool { FloatCore :: is_sign_positive (* self )}# [ doc = " Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`" ]# [ inline ] fn is_negative (& self )-> bool { FloatCore :: is_sign_negative (* self )}}}; } +macro_rules! __ra_macro_fixture203 {($name : ident for $($t : ty )*)=>($(impl $name for $t {})*)} +macro_rules! __ra_macro_fixture204 {($name : ident for $($t : ty )*)=>($(impl $name for $t { type FromStrRadixErr = :: core :: num :: ParseIntError ; # [ inline ] fn from_str_radix ( s : & str , radix : u32 )-> Result < Self , :: core :: num :: ParseIntError > {<$t >:: from_str_radix ( s , radix )}})*)} +macro_rules! __ra_macro_fixture205 {($name : ident for $($t : ident )*)=>($(impl $name for $t { type FromStrRadixErr = ParseFloatError ; fn from_str_radix ( src : & str , radix : u32 )-> Result < Self , Self :: FromStrRadixErr > { use self :: FloatErrorKind ::*; use self :: ParseFloatError as PFE ; match src { "inf" => return Ok ( core ::$t :: INFINITY ), "-inf" => return Ok ( core ::$t :: NEG_INFINITY ), "NaN" => return Ok ( core ::$t :: NAN ), _ =>{}, } fn slice_shift_char ( src : & str )-> Option < ( char , & str )> { let mut chars = src . chars (); if let Some ( ch )= chars . next (){ Some (( ch , chars . as_str ()))} else { None }} let ( is_positive , src )= match slice_shift_char ( src ){ None => return Err ( PFE { kind : Empty }), Some (( '-' , "" ))=> return Err ( PFE { kind : Empty }), Some (( '-' , src ))=>( false , src ), Some ((_, _))=>( true , src ), }; let mut sig = if is_positive { 0.0 } else {- 0.0 }; let mut prev_sig = sig ; let mut cs = src . chars (). enumerate (); let mut exp_info = None ::< ( char , usize )>; for ( i , c ) in cs . by_ref (){ match c . to_digit ( radix ){ Some ( digit )=>{ sig = sig * ( radix as $t ); if is_positive { sig = sig + (( digit as isize ) as $t ); } else { sig = sig - (( digit as isize ) as $t ); } if prev_sig != 0.0 { if is_positive && sig <= prev_sig { return Ok ( core ::$t :: INFINITY ); } if ! is_positive && sig >= prev_sig { return Ok ( core ::$t :: NEG_INFINITY ); } if is_positive && ( prev_sig != ( sig - digit as $t )/ radix as $t ){ return Ok ( core ::$t :: INFINITY ); } if ! is_positive && ( prev_sig != ( sig + digit as $t )/ radix as $t ){ return Ok ( core ::$t :: NEG_INFINITY ); }} prev_sig = sig ; }, None => match c { 'e' | 'E' | 'p' | 'P' =>{ exp_info = Some (( c , i + 1 )); break ; }, '.' =>{ break ; }, _ =>{ return Err ( PFE { kind : Invalid }); }, }, }} if exp_info . is_none (){ let mut power = 1.0 ; for ( i , c ) in cs . by_ref (){ match c . to_digit ( radix ){ Some ( digit )=>{ power = power / ( radix as $t ); sig = if is_positive { sig + ( digit as $t )* power } else { sig - ( digit as $t )* power }; if is_positive && sig < prev_sig { return Ok ( core ::$t :: INFINITY ); } if ! is_positive && sig > prev_sig { return Ok ( core ::$t :: NEG_INFINITY ); } prev_sig = sig ; }, None => match c { 'e' | 'E' | 'p' | 'P' =>{ exp_info = Some (( c , i + 1 )); break ; }, _ =>{ return Err ( PFE { kind : Invalid }); }, }, }}} let exp = match exp_info { Some (( c , offset ))=>{ let base = match c { 'E' | 'e' if radix == 10 => 10.0 , 'P' | 'p' if radix == 16 => 2.0 , _ => return Err ( PFE { kind : Invalid }), }; let src = & src [ offset ..]; let ( is_positive , exp )= match slice_shift_char ( src ){ Some (( '-' , src ))=>( false , src . parse ::< usize > ()), Some (( '+' , src ))=>( true , src . parse ::< usize > ()), Some ((_, _))=>( true , src . parse ::< usize > ()), None => return Err ( PFE { kind : Invalid }), }; # [ cfg ( feature = "std" )] fn pow ( base : $t , exp : usize )-> $t { Float :: powi ( base , exp as i32 )} match ( is_positive , exp ){( true , Ok ( exp ))=> pow ( base , exp ), ( false , Ok ( exp ))=> 1.0 / pow ( base , exp ), (_, Err (_))=> return Err ( PFE { kind : Invalid }), }}, None => 1.0 , }; Ok ( sig * exp )}})*)} +macro_rules! __ra_macro_fixture206 {($m : ident !! )=>($m ! {}); ($m : ident !! $h : ident , $($t : ident ,)* )=>($m ! {$h $($t )* } for_each_tuple_ ! {$m !! $($t ,)* }); } +macro_rules! __ra_macro_fixture207 {($($name : ident )* )=>( impl <$($name : Bounded ,)*> Bounded for ($($name ,)*){# [ inline ] fn min_value ()-> Self {($($name :: min_value (),)*)}# [ inline ] fn max_value ()-> Self {($($name :: max_value (),)*)}}); } +macro_rules! __ra_macro_fixture208 {($T : ty , $U : ty )=>{ impl Roots for $T {# [ inline ] fn nth_root (& self , n : u32 )-> Self { if * self >= 0 {(* self as $U ). nth_root ( n ) as Self } else { assert ! ( n . is_odd (), "even roots of a negative are imaginary" ); - (( self . wrapping_neg () as $U ). nth_root ( n ) as Self )}}# [ inline ] fn sqrt (& self )-> Self { assert ! (* self >= 0 , "the square root of a negative is imaginary" ); (* self as $U ). sqrt () as Self }# [ inline ] fn cbrt (& self )-> Self { if * self >= 0 {(* self as $U ). cbrt () as Self } else {- (( self . wrapping_neg () as $U ). cbrt () as Self )}}}}; } +macro_rules! __ra_macro_fixture209 {($T : ident )=>{ impl Roots for $T {# [ inline ] fn nth_root (& self , n : u32 )-> Self { fn go ( a : $T , n : u32 )-> $T { match n { 0 => panic ! ( "can't find a root of degree 0!" ), 1 => return a , 2 => return a . sqrt (), 3 => return a . cbrt (), _ =>(), } if bits ::<$T > ()<= n || a < ( 1 << n ){ return ( a > 0 ) as $T ; } if bits ::<$T > ()> 64 { return if a <= core :: u64 :: MAX as $T {( a as u64 ). nth_root ( n ) as $T } else { let lo = ( a >> n ). nth_root ( n )<< 1 ; let hi = lo + 1 ; if hi . next_power_of_two (). trailing_zeros ()* n >= bits ::<$T > (){ match checked_pow ( hi , n as usize ){ Some ( x ) if x <= a => hi , _ => lo , }} else { if hi . pow ( n )<= a { hi } else { lo }}}; }# [ cfg ( feature = "std" )]# [ inline ] fn guess ( x : $T , n : u32 )-> $T { if bits ::<$T > ()<= 32 || x <= core :: u32 :: MAX as $T { 1 << (( log2 ( x )+ n - 1 )/ n )} else {(( x as f64 ). ln ()/ f64 :: from ( n )). exp () as $T }}# [ cfg ( not ( feature = "std" ))]# [ inline ] fn guess ( x : $T , n : u32 )-> $T { 1 << (( log2 ( x )+ n - 1 )/ n )} let n1 = n - 1 ; let next = | x : $T | { let y = match checked_pow ( x , n1 as usize ){ Some ( ax )=> a / ax , None => 0 , }; ( y + x * n1 as $T )/ n as $T }; fixpoint ( guess ( a , n ), next )} go (* self , n )}# [ inline ] fn sqrt (& self )-> Self { fn go ( a : $T )-> $T { if bits ::<$T > ()> 64 { return if a <= core :: u64 :: MAX as $T {( a as u64 ). sqrt () as $T } else { let lo = ( a >> 2u32 ). sqrt ()<< 1 ; let hi = lo + 1 ; if hi * hi <= a { hi } else { lo }}; } if a < 4 { return ( a > 0 ) as $T ; }# [ cfg ( feature = "std" )]# [ inline ] fn guess ( x : $T )-> $T {( x as f64 ). sqrt () as $T }# [ cfg ( not ( feature = "std" ))]# [ inline ] fn guess ( x : $T )-> $T { 1 << (( log2 ( x )+ 1 )/ 2 )} let next = | x : $T | ( a / x + x )>> 1 ; fixpoint ( guess ( a ), next )} go (* self )}# [ inline ] fn cbrt (& self )-> Self { fn go ( a : $T )-> $T { if bits ::<$T > ()> 64 { return if a <= core :: u64 :: MAX as $T {( a as u64 ). cbrt () as $T } else { let lo = ( a >> 3u32 ). cbrt ()<< 1 ; let hi = lo + 1 ; if hi * hi * hi <= a { hi } else { lo }}; } if bits ::<$T > ()<= 32 { let mut x = a ; let mut y2 = 0 ; let mut y = 0 ; let smax = bits ::<$T > ()/ 3 ; for s in ( 0 .. smax + 1 ). rev (){ let s = s * 3 ; y2 *= 4 ; y *= 2 ; let b = 3 * ( y2 + y )+ 1 ; if x >> s >= b { x -= b << s ; y2 += 2 * y + 1 ; y += 1 ; }} return y ; } if a < 8 { return ( a > 0 ) as $T ; } if a <= core :: u32 :: MAX as $T { return ( a as u32 ). cbrt () as $T ; }# [ cfg ( feature = "std" )]# [ inline ] fn guess ( x : $T )-> $T {( x as f64 ). cbrt () as $T }# [ cfg ( not ( feature = "std" ))]# [ inline ] fn guess ( x : $T )-> $T { 1 << (( log2 ( x )+ 2 )/ 3 )} let next = | x : $T | ( a / ( x * x )+ x * 2 )/ 3 ; fixpoint ( guess ( a ), next )} go (* self )}}}; } +macro_rules! __ra_macro_fixture210 {($T : ty , $test_mod : ident )=>{ impl Integer for $T {# [ doc = " Floored integer division" ]# [ inline ] fn div_floor (& self , other : & Self )-> Self { let ( d , r )= self . div_rem ( other ); if ( r > 0 && * other < 0 )|| ( r < 0 && * other > 0 ){ d - 1 } else { d }}# [ doc = " Floored integer modulo" ]# [ inline ] fn mod_floor (& self , other : & Self )-> Self { let r = * self % * other ; if ( r > 0 && * other < 0 )|| ( r < 0 && * other > 0 ){ r + * other } else { r }}# [ doc = " Calculates `div_floor` and `mod_floor` simultaneously" ]# [ inline ] fn div_mod_floor (& self , other : & Self )-> ( Self , Self ){ let ( d , r )= self . div_rem ( other ); if ( r > 0 && * other < 0 )|| ( r < 0 && * other > 0 ){( d - 1 , r + * other )} else {( d , r )}}# [ inline ] fn div_ceil (& self , other : & Self )-> Self { let ( d , r )= self . div_rem ( other ); if ( r > 0 && * other > 0 )|| ( r < 0 && * other < 0 ){ d + 1 } else { d }}# [ doc = " Calculates the Greatest Common Divisor (GCD) of the number and" ]# [ doc = " `other`. The result is always positive." ]# [ inline ] fn gcd (& self , other : & Self )-> Self { let mut m = * self ; let mut n = * other ; if m == 0 || n == 0 { return ( m | n ). abs (); } let shift = ( m | n ). trailing_zeros (); if m == Self :: min_value ()|| n == Self :: min_value (){ return ( 1 << shift ). abs (); } m = m . abs (); n = n . abs (); m >>= m . trailing_zeros (); n >>= n . trailing_zeros (); while m != n { if m > n { m -= n ; m >>= m . trailing_zeros (); } else { n -= m ; n >>= n . trailing_zeros (); }} m << shift }# [ inline ] fn extended_gcd_lcm (& self , other : & Self )-> ( ExtendedGcd < Self >, Self ){ let egcd = self . extended_gcd ( other ); let lcm = if egcd . gcd . is_zero (){ Self :: zero ()} else {(* self * (* other / egcd . gcd )). abs ()}; ( egcd , lcm )}# [ doc = " Calculates the Lowest Common Multiple (LCM) of the number and" ]# [ doc = " `other`." ]# [ inline ] fn lcm (& self , other : & Self )-> Self { self . gcd_lcm ( other ). 1 }# [ doc = " Calculates the Greatest Common Divisor (GCD) and" ]# [ doc = " Lowest Common Multiple (LCM) of the number and `other`." ]# [ inline ] fn gcd_lcm (& self , other : & Self )-> ( Self , Self ){ if self . is_zero ()&& other . is_zero (){ return ( Self :: zero (), Self :: zero ()); } let gcd = self . gcd ( other ); let lcm = (* self * (* other / gcd )). abs (); ( gcd , lcm )}# [ doc = " Deprecated, use `is_multiple_of` instead." ]# [ inline ] fn divides (& self , other : & Self )-> bool { self . is_multiple_of ( other )}# [ doc = " Returns `true` if the number is a multiple of `other`." ]# [ inline ] fn is_multiple_of (& self , other : & Self )-> bool {* self % * other == 0 }# [ doc = " Returns `true` if the number is divisible by `2`" ]# [ inline ] fn is_even (& self )-> bool {(* self )& 1 == 0 }# [ doc = " Returns `true` if the number is not divisible by `2`" ]# [ inline ] fn is_odd (& self )-> bool {! self . is_even ()}# [ doc = " Simultaneous truncated integer division and modulus." ]# [ inline ] fn div_rem (& self , other : & Self )-> ( Self , Self ){(* self / * other , * self % * other )}}# [ cfg ( test )] mod $test_mod { use core :: mem ; use Integer ; # [ doc = " Checks that the division rule holds for:" ]# [ doc = "" ]# [ doc = " - `n`: numerator (dividend)" ]# [ doc = " - `d`: denominator (divisor)" ]# [ doc = " - `qr`: quotient and remainder" ]# [ cfg ( test )] fn test_division_rule (( n , d ): ($T , $T ), ( q , r ): ($T , $T )){ assert_eq ! ( d * q + r , n ); }# [ test ] fn test_div_rem (){ fn test_nd_dr ( nd : ($T , $T ), qr : ($T , $T )){ let ( n , d )= nd ; let separate_div_rem = ( n / d , n % d ); let combined_div_rem = n . div_rem (& d ); assert_eq ! ( separate_div_rem , qr ); assert_eq ! ( combined_div_rem , qr ); test_division_rule ( nd , separate_div_rem ); test_division_rule ( nd , combined_div_rem ); } test_nd_dr (( 8 , 3 ), ( 2 , 2 )); test_nd_dr (( 8 , - 3 ), (- 2 , 2 )); test_nd_dr ((- 8 , 3 ), (- 2 , - 2 )); test_nd_dr ((- 8 , - 3 ), ( 2 , - 2 )); test_nd_dr (( 1 , 2 ), ( 0 , 1 )); test_nd_dr (( 1 , - 2 ), ( 0 , 1 )); test_nd_dr ((- 1 , 2 ), ( 0 , - 1 )); test_nd_dr ((- 1 , - 2 ), ( 0 , - 1 )); }# [ test ] fn test_div_mod_floor (){ fn test_nd_dm ( nd : ($T , $T ), dm : ($T , $T )){ let ( n , d )= nd ; let separate_div_mod_floor = ( n . div_floor (& d ), n . mod_floor (& d )); let combined_div_mod_floor = n . div_mod_floor (& d ); assert_eq ! ( separate_div_mod_floor , dm ); assert_eq ! ( combined_div_mod_floor , dm ); test_division_rule ( nd , separate_div_mod_floor ); test_division_rule ( nd , combined_div_mod_floor ); } test_nd_dm (( 8 , 3 ), ( 2 , 2 )); test_nd_dm (( 8 , - 3 ), (- 3 , - 1 )); test_nd_dm ((- 8 , 3 ), (- 3 , 1 )); test_nd_dm ((- 8 , - 3 ), ( 2 , - 2 )); test_nd_dm (( 1 , 2 ), ( 0 , 1 )); test_nd_dm (( 1 , - 2 ), (- 1 , - 1 )); test_nd_dm ((- 1 , 2 ), (- 1 , 1 )); test_nd_dm ((- 1 , - 2 ), ( 0 , - 1 )); }# [ test ] fn test_gcd (){ assert_eq ! (( 10 as $T ). gcd (& 2 ), 2 as $T ); assert_eq ! (( 10 as $T ). gcd (& 3 ), 1 as $T ); assert_eq ! (( 0 as $T ). gcd (& 3 ), 3 as $T ); assert_eq ! (( 3 as $T ). gcd (& 3 ), 3 as $T ); assert_eq ! (( 56 as $T ). gcd (& 42 ), 14 as $T ); assert_eq ! (( 3 as $T ). gcd (&- 3 ), 3 as $T ); assert_eq ! ((- 6 as $T ). gcd (& 3 ), 3 as $T ); assert_eq ! ((- 4 as $T ). gcd (&- 2 ), 2 as $T ); }# [ test ] fn test_gcd_cmp_with_euclidean (){ fn euclidean_gcd ( mut m : $T , mut n : $T )-> $T { while m != 0 { mem :: swap (& mut m , & mut n ); m %= n ; } n . abs ()} for i in - 127 .. 127 { for j in - 127 .. 127 { assert_eq ! ( euclidean_gcd ( i , j ), i . gcd (& j )); }} let i = 127 ; for j in - 127 .. 127 { assert_eq ! ( euclidean_gcd ( i , j ), i . gcd (& j )); } assert_eq ! ( 127 . gcd (& 127 ), 127 ); }# [ test ] fn test_gcd_min_val (){ let min = <$T >:: min_value (); let max = <$T >:: max_value (); let max_pow2 = max / 2 + 1 ; assert_eq ! ( min . gcd (& max ), 1 as $T ); assert_eq ! ( max . gcd (& min ), 1 as $T ); assert_eq ! ( min . gcd (& max_pow2 ), max_pow2 ); assert_eq ! ( max_pow2 . gcd (& min ), max_pow2 ); assert_eq ! ( min . gcd (& 42 ), 2 as $T ); assert_eq ! (( 42 as $T ). gcd (& min ), 2 as $T ); }# [ test ]# [ should_panic ] fn test_gcd_min_val_min_val (){ let min = <$T >:: min_value (); assert ! ( min . gcd (& min )>= 0 ); }# [ test ]# [ should_panic ] fn test_gcd_min_val_0 (){ let min = <$T >:: min_value (); assert ! ( min . gcd (& 0 )>= 0 ); }# [ test ]# [ should_panic ] fn test_gcd_0_min_val (){ let min = <$T >:: min_value (); assert ! (( 0 as $T ). gcd (& min )>= 0 ); }# [ test ] fn test_lcm (){ assert_eq ! (( 1 as $T ). lcm (& 0 ), 0 as $T ); assert_eq ! (( 0 as $T ). lcm (& 1 ), 0 as $T ); assert_eq ! (( 1 as $T ). lcm (& 1 ), 1 as $T ); assert_eq ! ((- 1 as $T ). lcm (& 1 ), 1 as $T ); assert_eq ! (( 1 as $T ). lcm (&- 1 ), 1 as $T ); assert_eq ! ((- 1 as $T ). lcm (&- 1 ), 1 as $T ); assert_eq ! (( 8 as $T ). lcm (& 9 ), 72 as $T ); assert_eq ! (( 11 as $T ). lcm (& 5 ), 55 as $T ); }# [ test ] fn test_gcd_lcm (){ use core :: iter :: once ; for i in once ( 0 ). chain (( 1 ..). take ( 127 ). flat_map (| a | once ( a ). chain ( once (- a )))). chain ( once (- 128 )){ for j in once ( 0 ). chain (( 1 ..). take ( 127 ). flat_map (| a | once ( a ). chain ( once (- a )))). chain ( once (- 128 )){ assert_eq ! ( i . gcd_lcm (& j ), ( i . gcd (& j ), i . lcm (& j ))); }}}# [ test ] fn test_extended_gcd_lcm (){ use core :: fmt :: Debug ; use traits :: NumAssign ; use ExtendedGcd ; fn check < A : Copy + Debug + Integer + NumAssign > ( a : A , b : A ){ let ExtendedGcd { gcd , x , y , .. }= a . extended_gcd (& b ); assert_eq ! ( gcd , x * a + y * b ); } use core :: iter :: once ; for i in once ( 0 ). chain (( 1 ..). take ( 127 ). flat_map (| a | once ( a ). chain ( once (- a )))). chain ( once (- 128 )){ for j in once ( 0 ). chain (( 1 ..). take ( 127 ). flat_map (| a | once ( a ). chain ( once (- a )))). chain ( once (- 128 )){ check ( i , j ); let ( ExtendedGcd { gcd , .. }, lcm )= i . extended_gcd_lcm (& j ); assert_eq ! (( gcd , lcm ), ( i . gcd (& j ), i . lcm (& j ))); }}}# [ test ] fn test_even (){ assert_eq ! ((- 4 as $T ). is_even (), true ); assert_eq ! ((- 3 as $T ). is_even (), false ); assert_eq ! ((- 2 as $T ). is_even (), true ); assert_eq ! ((- 1 as $T ). is_even (), false ); assert_eq ! (( 0 as $T ). is_even (), true ); assert_eq ! (( 1 as $T ). is_even (), false ); assert_eq ! (( 2 as $T ). is_even (), true ); assert_eq ! (( 3 as $T ). is_even (), false ); assert_eq ! (( 4 as $T ). is_even (), true ); }# [ test ] fn test_odd (){ assert_eq ! ((- 4 as $T ). is_odd (), false ); assert_eq ! ((- 3 as $T ). is_odd (), true ); assert_eq ! ((- 2 as $T ). is_odd (), false ); assert_eq ! ((- 1 as $T ). is_odd (), true ); assert_eq ! (( 0 as $T ). is_odd (), false ); assert_eq ! (( 1 as $T ). is_odd (), true ); assert_eq ! (( 2 as $T ). is_odd (), false ); assert_eq ! (( 3 as $T ). is_odd (), true ); assert_eq ! (( 4 as $T ). is_odd (), false ); }}}; } +macro_rules! __ra_macro_fixture211 {($T : ty , $test_mod : ident )=>{ impl Integer for $T {# [ doc = " Unsigned integer division. Returns the same result as `div` (`/`)." ]# [ inline ] fn div_floor (& self , other : & Self )-> Self {* self / * other }# [ doc = " Unsigned integer modulo operation. Returns the same result as `rem` (`%`)." ]# [ inline ] fn mod_floor (& self , other : & Self )-> Self {* self % * other }# [ inline ] fn div_ceil (& self , other : & Self )-> Self {* self / * other + ( 0 != * self % * other ) as Self }# [ doc = " Calculates the Greatest Common Divisor (GCD) of the number and `other`" ]# [ inline ] fn gcd (& self , other : & Self )-> Self { let mut m = * self ; let mut n = * other ; if m == 0 || n == 0 { return m | n ; } let shift = ( m | n ). trailing_zeros (); m >>= m . trailing_zeros (); n >>= n . trailing_zeros (); while m != n { if m > n { m -= n ; m >>= m . trailing_zeros (); } else { n -= m ; n >>= n . trailing_zeros (); }} m << shift }# [ inline ] fn extended_gcd_lcm (& self , other : & Self )-> ( ExtendedGcd < Self >, Self ){ let egcd = self . extended_gcd ( other ); let lcm = if egcd . gcd . is_zero (){ Self :: zero ()} else {* self * (* other / egcd . gcd )}; ( egcd , lcm )}# [ doc = " Calculates the Lowest Common Multiple (LCM) of the number and `other`." ]# [ inline ] fn lcm (& self , other : & Self )-> Self { self . gcd_lcm ( other ). 1 }# [ doc = " Calculates the Greatest Common Divisor (GCD) and" ]# [ doc = " Lowest Common Multiple (LCM) of the number and `other`." ]# [ inline ] fn gcd_lcm (& self , other : & Self )-> ( Self , Self ){ if self . is_zero ()&& other . is_zero (){ return ( Self :: zero (), Self :: zero ()); } let gcd = self . gcd ( other ); let lcm = * self * (* other / gcd ); ( gcd , lcm )}# [ doc = " Deprecated, use `is_multiple_of` instead." ]# [ inline ] fn divides (& self , other : & Self )-> bool { self . is_multiple_of ( other )}# [ doc = " Returns `true` if the number is a multiple of `other`." ]# [ inline ] fn is_multiple_of (& self , other : & Self )-> bool {* self % * other == 0 }# [ doc = " Returns `true` if the number is divisible by `2`." ]# [ inline ] fn is_even (& self )-> bool {* self % 2 == 0 }# [ doc = " Returns `true` if the number is not divisible by `2`." ]# [ inline ] fn is_odd (& self )-> bool {! self . is_even ()}# [ doc = " Simultaneous truncated integer division and modulus." ]# [ inline ] fn div_rem (& self , other : & Self )-> ( Self , Self ){(* self / * other , * self % * other )}}# [ cfg ( test )] mod $test_mod { use core :: mem ; use Integer ; # [ test ] fn test_div_mod_floor (){ assert_eq ! (( 10 as $T ). div_floor (& ( 3 as $T )), 3 as $T ); assert_eq ! (( 10 as $T ). mod_floor (& ( 3 as $T )), 1 as $T ); assert_eq ! (( 10 as $T ). div_mod_floor (& ( 3 as $T )), ( 3 as $T , 1 as $T )); assert_eq ! (( 5 as $T ). div_floor (& ( 5 as $T )), 1 as $T ); assert_eq ! (( 5 as $T ). mod_floor (& ( 5 as $T )), 0 as $T ); assert_eq ! (( 5 as $T ). div_mod_floor (& ( 5 as $T )), ( 1 as $T , 0 as $T )); assert_eq ! (( 3 as $T ). div_floor (& ( 7 as $T )), 0 as $T ); assert_eq ! (( 3 as $T ). mod_floor (& ( 7 as $T )), 3 as $T ); assert_eq ! (( 3 as $T ). div_mod_floor (& ( 7 as $T )), ( 0 as $T , 3 as $T )); }# [ test ] fn test_gcd (){ assert_eq ! (( 10 as $T ). gcd (& 2 ), 2 as $T ); assert_eq ! (( 10 as $T ). gcd (& 3 ), 1 as $T ); assert_eq ! (( 0 as $T ). gcd (& 3 ), 3 as $T ); assert_eq ! (( 3 as $T ). gcd (& 3 ), 3 as $T ); assert_eq ! (( 56 as $T ). gcd (& 42 ), 14 as $T ); }# [ test ] fn test_gcd_cmp_with_euclidean (){ fn euclidean_gcd ( mut m : $T , mut n : $T )-> $T { while m != 0 { mem :: swap (& mut m , & mut n ); m %= n ; } n } for i in 0 .. 255 { for j in 0 .. 255 { assert_eq ! ( euclidean_gcd ( i , j ), i . gcd (& j )); }} let i = 255 ; for j in 0 .. 255 { assert_eq ! ( euclidean_gcd ( i , j ), i . gcd (& j )); } assert_eq ! ( 255 . gcd (& 255 ), 255 ); }# [ test ] fn test_lcm (){ assert_eq ! (( 1 as $T ). lcm (& 0 ), 0 as $T ); assert_eq ! (( 0 as $T ). lcm (& 1 ), 0 as $T ); assert_eq ! (( 1 as $T ). lcm (& 1 ), 1 as $T ); assert_eq ! (( 8 as $T ). lcm (& 9 ), 72 as $T ); assert_eq ! (( 11 as $T ). lcm (& 5 ), 55 as $T ); assert_eq ! (( 15 as $T ). lcm (& 17 ), 255 as $T ); }# [ test ] fn test_gcd_lcm (){ for i in ( 0 ..). take ( 256 ){ for j in ( 0 ..). take ( 256 ){ assert_eq ! ( i . gcd_lcm (& j ), ( i . gcd (& j ), i . lcm (& j ))); }}}# [ test ] fn test_is_multiple_of (){ assert ! (( 6 as $T ). is_multiple_of (& ( 6 as $T ))); assert ! (( 6 as $T ). is_multiple_of (& ( 3 as $T ))); assert ! (( 6 as $T ). is_multiple_of (& ( 1 as $T ))); }# [ test ] fn test_even (){ assert_eq ! (( 0 as $T ). is_even (), true ); assert_eq ! (( 1 as $T ). is_even (), false ); assert_eq ! (( 2 as $T ). is_even (), true ); assert_eq ! (( 3 as $T ). is_even (), false ); assert_eq ! (( 4 as $T ). is_even (), true ); }# [ test ] fn test_odd (){ assert_eq ! (( 0 as $T ). is_odd (), false ); assert_eq ! (( 1 as $T ). is_odd (), true ); assert_eq ! (( 2 as $T ). is_odd (), false ); assert_eq ! (( 3 as $T ). is_odd (), true ); assert_eq ! (( 4 as $T ). is_odd (), false ); }}}; } +macro_rules! __ra_macro_fixture212 {($I : ident , $U : ident )=>{ mod $I { use check ; use neg ; use num_integer :: Roots ; use pos ; use std :: mem ; # [ test ]# [ should_panic ] fn zeroth_root (){( 123 as $I ). nth_root ( 0 ); }# [ test ] fn sqrt (){ check (& pos ::<$I > (), 2 ); }# [ test ]# [ should_panic ] fn sqrt_neg (){(- 123 as $I ). sqrt (); }# [ test ] fn cbrt (){ check (& pos ::<$I > (), 3 ); }# [ test ] fn cbrt_neg (){ check (& neg ::<$I > (), 3 ); }# [ test ] fn nth_root (){ let bits = 8 * mem :: size_of ::<$I > () as u32 - 1 ; let pos = pos ::<$I > (); for n in 4 .. bits { check (& pos , n ); }}# [ test ] fn nth_root_neg (){ let bits = 8 * mem :: size_of ::<$I > () as u32 - 1 ; let neg = neg ::<$I > (); for n in 2 .. bits / 2 { check (& neg , 2 * n + 1 ); }}# [ test ] fn bit_size (){ let bits = 8 * mem :: size_of ::<$I > () as u32 - 1 ; assert_eq ! ($I :: max_value (). nth_root ( bits - 1 ), 2 ); assert_eq ! ($I :: max_value (). nth_root ( bits ), 1 ); assert_eq ! ($I :: min_value (). nth_root ( bits ), - 2 ); assert_eq ! (($I :: min_value ()+ 1 ). nth_root ( bits ), - 1 ); }} mod $U { use check ; use num_integer :: Roots ; use pos ; use std :: mem ; # [ test ]# [ should_panic ] fn zeroth_root (){( 123 as $U ). nth_root ( 0 ); }# [ test ] fn sqrt (){ check (& pos ::<$U > (), 2 ); }# [ test ] fn cbrt (){ check (& pos ::<$U > (), 3 ); }# [ test ] fn nth_root (){ let bits = 8 * mem :: size_of ::<$I > () as u32 - 1 ; let pos = pos ::<$I > (); for n in 4 .. bits { check (& pos , n ); }}# [ test ] fn bit_size (){ let bits = 8 * mem :: size_of ::<$U > () as u32 ; assert_eq ! ($U :: max_value (). nth_root ( bits - 1 ), 2 ); assert_eq ! ($U :: max_value (). nth_root ( bits ), 1 ); }}}; } +macro_rules! __ra_macro_fixture213 {($name : ident , $ranges : ident )=>{# [ test ] fn $name (){ let set = ranges_to_set ( general_category ::$ranges ); let hashset : HashSet < u32 > = set . iter (). cloned (). collect (); let trie = TrieSetOwned :: from_codepoints (& set ). unwrap (); for cp in 0 .. 0x110000 { assert ! ( trie . contains_u32 ( cp )== hashset . contains (& cp )); } assert ! (! trie . contains_u32 ( 0x110000 )); assert ! (! hashset . contains (& 0x110000 )); }}; } +macro_rules! __ra_macro_fixture214 {{$(mod $module : ident ; [$($prop : ident , )*]; )*}=>{$(# [ allow ( unused )] mod $module ; $(pub fn $prop ( c : char )-> bool { self ::$module ::$prop . contains_char ( c )})* )*}; } +macro_rules! __ra_macro_fixture215 {($name : ident : $input : expr , $($x : tt )* )=>{# [ test ] fn $name (){ let expected_sets = vec ! [$($x )*]; let range_set : RangeSet = $input . parse (). expect ( "parse failed" ); assert_eq ! ( range_set . ranges . len (), expected_sets . len ()); for it in range_set . ranges . iter (). zip ( expected_sets . iter ()){ let ( ai , bi )= it ; assert_eq ! ( ai . comparator_set . len (), * bi ); }}}; } +macro_rules! __ra_macro_fixture216 {($name : ident : $input : expr , $($x : tt )* )=>{# [ test ] fn $name (){ let expected_sets = vec ! [$($x )*]; let range_set = RangeSet :: parse ($input , Compat :: Npm ). expect ( "parse failed" ); assert_eq ! ( range_set . ranges . len (), expected_sets . len ()); for it in range_set . ranges . iter (). zip ( expected_sets . iter ()){ let ( ai , bi )= it ; assert_eq ! ( ai . comparator_set . len (), * bi ); }}}; } +macro_rules! __ra_macro_fixture217 {($($name : ident : $value : expr , )* )=>{$(# [ test ] fn $name (){ assert ! ($value . parse ::< RangeSet > (). is_err ()); })* }; } +macro_rules! __ra_macro_fixture218 {($($name : ident : $value : expr , )* )=>{$(# [ test ] fn $name (){ let ( input , expected_range )= $value ; let parsed_range = parse_range ( input ); let range = from_pair_iterator ( parsed_range , range_set :: Compat :: Cargo ). expect ( "parsing failed" ); let num_comparators = range . comparator_set . len (); let expected_comparators = expected_range . comparator_set . len (); assert_eq ! ( expected_comparators , num_comparators , "expected number of comparators: {}, got: {}" , expected_comparators , num_comparators ); assert_eq ! ( range , expected_range ); })* }; } +macro_rules! __ra_macro_fixture219 {($($name : ident : $value : expr , )* )=>{$(# [ test ] fn $name (){ let ( input , expected_range )= $value ; let parsed_range = parse_range ( input ); let range = from_pair_iterator ( parsed_range , range_set :: Compat :: Npm ). expect ( "parsing failed" ); let num_comparators = range . comparator_set . len (); let expected_comparators = expected_range . comparator_set . len (); assert_eq ! ( expected_comparators , num_comparators , "expected number of comparators: {}, got: {}" , expected_comparators , num_comparators ); assert_eq ! ( range , expected_range ); })* }; } +macro_rules! __ra_macro_fixture220 {($ty : ident $(<$lifetime : tt >)*)=>{ impl <$($lifetime ,)* E > Copy for $ty <$($lifetime ,)* E > {} impl <$($lifetime ,)* E > Clone for $ty <$($lifetime ,)* E > { fn clone (& self )-> Self {* self }}}; } +macro_rules! __ra_macro_fixture221 {($ty : ty , $doc : tt , $name : ident , $method : ident $($cast : tt )*)=>{# [ doc = "A deserializer holding" ]# [ doc = $doc ] pub struct $name < E > { value : $ty , marker : PhantomData < E > } impl_copy_clone ! ($name ); impl < 'de , E > IntoDeserializer < 'de , E > for $ty where E : de :: Error , { type Deserializer = $name < E >; fn into_deserializer ( self )-> $name < E > {$name { value : self , marker : PhantomData , }}} impl < 'de , E > de :: Deserializer < 'de > for $name < E > where E : de :: Error , { type Error = E ; forward_to_deserialize_any ! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any } fn deserialize_any < V > ( self , visitor : V )-> Result < V :: Value , Self :: Error > where V : de :: Visitor < 'de >, { visitor .$method ( self . value $($cast )*)}} impl < E > Debug for $name < E > { fn fmt (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . debug_struct ( stringify ! ($name )). field ( "value" , & self . value ). finish ()}}}} +macro_rules! __ra_macro_fixture222 {($($tt : tt )*)=>{}; } +macro_rules! __ra_macro_fixture223 {($ty : ident , $deserialize : ident $($methods : tt )*)=>{ impl < 'de > Deserialize < 'de > for $ty {# [ inline ] fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { struct PrimitiveVisitor ; impl < 'de > Visitor < 'de > for PrimitiveVisitor { type Value = $ty ; fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( stringify ! ($ty ))}$($methods )* } deserializer .$deserialize ( PrimitiveVisitor )}}}; } +macro_rules! __ra_macro_fixture224 {($ty : ident < T $(: $tbound1 : ident $(+ $tbound2 : ident )*)* $(, $typaram : ident : $bound1 : ident $(+ $bound2 : ident )*)* >, $access : ident , $clear : expr , $with_capacity : expr , $reserve : expr , $insert : expr )=>{ impl < 'de , T $(, $typaram )*> Deserialize < 'de > for $ty < T $(, $typaram )*> where T : Deserialize < 'de > $(+ $tbound1 $(+ $tbound2 )*)*, $($typaram : $bound1 $(+ $bound2 )*,)* { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { struct SeqVisitor < T $(, $typaram )*> { marker : PhantomData <$ty < T $(, $typaram )*>>, } impl < 'de , T $(, $typaram )*> Visitor < 'de > for SeqVisitor < T $(, $typaram )*> where T : Deserialize < 'de > $(+ $tbound1 $(+ $tbound2 )*)*, $($typaram : $bound1 $(+ $bound2 )*,)* { type Value = $ty < T $(, $typaram )*>; fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( "a sequence" )}# [ inline ] fn visit_seq < A > ( self , mut $access : A )-> Result < Self :: Value , A :: Error > where A : SeqAccess < 'de >, { let mut values = $with_capacity ; while let Some ( value )= try ! ($access . next_element ()){$insert (& mut values , value ); } Ok ( values )}} let visitor = SeqVisitor { marker : PhantomData }; deserializer . deserialize_seq ( visitor )} fn deserialize_in_place < D > ( deserializer : D , place : & mut Self )-> Result < (), D :: Error > where D : Deserializer < 'de >, { struct SeqInPlaceVisitor < 'a , T : 'a $(, $typaram : 'a )*> (& 'a mut $ty < T $(, $typaram )*>); impl < 'a , 'de , T $(, $typaram )*> Visitor < 'de > for SeqInPlaceVisitor < 'a , T $(, $typaram )*> where T : Deserialize < 'de > $(+ $tbound1 $(+ $tbound2 )*)*, $($typaram : $bound1 $(+ $bound2 )*,)* { type Value = (); fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( "a sequence" )}# [ inline ] fn visit_seq < A > ( mut self , mut $access : A )-> Result < Self :: Value , A :: Error > where A : SeqAccess < 'de >, {$clear (& mut self . 0 ); $reserve (& mut self . 0 , size_hint :: cautious ($access . size_hint ())); while let Some ( value )= try ! ($access . next_element ()){$insert (& mut self . 0 , value ); } Ok (())}} deserializer . deserialize_seq ( SeqInPlaceVisitor ( place ))}}}} +macro_rules! __ra_macro_fixture225 {($($len : expr =>($($n : tt )+))+)=>{$(impl < 'de , T > Visitor < 'de > for ArrayVisitor < [ T ; $len ]> where T : Deserialize < 'de >, { type Value = [ T ; $len ]; fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( concat ! ( "an array of length " , $len ))}# [ inline ] fn visit_seq < A > ( self , mut seq : A )-> Result < Self :: Value , A :: Error > where A : SeqAccess < 'de >, { Ok ([$(match try ! ( seq . next_element ()){ Some ( val )=> val , None => return Err ( Error :: invalid_length ($n , & self )), }),+])}} impl < 'a , 'de , T > Visitor < 'de > for ArrayInPlaceVisitor < 'a , [ T ; $len ]> where T : Deserialize < 'de >, { type Value = (); fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( concat ! ( "an array of length " , $len ))}# [ inline ] fn visit_seq < A > ( self , mut seq : A )-> Result < Self :: Value , A :: Error > where A : SeqAccess < 'de >, { let mut fail_idx = None ; for ( idx , dest ) in self . 0 [..]. iter_mut (). enumerate (){ if try ! ( seq . next_element_seed ( InPlaceSeed ( dest ))). is_none (){ fail_idx = Some ( idx ); break ; }} if let Some ( idx )= fail_idx { return Err ( Error :: invalid_length ( idx , & self )); } Ok (())}} impl < 'de , T > Deserialize < 'de > for [ T ; $len ] where T : Deserialize < 'de >, { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { deserializer . deserialize_tuple ($len , ArrayVisitor ::< [ T ; $len ]>:: new ())} fn deserialize_in_place < D > ( deserializer : D , place : & mut Self )-> Result < (), D :: Error > where D : Deserializer < 'de >, { deserializer . deserialize_tuple ($len , ArrayInPlaceVisitor ( place ))}})+ }} +macro_rules! __ra_macro_fixture226 {($($len : tt =>($($n : tt $name : ident )+))+)=>{$(impl < 'de , $($name : Deserialize < 'de >),+> Deserialize < 'de > for ($($name ,)+){# [ inline ] fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { struct TupleVisitor <$($name ,)+> { marker : PhantomData < ($($name ,)+)>, } impl < 'de , $($name : Deserialize < 'de >),+> Visitor < 'de > for TupleVisitor <$($name ,)+> { type Value = ($($name ,)+); fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( concat ! ( "a tuple of size " , $len ))}# [ inline ]# [ allow ( non_snake_case )] fn visit_seq < A > ( self , mut seq : A )-> Result < Self :: Value , A :: Error > where A : SeqAccess < 'de >, {$(let $name = match try ! ( seq . next_element ()){ Some ( value )=> value , None => return Err ( Error :: invalid_length ($n , & self )), }; )+ Ok (($($name ,)+))}} deserializer . deserialize_tuple ($len , TupleVisitor { marker : PhantomData })}# [ inline ] fn deserialize_in_place < D > ( deserializer : D , place : & mut Self )-> Result < (), D :: Error > where D : Deserializer < 'de >, { struct TupleInPlaceVisitor < 'a , $($name : 'a ,)+> (& 'a mut ($($name ,)+)); impl < 'a , 'de , $($name : Deserialize < 'de >),+> Visitor < 'de > for TupleInPlaceVisitor < 'a , $($name ,)+> { type Value = (); fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( concat ! ( "a tuple of size " , $len ))}# [ inline ]# [ allow ( non_snake_case )] fn visit_seq < A > ( self , mut seq : A )-> Result < Self :: Value , A :: Error > where A : SeqAccess < 'de >, {$(if try ! ( seq . next_element_seed ( InPlaceSeed (& mut ( self . 0 ).$n ))). is_none (){ return Err ( Error :: invalid_length ($n , & self )); })+ Ok (())}} deserializer . deserialize_tuple ($len , TupleInPlaceVisitor ( place ))}})+ }} +macro_rules! __ra_macro_fixture227 {($ty : ident < K $(: $kbound1 : ident $(+ $kbound2 : ident )*)*, V $(, $typaram : ident : $bound1 : ident $(+ $bound2 : ident )*)* >, $access : ident , $with_capacity : expr )=>{ impl < 'de , K , V $(, $typaram )*> Deserialize < 'de > for $ty < K , V $(, $typaram )*> where K : Deserialize < 'de > $(+ $kbound1 $(+ $kbound2 )*)*, V : Deserialize < 'de >, $($typaram : $bound1 $(+ $bound2 )*),* { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { struct MapVisitor < K , V $(, $typaram )*> { marker : PhantomData <$ty < K , V $(, $typaram )*>>, } impl < 'de , K , V $(, $typaram )*> Visitor < 'de > for MapVisitor < K , V $(, $typaram )*> where K : Deserialize < 'de > $(+ $kbound1 $(+ $kbound2 )*)*, V : Deserialize < 'de >, $($typaram : $bound1 $(+ $bound2 )*),* { type Value = $ty < K , V $(, $typaram )*>; fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ( "a map" )}# [ inline ] fn visit_map < A > ( self , mut $access : A )-> Result < Self :: Value , A :: Error > where A : MapAccess < 'de >, { let mut values = $with_capacity ; while let Some (( key , value ))= try ! ($access . next_entry ()){ values . insert ( key , value ); } Ok ( values )}} let visitor = MapVisitor { marker : PhantomData }; deserializer . deserialize_map ( visitor )}}}} +macro_rules! __ra_macro_fixture228 {($expecting : tt $ty : ty ; $size : tt )=>{ impl < 'de > Deserialize < 'de > for $ty { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { if deserializer . is_human_readable (){ deserializer . deserialize_str ( FromStrVisitor :: new ($expecting ))} else {< [ u8 ; $size ]>:: deserialize ( deserializer ). map (<$ty >:: from )}}}}; } +macro_rules! __ra_macro_fixture229 {($expecting : tt $ty : ty , $new : expr )=>{ impl < 'de > Deserialize < 'de > for $ty { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { if deserializer . is_human_readable (){ deserializer . deserialize_str ( FromStrVisitor :: new ($expecting ))} else {< (_, u16 )>:: deserialize ( deserializer ). map (| ( ip , port )| $new ( ip , port ))}}}}; } +macro_rules! __ra_macro_fixture230 {($name_kind : ident ($($variant : ident ; $bytes : expr ; $index : expr ),* )$expecting_message : expr , $variants_name : ident )=>{ enum $name_kind {$($variant ),* } static $variants_name : & 'static [& 'static str ]= & [$(stringify ! ($variant )),*]; impl < 'de > Deserialize < 'de > for $name_kind { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { struct KindVisitor ; impl < 'de > Visitor < 'de > for KindVisitor { type Value = $name_kind ; fn expecting (& self , formatter : & mut fmt :: Formatter )-> fmt :: Result { formatter . write_str ($expecting_message )} fn visit_u64 < E > ( self , value : u64 )-> Result < Self :: Value , E > where E : Error , { match value {$($index => Ok ($name_kind :: $variant ), )* _ => Err ( Error :: invalid_value ( Unexpected :: Unsigned ( value ), & self ),), }} fn visit_str < E > ( self , value : & str )-> Result < Self :: Value , E > where E : Error , { match value {$(stringify ! ($variant )=> Ok ($name_kind :: $variant ), )* _ => Err ( Error :: unknown_variant ( value , $variants_name )), }} fn visit_bytes < E > ( self , value : & [ u8 ])-> Result < Self :: Value , E > where E : Error , { match value {$($bytes => Ok ($name_kind :: $variant ), )* _ =>{ match str :: from_utf8 ( value ){ Ok ( value )=> Err ( Error :: unknown_variant ( value , $variants_name )), Err (_)=> Err ( Error :: invalid_value ( Unexpected :: Bytes ( value ), & self )), }}}}} deserializer . deserialize_identifier ( KindVisitor )}}}} +macro_rules! __ra_macro_fixture231 {($(# [ doc = $doc : tt ])* ($($id : ident ),* ), $ty : ty , $func : expr )=>{$(# [ doc = $doc ])* impl < 'de $(, $id : Deserialize < 'de >,)*> Deserialize < 'de > for $ty { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { Deserialize :: deserialize ( deserializer ). map ($func )}}}} +macro_rules! __ra_macro_fixture232 {($($T : ident , )+ )=>{$(# [ cfg ( num_nonzero )] impl < 'de > Deserialize < 'de > for num ::$T { fn deserialize < D > ( deserializer : D )-> Result < Self , D :: Error > where D : Deserializer < 'de >, { let value = try ! ( Deserialize :: deserialize ( deserializer )); match < num ::$T >:: new ( value ){ Some ( nonzero )=> Ok ( nonzero ), None => Err ( Error :: custom ( "expected a non-zero value" )), }}})+ }; } +macro_rules! __ra_macro_fixture233 {( Error : Sized $(+ $($supertrait : ident )::+)*)=>{# [ doc = " The `Error` trait allows `Deserialize` implementations to create descriptive" ]# [ doc = " error messages belonging to the `Deserializer` against which they are" ]# [ doc = " currently running." ]# [ doc = "" ]# [ doc = " Every `Deserializer` declares an `Error` type that encompasses both" ]# [ doc = " general-purpose deserialization errors as well as errors specific to the" ]# [ doc = " particular deserialization format. For example the `Error` type of" ]# [ doc = " `serde_json` can represent errors like an invalid JSON escape sequence or an" ]# [ doc = " unterminated string literal, in addition to the error cases that are part of" ]# [ doc = " this trait." ]# [ doc = "" ]# [ doc = " Most deserializers should only need to provide the `Error::custom` method" ]# [ doc = " and inherit the default behavior for the other methods." ]# [ doc = "" ]# [ doc = " # Example implementation" ]# [ doc = "" ]# [ doc = " The [example data format] presented on the website shows an error" ]# [ doc = " type appropriate for a basic JSON data format." ]# [ doc = "" ]# [ doc = " [example data format]: https://serde.rs/data-format.html" ] pub trait Error : Sized $(+ $($supertrait )::+)* {# [ doc = " Raised when there is general error when deserializing a type." ]# [ doc = "" ]# [ doc = " The message should not be capitalized and should not end with a period." ]# [ doc = "" ]# [ doc = " ```edition2018" ]# [ doc = " # use std::str::FromStr;" ]# [ doc = " #" ]# [ doc = " # struct IpAddr;" ]# [ doc = " #" ]# [ doc = " # impl FromStr for IpAddr {" ]# [ doc = " # type Err = String;" ]# [ doc = " #" ]# [ doc = " # fn from_str(_: &str) -> Result<Self, String> {" ]# [ doc = " # unimplemented!()" ]# [ doc = " # }" ]# [ doc = " # }" ]# [ doc = " #" ]# [ doc = " use serde::de::{self, Deserialize, Deserializer};" ]# [ doc = "" ]# [ doc = " impl<\\\'de> Deserialize<\\\'de> for IpAddr {" ]# [ doc = " fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>" ]# [ doc = " where" ]# [ doc = " D: Deserializer<\\\'de>," ]# [ doc = " {" ]# [ doc = " let s = String::deserialize(deserializer)?;" ]# [ doc = " s.parse().map_err(de::Error::custom)" ]# [ doc = " }" ]# [ doc = " }" ]# [ doc = " ```" ] fn custom < T > ( msg : T )-> Self where T : Display ; # [ doc = " Raised when a `Deserialize` receives a type different from what it was" ]# [ doc = " expecting." ]# [ doc = "" ]# [ doc = " The `unexp` argument provides information about what type was received." ]# [ doc = " This is the type that was present in the input file or other source data" ]# [ doc = " of the Deserializer." ]# [ doc = "" ]# [ doc = " The `exp` argument provides information about what type was being" ]# [ doc = " expected. This is the type that is written in the program." ]# [ doc = "" ]# [ doc = " For example if we try to deserialize a String out of a JSON file" ]# [ doc = " containing an integer, the unexpected type is the integer and the" ]# [ doc = " expected type is the string." ]# [ cold ] fn invalid_type ( unexp : Unexpected , exp : & Expected )-> Self { Error :: custom ( format_args ! ( "invalid type: {}, expected {}" , unexp , exp ))}# [ doc = " Raised when a `Deserialize` receives a value of the right type but that" ]# [ doc = " is wrong for some other reason." ]# [ doc = "" ]# [ doc = " The `unexp` argument provides information about what value was received." ]# [ doc = " This is the value that was present in the input file or other source" ]# [ doc = " data of the Deserializer." ]# [ doc = "" ]# [ doc = " The `exp` argument provides information about what value was being" ]# [ doc = " expected. This is the type that is written in the program." ]# [ doc = "" ]# [ doc = " For example if we try to deserialize a String out of some binary data" ]# [ doc = " that is not valid UTF-8, the unexpected value is the bytes and the" ]# [ doc = " expected value is a string." ]# [ cold ] fn invalid_value ( unexp : Unexpected , exp : & Expected )-> Self { Error :: custom ( format_args ! ( "invalid value: {}, expected {}" , unexp , exp ))}# [ doc = " Raised when deserializing a sequence or map and the input data contains" ]# [ doc = " too many or too few elements." ]# [ doc = "" ]# [ doc = " The `len` argument is the number of elements encountered. The sequence" ]# [ doc = " or map may have expected more arguments or fewer arguments." ]# [ doc = "" ]# [ doc = " The `exp` argument provides information about what data was being" ]# [ doc = " expected. For example `exp` might say that a tuple of size 6 was" ]# [ doc = " expected." ]# [ cold ] fn invalid_length ( len : usize , exp : & Expected )-> Self { Error :: custom ( format_args ! ( "invalid length {}, expected {}" , len , exp ))}# [ doc = " Raised when a `Deserialize` enum type received a variant with an" ]# [ doc = " unrecognized name." ]# [ cold ] fn unknown_variant ( variant : & str , expected : & 'static [& 'static str ])-> Self { if expected . is_empty (){ Error :: custom ( format_args ! ( "unknown variant `{}`, there are no variants" , variant ))} else { Error :: custom ( format_args ! ( "unknown variant `{}`, expected {}" , variant , OneOf { names : expected }))}}# [ doc = " Raised when a `Deserialize` struct type received a field with an" ]# [ doc = " unrecognized name." ]# [ cold ] fn unknown_field ( field : & str , expected : & 'static [& 'static str ])-> Self { if expected . is_empty (){ Error :: custom ( format_args ! ( "unknown field `{}`, there are no fields" , field ))} else { Error :: custom ( format_args ! ( "unknown field `{}`, expected {}" , field , OneOf { names : expected }))}}# [ doc = " Raised when a `Deserialize` struct type expected to receive a required" ]# [ doc = " field with a particular name but that field was not present in the" ]# [ doc = " input." ]# [ cold ] fn missing_field ( field : & 'static str )-> Self { Error :: custom ( format_args ! ( "missing field `{}`" , field ))}# [ doc = " Raised when a `Deserialize` struct type received more than one of the" ]# [ doc = " same field." ]# [ cold ] fn duplicate_field ( field : & 'static str )-> Self { Error :: custom ( format_args ! ( "duplicate field `{}`" , field ))}}}} +macro_rules! __ra_macro_fixture234 {($ty : ident , $method : ident $($cast : tt )*)=>{ impl Serialize for $ty {# [ inline ] fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , { serializer .$method (* self $($cast )*)}}}} +macro_rules! __ra_macro_fixture235 {($($len : tt )+)=>{$(impl < T > Serialize for [ T ; $len ] where T : Serialize , {# [ inline ] fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , { let mut seq = try ! ( serializer . serialize_tuple ($len )); for e in self { try ! ( seq . serialize_element ( e )); } seq . end ()}})+ }} +macro_rules! __ra_macro_fixture236 {($ty : ident < T $(: $tbound1 : ident $(+ $tbound2 : ident )*)* $(, $typaram : ident : $bound : ident )* >)=>{ impl < T $(, $typaram )*> Serialize for $ty < T $(, $typaram )*> where T : Serialize $(+ $tbound1 $(+ $tbound2 )*)*, $($typaram : $bound ,)* {# [ inline ] fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , { serializer . collect_seq ( self )}}}} +macro_rules! __ra_macro_fixture237 {($($len : expr =>($($n : tt $name : ident )+))+)=>{$(impl <$($name ),+> Serialize for ($($name ,)+) where $($name : Serialize ,)+ {# [ inline ] fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , { let mut tuple = try ! ( serializer . serialize_tuple ($len )); $(try ! ( tuple . serialize_element (& self .$n )); )+ tuple . end ()}})+ }} +macro_rules! __ra_macro_fixture238 {($ty : ident < K $(: $kbound1 : ident $(+ $kbound2 : ident )*)*, V $(, $typaram : ident : $bound : ident )* >)=>{ impl < K , V $(, $typaram )*> Serialize for $ty < K , V $(, $typaram )*> where K : Serialize $(+ $kbound1 $(+ $kbound2 )*)*, V : Serialize , $($typaram : $bound ,)* {# [ inline ] fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , { serializer . collect_map ( self )}}}} +macro_rules! __ra_macro_fixture239 {($(# [ doc = $doc : tt ])* <$($desc : tt )+ )=>{$(# [ doc = $doc ])* impl <$($desc )+ {# [ inline ] fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , {(** self ). serialize ( serializer )}}}; } +macro_rules! __ra_macro_fixture240 {($($T : ident , )+ )=>{$(# [ cfg ( num_nonzero )] impl Serialize for num ::$T { fn serialize < S > (& self , serializer : S )-> Result < S :: Ok , S :: Error > where S : Serializer , { self . get (). serialize ( serializer )}})+ }} +macro_rules! __ra_macro_fixture241 {( Error : Sized $(+ $($supertrait : ident )::+)*)=>{# [ doc = " Trait used by `Serialize` implementations to generically construct" ]# [ doc = " errors belonging to the `Serializer` against which they are" ]# [ doc = " currently running." ]# [ doc = "" ]# [ doc = " # Example implementation" ]# [ doc = "" ]# [ doc = " The [example data format] presented on the website shows an error" ]# [ doc = " type appropriate for a basic JSON data format." ]# [ doc = "" ]# [ doc = " [example data format]: https://serde.rs/data-format.html" ] pub trait Error : Sized $(+ $($supertrait )::+)* {# [ doc = " Used when a [`Serialize`] implementation encounters any error" ]# [ doc = " while serializing a type." ]# [ doc = "" ]# [ doc = " The message should not be capitalized and should not end with a" ]# [ doc = " period." ]# [ doc = "" ]# [ doc = " For example, a filesystem [`Path`] may refuse to serialize" ]# [ doc = " itself if it contains invalid UTF-8 data." ]# [ doc = "" ]# [ doc = " ```edition2018" ]# [ doc = " # struct Path;" ]# [ doc = " #" ]# [ doc = " # impl Path {" ]# [ doc = " # fn to_str(&self) -> Option<&str> {" ]# [ doc = " # unimplemented!()" ]# [ doc = " # }" ]# [ doc = " # }" ]# [ doc = " #" ]# [ doc = " use serde::ser::{self, Serialize, Serializer};" ]# [ doc = "" ]# [ doc = " impl Serialize for Path {" ]# [ doc = " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>" ]# [ doc = " where" ]# [ doc = " S: Serializer," ]# [ doc = " {" ]# [ doc = " match self.to_str() {" ]# [ doc = " Some(s) => serializer.serialize_str(s)," ]# [ doc = " None => Err(ser::Error::custom(\\\"path contains invalid UTF-8 characters\\\"))," ]# [ doc = " }" ]# [ doc = " }" ]# [ doc = " }" ]# [ doc = " ```" ]# [ doc = "" ]# [ doc = " [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html" ]# [ doc = " [`Serialize`]: ../trait.Serialize.html" ] fn custom < T > ( msg : T )-> Self where T : Display ; }}} +macro_rules! __ra_macro_fixture242 {($t : ty , $($attr : meta ),* )=>{$(# [$attr ])* impl < L , R > AsRef <$t > for Either < L , R > where L : AsRef <$t >, R : AsRef <$t > { fn as_ref (& self )-> &$t { either ! (* self , ref inner => inner . as_ref ())}}$(# [$attr ])* impl < L , R > AsMut <$t > for Either < L , R > where L : AsMut <$t >, R : AsMut <$t > { fn as_mut (& mut self )-> & mut $t { either ! (* self , ref mut inner => inner . as_mut ())}}}; } +macro_rules! __ra_macro_fixture243 {($C : ident $P : ident ; $A : ident , $($I : ident ),* ; $($X : ident )*)=>(# [ derive ( Clone , Debug )] pub struct $C < I : Iterator > { item : Option < I :: Item >, iter : I , c : $P < I >, } impl < I : Iterator + Clone > From < I > for $C < I > { fn from ( mut iter : I )-> Self {$C { item : iter . next (), iter : iter . clone (), c : $P :: from ( iter ), }}} impl < I : Iterator + Clone > From < I > for $C < Fuse < I >> { fn from ( iter : I )-> Self { let mut iter = iter . fuse (); $C { item : iter . next (), iter : iter . clone (), c : $P :: from ( iter ), }}} impl < I , $A > Iterator for $C < I > where I : Iterator < Item = $A > + Clone , I :: Item : Clone { type Item = ($($I ),*); fn next (& mut self )-> Option < Self :: Item > { if let Some (($($X ),*,))= self . c . next (){ let z = self . item . clone (). unwrap (); Some (( z , $($X ),*))} else { self . item = self . iter . next (); self . item . clone (). and_then (| z | { self . c = $P :: from ( self . iter . clone ()); self . c . next (). map (| ($($X ),*,)| ( z , $($X ),*))})}}} impl < I , $A > HasCombination < I > for ($($I ),*) where I : Iterator < Item = $A > + Clone , I :: Item : Clone { type Combination = $C < Fuse < I >>; })} +macro_rules! __ra_macro_fixture244 (($_A : ident , $_B : ident , )=>(); ($A : ident , $($B : ident ,)*)=>( impl_cons_iter ! ($($B ,)*); # [ allow ( non_snake_case )] impl < X , Iter , $($B ),*> Iterator for ConsTuples < Iter , (($($B ,)*), X )> where Iter : Iterator < Item = (($($B ,)*), X )>, { type Item = ($($B ,)* X , ); fn next (& mut self )-> Option < Self :: Item > { self . iter . next (). map (| (($($B ,)*), x )| ($($B ,)* x , ))} fn size_hint (& self )-> ( usize , Option < usize >){ self . iter . size_hint ()} fn fold < Acc , Fold > ( self , accum : Acc , mut f : Fold )-> Acc where Fold : FnMut ( Acc , Self :: Item )-> Acc , { self . iter . fold ( accum , move | acc , (($($B ,)*), x )| f ( acc , ($($B ,)* x , )))}}# [ allow ( non_snake_case )] impl < X , Iter , $($B ),*> DoubleEndedIterator for ConsTuples < Iter , (($($B ,)*), X )> where Iter : DoubleEndedIterator < Item = (($($B ,)*), X )>, { fn next_back (& mut self )-> Option < Self :: Item > { self . iter . next (). map (| (($($B ,)*), x )| ($($B ,)* x , ))}}); ); +macro_rules! __ra_macro_fixture245 {($($fmt_trait : ident )*)=>{$(impl < 'a , I > fmt ::$fmt_trait for Format < 'a , I > where I : Iterator , I :: Item : fmt ::$fmt_trait , { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { self . format ( f , fmt ::$fmt_trait :: fmt )}})* }} +macro_rules! __ra_macro_fixture246 {([$($typarm : tt )*]$type_ : ty )=>{ impl <$($typarm )*> PeekingNext for $type_ { fn peeking_next < F > (& mut self , accept : F )-> Option < Self :: Item > where F : FnOnce (& Self :: Item )-> bool { let saved_state = self . clone (); if let Some ( r )= self . next (){ if ! accept (& r ){* self = saved_state ; } else { return Some ( r )}} None }}}} +macro_rules! __ra_macro_fixture247 {($dummy : ident ,)=>{}; ($dummy : ident , $($Y : ident ,)*)=>( impl_tuple_collect ! ($($Y ,)*); impl < A > TupleCollect for ($(ignore_ident ! ($Y , A ),)*){ type Item = A ; type Buffer = [ Option < A >; count_ident ! ($($Y ,)*)- 1 ]; # [ allow ( unused_assignments , unused_mut )] fn collect_from_iter < I > ( iter : I , buf : & mut Self :: Buffer )-> Option < Self > where I : IntoIterator < Item = A >{ let mut iter = iter . into_iter (); $(let mut $Y = None ; )* loop {$($Y = iter . next (); if $Y . is_none (){ break })* return Some (($($Y . unwrap ()),*,))} let mut i = 0 ; let mut s = buf . as_mut (); $(if i < s . len (){ s [ i ]= $Y ; i += 1 ; })* return None ; } fn collect_from_iter_no_buf < I > ( iter : I )-> Option < Self > where I : IntoIterator < Item = A >{ let mut iter = iter . into_iter (); Some (($({let $Y = iter . next ()?; $Y }, )*))} fn num_items ()-> usize { count_ident ! ($($Y ,)*)} fn left_shift_push (& mut self , mut item : A ){ use std :: mem :: replace ; let & mut ($(ref mut $Y ),*,)= self ; macro_rules ! replace_item {($i : ident )=>{ item = replace ($i , item ); }}; rev_for_each_ident ! ( replace_item , $($Y ,)*); drop ( item ); }})} +macro_rules! __ra_macro_fixture248 {($($B : ident ),*)=>(# [ allow ( non_snake_case )] impl <$($B : IntoIterator ),*> From < ($($B ,)*)> for Zip < ($($B :: IntoIter ,)*)> { fn from ( t : ($($B ,)*))-> Self { let ($($B ,)*)= t ; Zip { t : ($($B . into_iter (),)*)}}}# [ allow ( non_snake_case )]# [ allow ( unused_assignments )] impl <$($B ),*> Iterator for Zip < ($($B ,)*)> where $($B : Iterator , )* { type Item = ($($B :: Item ,)*); fn next (& mut self )-> Option < Self :: Item > { let ($(ref mut $B ,)*)= self . t ; $(let $B = match $B . next (){ None => return None , Some ( elt )=> elt }; )* Some (($($B ,)*))} fn size_hint (& self )-> ( usize , Option < usize >){ let sh = (:: std :: usize :: MAX , None ); let ($(ref $B ,)*)= self . t ; $(let sh = size_hint :: min ($B . size_hint (), sh ); )* sh }}# [ allow ( non_snake_case )] impl <$($B ),*> ExactSizeIterator for Zip < ($($B ,)*)> where $($B : ExactSizeIterator , )* {}# [ allow ( non_snake_case )] impl <$($B ),*> DoubleEndedIterator for Zip < ($($B ,)*)> where $($B : DoubleEndedIterator + ExactSizeIterator , )* {# [ inline ] fn next_back (& mut self )-> Option < Self :: Item > { let ($(ref mut $B ,)*)= self . t ; let size = * [$($B . len (), )*]. iter (). min (). unwrap (); $(if $B . len ()!= size { for _ in 0 ..$B . len ()- size {$B . next_back (); }})* match ($($B . next_back (),)*){($(Some ($B ),)*)=> Some (($($B ,)*)), _ => None , }}}); } +macro_rules! __ra_macro_fixture249 {($iter : ty =>$item : ty , impl $($args : tt )* )=>{ delegate_iterator ! {$iter =>$item , impl $($args )* } impl $($args )* IndexedParallelIterator for $iter { fn drive < C > ( self , consumer : C )-> C :: Result where C : Consumer < Self :: Item > { self . inner . drive ( consumer )} fn len (& self )-> usize { self . inner . len ()} fn with_producer < CB > ( self , callback : CB )-> CB :: Output where CB : ProducerCallback < Self :: Item > { self . inner . with_producer ( callback )}}}} +macro_rules! __ra_macro_fixture250 {($t : ty =>$iter : ident <$($i : tt ),*>, impl $($args : tt )*)=>{ impl $($args )* IntoParallelIterator for $t { type Item = <$t as IntoIterator >:: Item ; type Iter = $iter <$($i ),*>; fn into_par_iter ( self )-> Self :: Iter { use std :: iter :: FromIterator ; $iter { inner : Vec :: from_iter ( self ). into_par_iter ()}}}}; } +macro_rules! __ra_macro_fixture251 {($iter : ty =>$item : ty , impl $($args : tt )* )=>{ impl $($args )* ParallelIterator for $iter { type Item = $item ; fn drive_unindexed < C > ( self , consumer : C )-> C :: Result where C : UnindexedConsumer < Self :: Item > { self . inner . drive_unindexed ( consumer )} fn opt_len (& self )-> Option < usize > { self . inner . opt_len ()}}}} +macro_rules! __ra_macro_fixture252 {($($Tuple : ident {$(($idx : tt )-> $T : ident )+ })+)=>{$(impl <$($T , )+> IntoParallelIterator for ($($T , )+) where $($T : IntoParallelIterator , $T :: Iter : IndexedParallelIterator , )+ { type Item = ($($T :: Item , )+); type Iter = MultiZip < ($($T :: Iter , )+)>; fn into_par_iter ( self )-> Self :: Iter { MultiZip { tuple : ($(self .$idx . into_par_iter (), )+ ), }}} impl < 'a , $($T , )+> IntoParallelIterator for & 'a ($($T , )+) where $($T : IntoParallelRefIterator < 'a >, $T :: Iter : IndexedParallelIterator , )+ { type Item = ($($T :: Item , )+); type Iter = MultiZip < ($($T :: Iter , )+)>; fn into_par_iter ( self )-> Self :: Iter { MultiZip { tuple : ($(self .$idx . par_iter (), )+ ), }}} impl < 'a , $($T , )+> IntoParallelIterator for & 'a mut ($($T , )+) where $($T : IntoParallelRefMutIterator < 'a >, $T :: Iter : IndexedParallelIterator , )+ { type Item = ($($T :: Item , )+); type Iter = MultiZip < ($($T :: Iter , )+)>; fn into_par_iter ( self )-> Self :: Iter { MultiZip { tuple : ($(self .$idx . par_iter_mut (), )+ ), }}} impl <$($T , )+> ParallelIterator for MultiZip < ($($T , )+)> where $($T : IndexedParallelIterator , )+ { type Item = ($($T :: Item , )+); fn drive_unindexed < CONSUMER > ( self , consumer : CONSUMER )-> CONSUMER :: Result where CONSUMER : UnindexedConsumer < Self :: Item >, { self . drive ( consumer )} fn opt_len (& self )-> Option < usize > { Some ( self . len ())}} impl <$($T , )+> IndexedParallelIterator for MultiZip < ($($T , )+)> where $($T : IndexedParallelIterator , )+ { fn drive < CONSUMER > ( self , consumer : CONSUMER )-> CONSUMER :: Result where CONSUMER : Consumer < Self :: Item >, { reduce ! ($(self . tuple .$idx ),+ => IndexedParallelIterator :: zip ). map ( flatten ! ($($T ),+)). drive ( consumer )} fn len (& self )-> usize { reduce ! ($(self . tuple .$idx . len ()),+ => Ord :: min )} fn with_producer < CB > ( self , callback : CB )-> CB :: Output where CB : ProducerCallback < Self :: Item >, { reduce ! ($(self . tuple .$idx ),+ => IndexedParallelIterator :: zip ). map ( flatten ! ($($T ),+)). with_producer ( callback )}})+ }} +macro_rules! __ra_macro_fixture253 {($t : ty )=>{ impl ParallelIterator for Iter <$t > { type Item = $t ; fn drive_unindexed < C > ( self , consumer : C )-> C :: Result where C : UnindexedConsumer < Self :: Item >, { bridge ( self , consumer )} fn opt_len (& self )-> Option < usize > { Some ( self . len ())}} impl IndexedParallelIterator for Iter <$t > { fn drive < C > ( self , consumer : C )-> C :: Result where C : Consumer < Self :: Item >, { bridge ( self , consumer )} fn len (& self )-> usize { self . range . len ()} fn with_producer < CB > ( self , callback : CB )-> CB :: Output where CB : ProducerCallback < Self :: Item >, { callback . callback ( IterProducer { range : self . range })}} impl Producer for IterProducer <$t > { type Item = < Range <$t > as Iterator >:: Item ; type IntoIter = Range <$t >; fn into_iter ( self )-> Self :: IntoIter { self . range } fn split_at ( self , index : usize )-> ( Self , Self ){ assert ! ( index <= self . range . len ()); let mid = self . range . start . wrapping_add ( index as $t ); let left = self . range . start .. mid ; let right = mid .. self . range . end ; ( IterProducer { range : left }, IterProducer { range : right })}}}; } +macro_rules! __ra_macro_fixture254 {($t : ty , $len_t : ty )=>{ impl UnindexedRangeLen <$len_t > for Range <$t > { fn len (& self )-> $len_t { let & Range { start , end }= self ; if end > start { end . wrapping_sub ( start ) as $len_t } else { 0 }}} impl ParallelIterator for Iter <$t > { type Item = $t ; fn drive_unindexed < C > ( self , consumer : C )-> C :: Result where C : UnindexedConsumer < Self :: Item >, {# [ inline ] fn offset ( start : $t )-> impl Fn ( usize )-> $t { move | i | start . wrapping_add ( i as $t )} if let Some ( len )= self . opt_len (){( 0 .. len ). into_par_iter (). map ( offset ( self . range . start )). drive ( consumer )} else { bridge_unindexed ( IterProducer { range : self . range }, consumer )}} fn opt_len (& self )-> Option < usize > { let len = self . range . len (); if len <= usize :: MAX as $len_t { Some ( len as usize )} else { None }}} impl UnindexedProducer for IterProducer <$t > { type Item = $t ; fn split ( mut self )-> ( Self , Option < Self >){ let index = self . range . len ()/ 2 ; if index > 0 { let mid = self . range . start . wrapping_add ( index as $t ); let right = mid .. self . range . end ; self . range . end = mid ; ( self , Some ( IterProducer { range : right }))} else {( self , None )}} fn fold_with < F > ( self , folder : F )-> F where F : Folder < Self :: Item >, { folder . consume_iter ( self )}}}; } +macro_rules! __ra_macro_fixture255 {($t : ty )=>{ parallel_range_impl ! {$t } impl IndexedParallelIterator for Iter <$t > { fn drive < C > ( self , consumer : C )-> C :: Result where C : Consumer < Self :: Item >, { convert ! ( self . drive ( consumer ))} fn len (& self )-> usize { self . range . len ()} fn with_producer < CB > ( self , callback : CB )-> CB :: Output where CB : ProducerCallback < Self :: Item >, { convert ! ( self . with_producer ( callback ))}}}; } +macro_rules! __ra_macro_fixture256 {($t : ty )=>{ impl ParallelIterator for Iter <$t > { type Item = $t ; fn drive_unindexed < C > ( self , consumer : C )-> C :: Result where C : UnindexedConsumer < Self :: Item >, { convert ! ( self . drive_unindexed ( consumer ))} fn opt_len (& self )-> Option < usize > { convert ! ( self . opt_len ())}}}; } +macro_rules! __ra_macro_fixture257 {($f : ident , $name : ident )=>{# [ test ] fn $name (){ let mut rng = thread_rng (); for len in ( 0 .. 25 ). chain ( 500 .. 501 ){ for & modulus in & [ 5 , 10 , 100 ]{ let dist = Uniform :: new ( 0 , modulus ); for _ in 0 .. 100 { let v : Vec < i32 > = rng . sample_iter (& dist ). take ( len ). collect (); let mut tmp = v . clone (); tmp .$f (| a , b | a . cmp ( b )); assert ! ( tmp . windows ( 2 ). all (| w | w [ 0 ]<= w [ 1 ])); let mut tmp = v . clone (); tmp .$f (| a , b | b . cmp ( a )); assert ! ( tmp . windows ( 2 ). all (| w | w [ 0 ]>= w [ 1 ])); }}} for & len in & [ 1_000 , 10_000 , 100_000 ]{ for & modulus in & [ 5 , 10 , 100 , 10_000 ]{ let dist = Uniform :: new ( 0 , modulus ); let mut v : Vec < i32 > = rng . sample_iter (& dist ). take ( len ). collect (); v .$f (| a , b | a . cmp ( b )); assert ! ( v . windows ( 2 ). all (| w | w [ 0 ]<= w [ 1 ])); }} for & len in & [ 1_000 , 10_000 , 100_000 ]{ let len_dist = Uniform :: new ( 0 , len ); for & modulus in & [ 5 , 10 , 1000 , 50_000 ]{ let dist = Uniform :: new ( 0 , modulus ); let mut v : Vec < i32 > = rng . sample_iter (& dist ). take ( len ). collect (); v . sort (); v . reverse (); for _ in 0 .. 5 { let a = rng . sample (& len_dist ); let b = rng . sample (& len_dist ); if a < b { v [ a .. b ]. reverse (); } else { v . swap ( a , b ); }} v .$f (| a , b | a . cmp ( b )); assert ! ( v . windows ( 2 ). all (| w | w [ 0 ]<= w [ 1 ])); }} let mut v : Vec <_> = ( 0 .. 100 ). collect (); v .$f (|_, _| * [ Less , Equal , Greater ]. choose (& mut thread_rng ()). unwrap ()); v .$f (| a , b | a . cmp ( b )); for i in 0 .. v . len (){ assert_eq ! ( v [ i ], i ); }[ 0i32 ; 0 ].$f (| a , b | a . cmp ( b )); [(); 10 ].$f (| a , b | a . cmp ( b )); [(); 100 ].$f (| a , b | a . cmp ( b )); let mut v = [ 0xDEAD_BEEFu64 ]; v .$f (| a , b | a . cmp ( b )); assert ! ( v == [ 0xDEAD_BEEF ]); }}; } +macro_rules! __ra_macro_fixture258 {($($name : ident # [$expr : meta ])*)=>{$(# [ doc = " First sanity check that the expression is OK." ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " #![deny(unused_must_use)]" ]# [ doc = "" ]# [ doc = " use rayon::prelude::*;" ]# [ doc = "" ]# [ doc = " let v: Vec<_> = (0..100).map(Some).collect();" ]# [ doc = " let _ =" ]# [$expr ]# [ doc = " ```" ]# [ doc = "" ]# [ doc = " Now trigger the `must_use`." ]# [ doc = "" ]# [ doc = " ```compile_fail" ]# [ doc = " #![deny(unused_must_use)]" ]# [ doc = "" ]# [ doc = " use rayon::prelude::*;" ]# [ doc = "" ]# [ doc = " let v: Vec<_> = (0..100).map(Some).collect();" ]# [$expr ]# [ doc = " ```" ] mod $name {})*}} +macro_rules! __ra_macro_fixture259 {($name : ident : $style : expr ; $input : expr =>$result : expr )=>{# [ test ] fn $name (){ assert_eq ! ($style . paint ($input ). to_string (), $result . to_string ()); let mut v = Vec :: new (); $style . paint ($input . as_bytes ()). write_to (& mut v ). unwrap (); assert_eq ! ( v . as_slice (), $result . as_bytes ()); }}; } +macro_rules! __ra_macro_fixture260 {($name : ident : $first : expr ; $next : expr =>$result : expr )=>{# [ test ] fn $name (){ assert_eq ! ($result , Difference :: between (&$first , &$next )); }}; } +macro_rules! __ra_macro_fixture261 {($name : ident : $obj : expr =>$result : expr )=>{# [ test ] fn $name (){ assert_eq ! ($result , format ! ( "{:?}" , $obj )); }}; } +macro_rules! __ra_macro_fixture262 {($name : ident , $ty_int : ty , $max : expr , $bytes : expr , $read : ident , $write : ident )=>{ mod $name {# [ allow ( unused_imports )] use super :: { qc_sized , Wi128 }; use crate :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; # [ test ] fn big_endian (){ fn prop ( n : $ty_int )-> bool { let mut buf = [ 0 ; 16 ]; BigEndian ::$write (& mut buf , n . clone (), $bytes ); n == BigEndian ::$read (& buf [..$bytes ], $bytes )} qc_sized ( prop as fn ($ty_int )-> bool , $max ); }# [ test ] fn little_endian (){ fn prop ( n : $ty_int )-> bool { let mut buf = [ 0 ; 16 ]; LittleEndian ::$write (& mut buf , n . clone (), $bytes ); n == LittleEndian ::$read (& buf [..$bytes ], $bytes )} qc_sized ( prop as fn ($ty_int )-> bool , $max ); }# [ test ] fn native_endian (){ fn prop ( n : $ty_int )-> bool { let mut buf = [ 0 ; 16 ]; NativeEndian ::$write (& mut buf , n . clone (), $bytes ); n == NativeEndian ::$read (& buf [..$bytes ], $bytes )} qc_sized ( prop as fn ($ty_int )-> bool , $max ); }}}; ($name : ident , $ty_int : ty , $max : expr , $read : ident , $write : ident )=>{ mod $name {# [ allow ( unused_imports )] use super :: { qc_sized , Wi128 }; use crate :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; use core :: mem :: size_of ; # [ test ] fn big_endian (){ fn prop ( n : $ty_int )-> bool { let bytes = size_of ::<$ty_int > (); let mut buf = [ 0 ; 16 ]; BigEndian ::$write (& mut buf [ 16 - bytes ..], n . clone ()); n == BigEndian ::$read (& buf [ 16 - bytes ..])} qc_sized ( prop as fn ($ty_int )-> bool , $max - 1 ); }# [ test ] fn little_endian (){ fn prop ( n : $ty_int )-> bool { let bytes = size_of ::<$ty_int > (); let mut buf = [ 0 ; 16 ]; LittleEndian ::$write (& mut buf [.. bytes ], n . clone ()); n == LittleEndian ::$read (& buf [.. bytes ])} qc_sized ( prop as fn ($ty_int )-> bool , $max - 1 ); }# [ test ] fn native_endian (){ fn prop ( n : $ty_int )-> bool { let bytes = size_of ::<$ty_int > (); let mut buf = [ 0 ; 16 ]; NativeEndian ::$write (& mut buf [.. bytes ], n . clone ()); n == NativeEndian ::$read (& buf [.. bytes ])} qc_sized ( prop as fn ($ty_int )-> bool , $max - 1 ); }}}; } +macro_rules! __ra_macro_fixture263 {($name : ident , $maximally_small : expr , $zero : expr , $read : ident , $write : ident )=>{ mod $name { use crate :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; # [ test ]# [ should_panic ] fn read_big_endian (){ let buf = [ 0 ; $maximally_small ]; BigEndian ::$read (& buf ); }# [ test ]# [ should_panic ] fn read_little_endian (){ let buf = [ 0 ; $maximally_small ]; LittleEndian ::$read (& buf ); }# [ test ]# [ should_panic ] fn read_native_endian (){ let buf = [ 0 ; $maximally_small ]; NativeEndian ::$read (& buf ); }# [ test ]# [ should_panic ] fn write_big_endian (){ let mut buf = [ 0 ; $maximally_small ]; BigEndian ::$write (& mut buf , $zero ); }# [ test ]# [ should_panic ] fn write_little_endian (){ let mut buf = [ 0 ; $maximally_small ]; LittleEndian ::$write (& mut buf , $zero ); }# [ test ]# [ should_panic ] fn write_native_endian (){ let mut buf = [ 0 ; $maximally_small ]; NativeEndian ::$write (& mut buf , $zero ); }}}; ($name : ident , $maximally_small : expr , $read : ident )=>{ mod $name { use crate :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; # [ test ]# [ should_panic ] fn read_big_endian (){ let buf = [ 0 ; $maximally_small ]; BigEndian ::$read (& buf , $maximally_small + 1 ); }# [ test ]# [ should_panic ] fn read_little_endian (){ let buf = [ 0 ; $maximally_small ]; LittleEndian ::$read (& buf , $maximally_small + 1 ); }# [ test ]# [ should_panic ] fn read_native_endian (){ let buf = [ 0 ; $maximally_small ]; NativeEndian ::$read (& buf , $maximally_small + 1 ); }}}; } +macro_rules! __ra_macro_fixture264 {($name : ident , $read : ident , $write : ident , $num_bytes : expr , $numbers : expr )=>{ mod $name { use crate :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; # [ test ]# [ should_panic ] fn read_big_endian (){ let bytes = [ 0 ; $num_bytes ]; let mut numbers = $numbers ; BigEndian ::$read (& bytes , & mut numbers ); }# [ test ]# [ should_panic ] fn read_little_endian (){ let bytes = [ 0 ; $num_bytes ]; let mut numbers = $numbers ; LittleEndian ::$read (& bytes , & mut numbers ); }# [ test ]# [ should_panic ] fn read_native_endian (){ let bytes = [ 0 ; $num_bytes ]; let mut numbers = $numbers ; NativeEndian ::$read (& bytes , & mut numbers ); }# [ test ]# [ should_panic ] fn write_big_endian (){ let mut bytes = [ 0 ; $num_bytes ]; let numbers = $numbers ; BigEndian ::$write (& numbers , & mut bytes ); }# [ test ]# [ should_panic ] fn write_little_endian (){ let mut bytes = [ 0 ; $num_bytes ]; let numbers = $numbers ; LittleEndian ::$write (& numbers , & mut bytes ); }# [ test ]# [ should_panic ] fn write_native_endian (){ let mut bytes = [ 0 ; $num_bytes ]; let numbers = $numbers ; NativeEndian ::$write (& numbers , & mut bytes ); }}}; } +macro_rules! __ra_macro_fixture265 {($name : ident , $which : ident , $re : expr )=>{ test_lit ! ($name , $which , $re ,); }; ($name : ident , $which : ident , $re : expr , $($lit : expr ),*)=>{# [ test ] fn $name (){ let expr = ParserBuilder :: new (). build (). parse ($re ). unwrap (); let lits = Literals ::$which (& expr ); assert_lit_eq ! ( Unicode , lits , $($lit ),*); let expr = ParserBuilder :: new (). allow_invalid_utf8 ( true ). unicode ( false ). build (). parse ($re ). unwrap (); let lits = Literals ::$which (& expr ); assert_lit_eq ! ( Bytes , lits , $($lit ),*); }}; } +macro_rules! __ra_macro_fixture266 {($name : ident , $which : ident , $re : expr )=>{ test_exhausted ! ($name , $which , $re ,); }; ($name : ident , $which : ident , $re : expr , $($lit : expr ),*)=>{# [ test ] fn $name (){ let expr = ParserBuilder :: new (). build (). parse ($re ). unwrap (); let mut lits = Literals :: empty (); lits . set_limit_size ( 20 ). set_limit_class ( 10 ); $which (& mut lits , & expr ); assert_lit_eq ! ( Unicode , lits , $($lit ),*); let expr = ParserBuilder :: new (). allow_invalid_utf8 ( true ). unicode ( false ). build (). parse ($re ). unwrap (); let mut lits = Literals :: empty (); lits . set_limit_size ( 20 ). set_limit_class ( 10 ); $which (& mut lits , & expr ); assert_lit_eq ! ( Bytes , lits , $($lit ),*); }}; } +macro_rules! __ra_macro_fixture267 {($name : ident , $given : expr , $expected : expr )=>{# [ test ] fn $name (){ let given : Vec < Literal > = $given . into_iter (). map (| ul | { let cut = ul . is_cut (); Literal { v : ul . v . into_bytes (), cut : cut }}). collect (); let lits = create_lits ( given ); let got = lits . unambiguous_prefixes (); assert_eq ! ($expected , escape_lits ( got . literals ())); }}; } +macro_rules! __ra_macro_fixture268 {($name : ident , $trim : expr , $given : expr , $expected : expr )=>{# [ test ] fn $name (){ let given : Vec < Literal > = $given . into_iter (). map (| ul | { let cut = ul . is_cut (); Literal { v : ul . v . into_bytes (), cut : cut }}). collect (); let lits = create_lits ( given ); let got = lits . trim_suffix ($trim ). unwrap (); assert_eq ! ($expected , escape_lits ( got . literals ())); }}; } +macro_rules! __ra_macro_fixture269 {($name : ident , $given : expr , $expected : expr )=>{# [ test ] fn $name (){ let given : Vec < Literal > = $given . into_iter (). map (| s : & str | Literal { v : s . to_owned (). into_bytes (), cut : false , }). collect (); let lits = create_lits ( given ); let got = lits . longest_common_prefix (); assert_eq ! ($expected , escape_bytes ( got )); }}; } +macro_rules! __ra_macro_fixture270 {($name : ident , $given : expr , $expected : expr )=>{# [ test ] fn $name (){ let given : Vec < Literal > = $given . into_iter (). map (| s : & str | Literal { v : s . to_owned (). into_bytes (), cut : false , }). collect (); let lits = create_lits ( given ); let got = lits . longest_common_suffix (); assert_eq ! ($expected , escape_bytes ( got )); }}; } +macro_rules! __ra_macro_fixture271 {($name : ident , $text : expr )=>{# [ test ] fn $name (){ assert_eq ! ( None , find_cap_ref ($text . as_bytes ())); }}; ($name : ident , $text : expr , $capref : expr )=>{# [ test ] fn $name (){ assert_eq ! ( Some ($capref ), find_cap_ref ($text . as_bytes ())); }}; } +macro_rules! __ra_macro_fixture272 {($name : ident , $regex_mod : ident , $only_utf8 : expr )=>{ pub mod $name { use super :: RegexOptions ; use error :: Error ; use exec :: ExecBuilder ; use $regex_mod :: Regex ; # [ doc = " A configurable builder for a regular expression." ]# [ doc = "" ]# [ doc = " A builder can be used to configure how the regex is built, for example, by" ]# [ doc = " setting the default flags (which can be overridden in the expression" ]# [ doc = " itself) or setting various limits." ]# [ derive ( Debug )] pub struct RegexBuilder ( RegexOptions ); impl RegexBuilder {# [ doc = " Create a new regular expression builder with the given pattern." ]# [ doc = "" ]# [ doc = " If the pattern is invalid, then an error will be returned when" ]# [ doc = " `build` is called." ] pub fn new ( pattern : & str )-> RegexBuilder { let mut builder = RegexBuilder ( RegexOptions :: default ()); builder . 0 . pats . push ( pattern . to_owned ()); builder }# [ doc = " Consume the builder and compile the regular expression." ]# [ doc = "" ]# [ doc = " Note that calling `as_str` on the resulting `Regex` will produce the" ]# [ doc = " pattern given to `new` verbatim. Notably, it will not incorporate any" ]# [ doc = " of the flags set on this builder." ] pub fn build (& self )-> Result < Regex , Error > { ExecBuilder :: new_options ( self . 0 . clone ()). only_utf8 ($only_utf8 ). build (). map ( Regex :: from )}# [ doc = " Set the value for the case insensitive (`i`) flag." ]# [ doc = "" ]# [ doc = " When enabled, letters in the pattern will match both upper case and" ]# [ doc = " lower case variants." ] pub fn case_insensitive (& mut self , yes : bool , )-> & mut RegexBuilder { self . 0 . case_insensitive = yes ; self }# [ doc = " Set the value for the multi-line matching (`m`) flag." ]# [ doc = "" ]# [ doc = " When enabled, `^` matches the beginning of lines and `$` matches the" ]# [ doc = " end of lines." ]# [ doc = "" ]# [ doc = " By default, they match beginning/end of the input." ] pub fn multi_line (& mut self , yes : bool )-> & mut RegexBuilder { self . 0 . multi_line = yes ; self }# [ doc = " Set the value for the any character (`s`) flag, where in `.` matches" ]# [ doc = " anything when `s` is set and matches anything except for new line when" ]# [ doc = " it is not set (the default)." ]# [ doc = "" ]# [ doc = " N.B. \\\"matches anything\\\" means \\\"any byte\\\" when Unicode is disabled and" ]# [ doc = " means \\\"any valid UTF-8 encoding of any Unicode scalar value\\\" when" ]# [ doc = " Unicode is enabled." ] pub fn dot_matches_new_line (& mut self , yes : bool , )-> & mut RegexBuilder { self . 0 . dot_matches_new_line = yes ; self }# [ doc = " Set the value for the greedy swap (`U`) flag." ]# [ doc = "" ]# [ doc = " When enabled, a pattern like `a*` is lazy (tries to find shortest" ]# [ doc = " match) and `a*?` is greedy (tries to find longest match)." ]# [ doc = "" ]# [ doc = " By default, `a*` is greedy and `a*?` is lazy." ] pub fn swap_greed (& mut self , yes : bool )-> & mut RegexBuilder { self . 0 . swap_greed = yes ; self }# [ doc = " Set the value for the ignore whitespace (`x`) flag." ]# [ doc = "" ]# [ doc = " When enabled, whitespace such as new lines and spaces will be ignored" ]# [ doc = " between expressions of the pattern, and `#` can be used to start a" ]# [ doc = " comment until the next new line." ] pub fn ignore_whitespace (& mut self , yes : bool , )-> & mut RegexBuilder { self . 0 . ignore_whitespace = yes ; self }# [ doc = " Set the value for the Unicode (`u`) flag." ]# [ doc = "" ]# [ doc = " Enabled by default. When disabled, character classes such as `\\\\w` only" ]# [ doc = " match ASCII word characters instead of all Unicode word characters." ] pub fn unicode (& mut self , yes : bool )-> & mut RegexBuilder { self . 0 . unicode = yes ; self }# [ doc = " Whether to support octal syntax or not." ]# [ doc = "" ]# [ doc = " Octal syntax is a little-known way of uttering Unicode codepoints in" ]# [ doc = " a regular expression. For example, `a`, `\\\\x61`, `\\\\u0061` and" ]# [ doc = " `\\\\141` are all equivalent regular expressions, where the last example" ]# [ doc = " shows octal syntax." ]# [ doc = "" ]# [ doc = " While supporting octal syntax isn\\\'t in and of itself a problem, it does" ]# [ doc = " make good error messages harder. That is, in PCRE based regex engines," ]# [ doc = " syntax like `\\\\0` invokes a backreference, which is explicitly" ]# [ doc = " unsupported in Rust\\\'s regex engine. However, many users expect it to" ]# [ doc = " be supported. Therefore, when octal support is disabled, the error" ]# [ doc = " message will explicitly mention that backreferences aren\\\'t supported." ]# [ doc = "" ]# [ doc = " Octal syntax is disabled by default." ] pub fn octal (& mut self , yes : bool )-> & mut RegexBuilder { self . 0 . octal = yes ; self }# [ doc = " Set the approximate size limit of the compiled regular expression." ]# [ doc = "" ]# [ doc = " This roughly corresponds to the number of bytes occupied by a single" ]# [ doc = " compiled program. If the program exceeds this number, then a" ]# [ doc = " compilation error is returned." ] pub fn size_limit (& mut self , limit : usize , )-> & mut RegexBuilder { self . 0 . size_limit = limit ; self }# [ doc = " Set the approximate size of the cache used by the DFA." ]# [ doc = "" ]# [ doc = " This roughly corresponds to the number of bytes that the DFA will" ]# [ doc = " use while searching." ]# [ doc = "" ]# [ doc = " Note that this is a *per thread* limit. There is no way to set a global" ]# [ doc = " limit. In particular, if a regex is used from multiple threads" ]# [ doc = " simultaneously, then each thread may use up to the number of bytes" ]# [ doc = " specified here." ] pub fn dfa_size_limit (& mut self , limit : usize , )-> & mut RegexBuilder { self . 0 . dfa_size_limit = limit ; self }# [ doc = " Set the nesting limit for this parser." ]# [ doc = "" ]# [ doc = " The nesting limit controls how deep the abstract syntax tree is allowed" ]# [ doc = " to be. If the AST exceeds the given limit (e.g., with too many nested" ]# [ doc = " groups), then an error is returned by the parser." ]# [ doc = "" ]# [ doc = " The purpose of this limit is to act as a heuristic to prevent stack" ]# [ doc = " overflow for consumers that do structural induction on an `Ast` using" ]# [ doc = " explicit recursion. While this crate never does this (instead using" ]# [ doc = " constant stack space and moving the call stack to the heap), other" ]# [ doc = " crates may." ]# [ doc = "" ]# [ doc = " This limit is not checked until the entire Ast is parsed. Therefore," ]# [ doc = " if callers want to put a limit on the amount of heap space used, then" ]# [ doc = " they should impose a limit on the length, in bytes, of the concrete" ]# [ doc = " pattern string. In particular, this is viable since this parser" ]# [ doc = " implementation will limit itself to heap space proportional to the" ]# [ doc = " length of the pattern string." ]# [ doc = "" ]# [ doc = " Note that a nest limit of `0` will return a nest limit error for most" ]# [ doc = " patterns but not all. For example, a nest limit of `0` permits `a` but" ]# [ doc = " not `ab`, since `ab` requires a concatenation, which results in a nest" ]# [ doc = " depth of `1`. In general, a nest limit is not something that manifests" ]# [ doc = " in an obvious way in the concrete syntax, therefore, it should not be" ]# [ doc = " used in a granular way." ] pub fn nest_limit (& mut self , limit : u32 )-> & mut RegexBuilder { self . 0 . nest_limit = limit ; self }}}}; } +macro_rules! __ra_macro_fixture273 {($name : ident , $regex_mod : ident , $only_utf8 : expr )=>{ pub mod $name { use super :: RegexOptions ; use error :: Error ; use exec :: ExecBuilder ; use re_set ::$regex_mod :: RegexSet ; # [ doc = " A configurable builder for a set of regular expressions." ]# [ doc = "" ]# [ doc = " A builder can be used to configure how the regexes are built, for example," ]# [ doc = " by setting the default flags (which can be overridden in the expression" ]# [ doc = " itself) or setting various limits." ]# [ derive ( Debug )] pub struct RegexSetBuilder ( RegexOptions ); impl RegexSetBuilder {# [ doc = " Create a new regular expression builder with the given pattern." ]# [ doc = "" ]# [ doc = " If the pattern is invalid, then an error will be returned when" ]# [ doc = " `build` is called." ] pub fn new < I , S > ( patterns : I )-> RegexSetBuilder where S : AsRef < str >, I : IntoIterator < Item = S >, { let mut builder = RegexSetBuilder ( RegexOptions :: default ()); for pat in patterns { builder . 0 . pats . push ( pat . as_ref (). to_owned ()); } builder }# [ doc = " Consume the builder and compile the regular expressions into a set." ] pub fn build (& self )-> Result < RegexSet , Error > { ExecBuilder :: new_options ( self . 0 . clone ()). only_utf8 ($only_utf8 ). build (). map ( RegexSet :: from )}# [ doc = " Set the value for the case insensitive (`i`) flag." ] pub fn case_insensitive (& mut self , yes : bool , )-> & mut RegexSetBuilder { self . 0 . case_insensitive = yes ; self }# [ doc = " Set the value for the multi-line matching (`m`) flag." ] pub fn multi_line (& mut self , yes : bool , )-> & mut RegexSetBuilder { self . 0 . multi_line = yes ; self }# [ doc = " Set the value for the any character (`s`) flag, where in `.` matches" ]# [ doc = " anything when `s` is set and matches anything except for new line when" ]# [ doc = " it is not set (the default)." ]# [ doc = "" ]# [ doc = " N.B. \\\"matches anything\\\" means \\\"any byte\\\" for `regex::bytes::RegexSet`" ]# [ doc = " expressions and means \\\"any Unicode scalar value\\\" for `regex::RegexSet`" ]# [ doc = " expressions." ] pub fn dot_matches_new_line (& mut self , yes : bool , )-> & mut RegexSetBuilder { self . 0 . dot_matches_new_line = yes ; self }# [ doc = " Set the value for the greedy swap (`U`) flag." ] pub fn swap_greed (& mut self , yes : bool , )-> & mut RegexSetBuilder { self . 0 . swap_greed = yes ; self }# [ doc = " Set the value for the ignore whitespace (`x`) flag." ] pub fn ignore_whitespace (& mut self , yes : bool , )-> & mut RegexSetBuilder { self . 0 . ignore_whitespace = yes ; self }# [ doc = " Set the value for the Unicode (`u`) flag." ] pub fn unicode (& mut self , yes : bool )-> & mut RegexSetBuilder { self . 0 . unicode = yes ; self }# [ doc = " Whether to support octal syntax or not." ]# [ doc = "" ]# [ doc = " Octal syntax is a little-known way of uttering Unicode codepoints in" ]# [ doc = " a regular expression. For example, `a`, `\\\\x61`, `\\\\u0061` and" ]# [ doc = " `\\\\141` are all equivalent regular expressions, where the last example" ]# [ doc = " shows octal syntax." ]# [ doc = "" ]# [ doc = " While supporting octal syntax isn\\\'t in and of itself a problem, it does" ]# [ doc = " make good error messages harder. That is, in PCRE based regex engines," ]# [ doc = " syntax like `\\\\0` invokes a backreference, which is explicitly" ]# [ doc = " unsupported in Rust\\\'s regex engine. However, many users expect it to" ]# [ doc = " be supported. Therefore, when octal support is disabled, the error" ]# [ doc = " message will explicitly mention that backreferences aren\\\'t supported." ]# [ doc = "" ]# [ doc = " Octal syntax is disabled by default." ] pub fn octal (& mut self , yes : bool )-> & mut RegexSetBuilder { self . 0 . octal = yes ; self }# [ doc = " Set the approximate size limit of the compiled regular expression." ]# [ doc = "" ]# [ doc = " This roughly corresponds to the number of bytes occupied by a single" ]# [ doc = " compiled program. If the program exceeds this number, then a" ]# [ doc = " compilation error is returned." ] pub fn size_limit (& mut self , limit : usize , )-> & mut RegexSetBuilder { self . 0 . size_limit = limit ; self }# [ doc = " Set the approximate size of the cache used by the DFA." ]# [ doc = "" ]# [ doc = " This roughly corresponds to the number of bytes that the DFA will" ]# [ doc = " use while searching." ]# [ doc = "" ]# [ doc = " Note that this is a *per thread* limit. There is no way to set a global" ]# [ doc = " limit. In particular, if a regex is used from multiple threads" ]# [ doc = " simultaneously, then each thread may use up to the number of bytes" ]# [ doc = " specified here." ] pub fn dfa_size_limit (& mut self , limit : usize , )-> & mut RegexSetBuilder { self . 0 . dfa_size_limit = limit ; self }# [ doc = " Set the nesting limit for this parser." ]# [ doc = "" ]# [ doc = " The nesting limit controls how deep the abstract syntax tree is allowed" ]# [ doc = " to be. If the AST exceeds the given limit (e.g., with too many nested" ]# [ doc = " groups), then an error is returned by the parser." ]# [ doc = "" ]# [ doc = " The purpose of this limit is to act as a heuristic to prevent stack" ]# [ doc = " overflow for consumers that do structural induction on an `Ast` using" ]# [ doc = " explicit recursion. While this crate never does this (instead using" ]# [ doc = " constant stack space and moving the call stack to the heap), other" ]# [ doc = " crates may." ]# [ doc = "" ]# [ doc = " This limit is not checked until the entire Ast is parsed. Therefore," ]# [ doc = " if callers want to put a limit on the amount of heap space used, then" ]# [ doc = " they should impose a limit on the length, in bytes, of the concrete" ]# [ doc = " pattern string. In particular, this is viable since this parser" ]# [ doc = " implementation will limit itself to heap space proportional to the" ]# [ doc = " length of the pattern string." ]# [ doc = "" ]# [ doc = " Note that a nest limit of `0` will return a nest limit error for most" ]# [ doc = " patterns but not all. For example, a nest limit of `0` permits `a` but" ]# [ doc = " not `ab`, since `ab` requires a concatenation, which results in a nest" ]# [ doc = " depth of `1`. In general, a nest limit is not something that manifests" ]# [ doc = " in an obvious way in the concrete syntax, therefore, it should not be" ]# [ doc = " used in a granular way." ] pub fn nest_limit (& mut self , limit : u32 , )-> & mut RegexSetBuilder { self . 0 . nest_limit = limit ; self }}}}; } +macro_rules! __ra_macro_fixture274 {($name : ident , $builder_mod : ident , $text_ty : ty , $as_bytes : expr , $(# [$doc_regexset_example : meta ])* )=>{ pub mod $name { use std :: fmt ; use std :: iter ; use std :: slice ; use std :: vec ; use error :: Error ; use exec :: Exec ; use re_builder ::$builder_mod :: RegexSetBuilder ; use re_trait :: RegularExpression ; # [ doc = " Match multiple (possibly overlapping) regular expressions in a single scan." ]# [ doc = "" ]# [ doc = " A regex set corresponds to the union of two or more regular expressions." ]# [ doc = " That is, a regex set will match text where at least one of its" ]# [ doc = " constituent regular expressions matches. A regex set as its formulated here" ]# [ doc = " provides a touch more power: it will also report *which* regular" ]# [ doc = " expressions in the set match. Indeed, this is the key difference between" ]# [ doc = " regex sets and a single `Regex` with many alternates, since only one" ]# [ doc = " alternate can match at a time." ]# [ doc = "" ]# [ doc = " For example, consider regular expressions to match email addresses and" ]# [ doc = " domains: `[a-z]+@[a-z]+\\\\.(com|org|net)` and `[a-z]+\\\\.(com|org|net)`. If a" ]# [ doc = " regex set is constructed from those regexes, then searching the text" ]# [ doc = " `foo@example.com` will report both regexes as matching. Of course, one" ]# [ doc = " could accomplish this by compiling each regex on its own and doing two" ]# [ doc = " searches over the text. The key advantage of using a regex set is that it" ]# [ doc = " will report the matching regexes using a *single pass through the text*." ]# [ doc = " If one has hundreds or thousands of regexes to match repeatedly (like a URL" ]# [ doc = " router for a complex web application or a user agent matcher), then a regex" ]# [ doc = " set can realize huge performance gains." ]# [ doc = "" ]# [ doc = " # Example" ]# [ doc = "" ]# [ doc = " This shows how the above two regexes (for matching email addresses and" ]# [ doc = " domains) might work:" ]# [ doc = "" ]$(# [$doc_regexset_example ])* # [ doc = "" ]# [ doc = " Note that it would be possible to adapt the above example to using `Regex`" ]# [ doc = " with an expression like:" ]# [ doc = "" ]# [ doc = " ```ignore" ]# [ doc = " (?P<email>[a-z]+@(?P<email_domain>[a-z]+[.](com|org|net)))|(?P<domain>[a-z]+[.](com|org|net))" ]# [ doc = " ```" ]# [ doc = "" ]# [ doc = " After a match, one could then inspect the capture groups to figure out" ]# [ doc = " which alternates matched. The problem is that it is hard to make this" ]# [ doc = " approach scale when there are many regexes since the overlap between each" ]# [ doc = " alternate isn\\\'t always obvious to reason about." ]# [ doc = "" ]# [ doc = " # Limitations" ]# [ doc = "" ]# [ doc = " Regex sets are limited to answering the following two questions:" ]# [ doc = "" ]# [ doc = " 1. Does any regex in the set match?" ]# [ doc = " 2. If so, which regexes in the set match?" ]# [ doc = "" ]# [ doc = " As with the main `Regex` type, it is cheaper to ask (1) instead of (2)" ]# [ doc = " since the matching engines can stop after the first match is found." ]# [ doc = "" ]# [ doc = " Other features like finding the location of successive matches or their" ]# [ doc = " sub-captures aren\\\'t supported. If you need this functionality, the" ]# [ doc = " recommended approach is to compile each regex in the set independently and" ]# [ doc = " selectively match them based on which regexes in the set matched." ]# [ doc = "" ]# [ doc = " # Performance" ]# [ doc = "" ]# [ doc = " A `RegexSet` has the same performance characteristics as `Regex`. Namely," ]# [ doc = " search takes `O(mn)` time, where `m` is proportional to the size of the" ]# [ doc = " regex set and `n` is proportional to the length of the search text." ]# [ derive ( Clone )] pub struct RegexSet ( Exec ); impl RegexSet {# [ doc = " Create a new regex set with the given regular expressions." ]# [ doc = "" ]# [ doc = " This takes an iterator of `S`, where `S` is something that can produce" ]# [ doc = " a `&str`. If any of the strings in the iterator are not valid regular" ]# [ doc = " expressions, then an error is returned." ]# [ doc = "" ]# [ doc = " # Example" ]# [ doc = "" ]# [ doc = " Create a new regex set from an iterator of strings:" ]# [ doc = "" ]# [ doc = " ```rust" ]# [ doc = " # use regex::RegexSet;" ]# [ doc = " let set = RegexSet::new(&[r\\\"\\\\w+\\\", r\\\"\\\\d+\\\"]).unwrap();" ]# [ doc = " assert!(set.is_match(\\\"foo\\\"));" ]# [ doc = " ```" ] pub fn new < I , S > ( exprs : I )-> Result < RegexSet , Error > where S : AsRef < str >, I : IntoIterator < Item = S >{ RegexSetBuilder :: new ( exprs ). build ()}# [ doc = " Create a new empty regex set." ]# [ doc = "" ]# [ doc = " # Example" ]# [ doc = "" ]# [ doc = " ```rust" ]# [ doc = " # use regex::RegexSet;" ]# [ doc = " let set = RegexSet::empty();" ]# [ doc = " assert!(set.is_empty());" ]# [ doc = " ```" ] pub fn empty ()-> RegexSet { RegexSetBuilder :: new (& [ "" ; 0 ]). build (). unwrap ()}# [ doc = " Returns true if and only if one of the regexes in this set matches" ]# [ doc = " the text given." ]# [ doc = "" ]# [ doc = " This method should be preferred if you only need to test whether any" ]# [ doc = " of the regexes in the set should match, but don\\\'t care about *which*" ]# [ doc = " regexes matched. This is because the underlying matching engine will" ]# [ doc = " quit immediately after seeing the first match instead of continuing to" ]# [ doc = " find all matches." ]# [ doc = "" ]# [ doc = " Note that as with searches using `Regex`, the expression is unanchored" ]# [ doc = " by default. That is, if the regex does not start with `^` or `\\\\A`, or" ]# [ doc = " end with `$` or `\\\\z`, then it is permitted to match anywhere in the" ]# [ doc = " text." ]# [ doc = "" ]# [ doc = " # Example" ]# [ doc = "" ]# [ doc = " Tests whether a set matches some text:" ]# [ doc = "" ]# [ doc = " ```rust" ]# [ doc = " # use regex::RegexSet;" ]# [ doc = " let set = RegexSet::new(&[r\\\"\\\\w+\\\", r\\\"\\\\d+\\\"]).unwrap();" ]# [ doc = " assert!(set.is_match(\\\"foo\\\"));" ]# [ doc = " assert!(!set.is_match(\\\"\\u{2603}\\\"));" ]# [ doc = " ```" ] pub fn is_match (& self , text : $text_ty )-> bool { self . is_match_at ( text , 0 )}# [ doc = " Returns the same as is_match, but starts the search at the given" ]# [ doc = " offset." ]# [ doc = "" ]# [ doc = " The significance of the starting point is that it takes the surrounding" ]# [ doc = " context into consideration. For example, the `\\\\A` anchor can only" ]# [ doc = " match when `start == 0`." ]# [ doc ( hidden )] pub fn is_match_at (& self , text : $text_ty , start : usize )-> bool { self . 0 . searcher (). is_match_at ($as_bytes ( text ), start )}# [ doc = " Returns the set of regular expressions that match in the given text." ]# [ doc = "" ]# [ doc = " The set returned contains the index of each regular expression that" ]# [ doc = " matches in the given text. The index is in correspondence with the" ]# [ doc = " order of regular expressions given to `RegexSet`\\\'s constructor." ]# [ doc = "" ]# [ doc = " The set can also be used to iterate over the matched indices." ]# [ doc = "" ]# [ doc = " Note that as with searches using `Regex`, the expression is unanchored" ]# [ doc = " by default. That is, if the regex does not start with `^` or `\\\\A`, or" ]# [ doc = " end with `$` or `\\\\z`, then it is permitted to match anywhere in the" ]# [ doc = " text." ]# [ doc = "" ]# [ doc = " # Example" ]# [ doc = "" ]# [ doc = " Tests which regular expressions match the given text:" ]# [ doc = "" ]# [ doc = " ```rust" ]# [ doc = " # use regex::RegexSet;" ]# [ doc = " let set = RegexSet::new(&[" ]# [ doc = " r\\\"\\\\w+\\\"," ]# [ doc = " r\\\"\\\\d+\\\"," ]# [ doc = " r\\\"\\\\pL+\\\"," ]# [ doc = " r\\\"foo\\\"," ]# [ doc = " r\\\"bar\\\"," ]# [ doc = " r\\\"barfoo\\\"," ]# [ doc = " r\\\"foobar\\\"," ]# [ doc = " ]).unwrap();" ]# [ doc = " let matches: Vec<_> = set.matches(\\\"foobar\\\").into_iter().collect();" ]# [ doc = " assert_eq!(matches, vec![0, 2, 3, 4, 6]);" ]# [ doc = "" ]# [ doc = " // You can also test whether a particular regex matched:" ]# [ doc = " let matches = set.matches(\\\"foobar\\\");" ]# [ doc = " assert!(!matches.matched(5));" ]# [ doc = " assert!(matches.matched(6));" ]# [ doc = " ```" ] pub fn matches (& self , text : $text_ty )-> SetMatches { let mut matches = vec ! [ false ; self . 0 . regex_strings (). len ()]; let any = self . read_matches_at (& mut matches , text , 0 ); SetMatches { matched_any : any , matches : matches , }}# [ doc = " Returns the same as matches, but starts the search at the given" ]# [ doc = " offset and stores the matches into the slice given." ]# [ doc = "" ]# [ doc = " The significance of the starting point is that it takes the surrounding" ]# [ doc = " context into consideration. For example, the `\\\\A` anchor can only" ]# [ doc = " match when `start == 0`." ]# [ doc = "" ]# [ doc = " `matches` must have a length that is at least the number of regexes" ]# [ doc = " in this set." ]# [ doc = "" ]# [ doc = " This method returns true if and only if at least one member of" ]# [ doc = " `matches` is true after executing the set against `text`." ]# [ doc ( hidden )] pub fn read_matches_at (& self , matches : & mut [ bool ], text : $text_ty , start : usize , )-> bool { self . 0 . searcher (). many_matches_at ( matches , $as_bytes ( text ), start )}# [ doc = " Returns the total number of regular expressions in this set." ] pub fn len (& self )-> usize { self . 0 . regex_strings (). len ()}# [ doc = " Returns `true` if this set contains no regular expressions." ] pub fn is_empty (& self )-> bool { self . 0 . regex_strings (). is_empty ()}# [ doc = " Returns the patterns that this set will match on." ]# [ doc = "" ]# [ doc = " This function can be used to determine the pattern for a match. The" ]# [ doc = " slice returned has exactly as many patterns givens to this regex set," ]# [ doc = " and the order of the slice is the same as the order of the patterns" ]# [ doc = " provided to the set." ]# [ doc = "" ]# [ doc = " # Example" ]# [ doc = "" ]# [ doc = " ```rust" ]# [ doc = " # use regex::RegexSet;" ]# [ doc = " let set = RegexSet::new(&[" ]# [ doc = " r\\\"\\\\w+\\\"," ]# [ doc = " r\\\"\\\\d+\\\"," ]# [ doc = " r\\\"\\\\pL+\\\"," ]# [ doc = " r\\\"foo\\\"," ]# [ doc = " r\\\"bar\\\"," ]# [ doc = " r\\\"barfoo\\\"," ]# [ doc = " r\\\"foobar\\\"," ]# [ doc = " ]).unwrap();" ]# [ doc = " let matches: Vec<_> = set" ]# [ doc = " .matches(\\\"foobar\\\")" ]# [ doc = " .into_iter()" ]# [ doc = " .map(|match_idx| &set.patterns()[match_idx])" ]# [ doc = " .collect();" ]# [ doc = " assert_eq!(matches, vec![r\\\"\\\\w+\\\", r\\\"\\\\pL+\\\", r\\\"foo\\\", r\\\"bar\\\", r\\\"foobar\\\"]);" ]# [ doc = " ```" ] pub fn patterns (& self )-> & [ String ]{ self . 0 . regex_strings ()}}# [ doc = " A set of matches returned by a regex set." ]# [ derive ( Clone , Debug )] pub struct SetMatches { matched_any : bool , matches : Vec < bool >, } impl SetMatches {# [ doc = " Whether this set contains any matches." ] pub fn matched_any (& self )-> bool { self . matched_any }# [ doc = " Whether the regex at the given index matched." ]# [ doc = "" ]# [ doc = " The index for a regex is determined by its insertion order upon the" ]# [ doc = " initial construction of a `RegexSet`, starting at `0`." ]# [ doc = "" ]# [ doc = " # Panics" ]# [ doc = "" ]# [ doc = " If `regex_index` is greater than or equal to `self.len()`." ] pub fn matched (& self , regex_index : usize )-> bool { self . matches [ regex_index ]}# [ doc = " The total number of regexes in the set that created these matches." ] pub fn len (& self )-> usize { self . matches . len ()}# [ doc = " Returns an iterator over indexes in the regex that matched." ]# [ doc = "" ]# [ doc = " This will always produces matches in ascending order of index, where" ]# [ doc = " the index corresponds to the index of the regex that matched with" ]# [ doc = " respect to its position when initially building the set." ] pub fn iter (& self )-> SetMatchesIter { SetMatchesIter ((&* self . matches ). into_iter (). enumerate ())}} impl IntoIterator for SetMatches { type IntoIter = SetMatchesIntoIter ; type Item = usize ; fn into_iter ( self )-> Self :: IntoIter { SetMatchesIntoIter ( self . matches . into_iter (). enumerate ())}} impl < 'a > IntoIterator for & 'a SetMatches { type IntoIter = SetMatchesIter < 'a >; type Item = usize ; fn into_iter ( self )-> Self :: IntoIter { self . iter ()}}# [ doc = " An owned iterator over the set of matches from a regex set." ]# [ doc = "" ]# [ doc = " This will always produces matches in ascending order of index, where the" ]# [ doc = " index corresponds to the index of the regex that matched with respect to" ]# [ doc = " its position when initially building the set." ]# [ derive ( Debug )] pub struct SetMatchesIntoIter ( iter :: Enumerate < vec :: IntoIter < bool >>); impl Iterator for SetMatchesIntoIter { type Item = usize ; fn next (& mut self )-> Option < usize > { loop { match self . 0 . next (){ None => return None , Some ((_, false ))=>{} Some (( i , true ))=> return Some ( i ), }}} fn size_hint (& self )-> ( usize , Option < usize >){ self . 0 . size_hint ()}} impl DoubleEndedIterator for SetMatchesIntoIter { fn next_back (& mut self )-> Option < usize > { loop { match self . 0 . next_back (){ None => return None , Some ((_, false ))=>{} Some (( i , true ))=> return Some ( i ), }}}} impl iter :: FusedIterator for SetMatchesIntoIter {}# [ doc = " A borrowed iterator over the set of matches from a regex set." ]# [ doc = "" ]# [ doc = " The lifetime `\\\'a` refers to the lifetime of a `SetMatches` value." ]# [ doc = "" ]# [ doc = " This will always produces matches in ascending order of index, where the" ]# [ doc = " index corresponds to the index of the regex that matched with respect to" ]# [ doc = " its position when initially building the set." ]# [ derive ( Clone , Debug )] pub struct SetMatchesIter < 'a > ( iter :: Enumerate < slice :: Iter < 'a , bool >>); impl < 'a > Iterator for SetMatchesIter < 'a > { type Item = usize ; fn next (& mut self )-> Option < usize > { loop { match self . 0 . next (){ None => return None , Some ((_, & false ))=>{} Some (( i , & true ))=> return Some ( i ), }}} fn size_hint (& self )-> ( usize , Option < usize >){ self . 0 . size_hint ()}} impl < 'a > DoubleEndedIterator for SetMatchesIter < 'a > { fn next_back (& mut self )-> Option < usize > { loop { match self . 0 . next_back (){ None => return None , Some ((_, & false ))=>{} Some (( i , & true ))=> return Some ( i ), }}}} impl < 'a > iter :: FusedIterator for SetMatchesIter < 'a > {}# [ doc ( hidden )] impl From < Exec > for RegexSet { fn from ( exec : Exec )-> Self { RegexSet ( exec )}} impl fmt :: Debug for RegexSet { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { write ! ( f , "RegexSet({:?})" , self . 0 . regex_strings ())}}# [ allow ( dead_code )] fn as_bytes_str ( text : & str )-> & [ u8 ]{ text . as_bytes ()}# [ allow ( dead_code )] fn as_bytes_bytes ( text : & [ u8 ])-> & [ u8 ]{ text }}}} +macro_rules! __ra_macro_fixture275 {($($max_len : expr =>$t : ident ),* as $conv_fn : ident )=>{$(impl_IntegerCommon ! ($max_len , $t ); impl IntegerPrivate < [ u8 ; $max_len ]> for $t {# [ allow ( unused_comparisons )]# [ inline ] fn write_to ( self , buf : & mut [ u8 ; $max_len ])-> & [ u8 ]{ let is_nonnegative = self >= 0 ; let mut n = if is_nonnegative { self as $conv_fn } else {(! ( self as $conv_fn )). wrapping_add ( 1 )}; let mut curr = buf . len () as isize ; let buf_ptr = buf . as_mut_ptr (); let lut_ptr = DEC_DIGITS_LUT . as_ptr (); unsafe { if mem :: size_of ::<$t > ()>= 2 { while n >= 10000 { let rem = ( n % 10000 ) as isize ; n /= 10000 ; let d1 = ( rem / 100 )<< 1 ; let d2 = ( rem % 100 )<< 1 ; curr -= 4 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); ptr :: copy_nonoverlapping ( lut_ptr . offset ( d2 ), buf_ptr . offset ( curr + 2 ), 2 ); }} let mut n = n as isize ; if n >= 100 { let d1 = ( n % 100 )<< 1 ; n /= 100 ; curr -= 2 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); } if n < 10 { curr -= 1 ; * buf_ptr . offset ( curr )= ( n as u8 )+ b'0' ; } else { let d1 = n << 1 ; curr -= 2 ; ptr :: copy_nonoverlapping ( lut_ptr . offset ( d1 ), buf_ptr . offset ( curr ), 2 ); } if ! is_nonnegative { curr -= 1 ; * buf_ptr . offset ( curr )= b'-' ; }} let len = buf . len ()- curr as usize ; unsafe { slice :: from_raw_parts ( buf_ptr . offset ( curr ), len )}}})*}; } +macro_rules! __ra_macro_fixture276 {($max_len : expr , $t : ident )=>{ impl Integer for $t {# [ inline ] fn write ( self , buf : & mut Buffer )-> & str { unsafe { debug_assert ! ($max_len <= I128_MAX_LEN ); let buf = mem :: transmute ::<& mut [ u8 ; I128_MAX_LEN ], & mut [ u8 ; $max_len ]> (& mut buf . bytes , ); let bytes = self . write_to ( buf ); str :: from_utf8_unchecked ( bytes )}}} impl private :: Sealed for $t {}}; } +macro_rules! __ra_macro_fixture277 {(($name : ident $($generics : tt )*)=>$item : ty )=>{ impl $($generics )* Iterator for $name $($generics )* { type Item = $item ; # [ inline ] fn next (& mut self )-> Option < Self :: Item > { self . iter . next ()}# [ inline ] fn size_hint (& self )-> ( usize , Option < usize >){ self . iter . size_hint ()}} impl $($generics )* DoubleEndedIterator for $name $($generics )* {# [ inline ] fn next_back (& mut self )-> Option < Self :: Item > { self . iter . next_back ()}} impl $($generics )* ExactSizeIterator for $name $($generics )* {# [ inline ] fn len (& self )-> usize { self . iter . len ()}} impl $($generics )* FusedIterator for $name $($generics )* {}}} +macro_rules! __ra_macro_fixture278 {($($ty : ident )*)=>{$(impl From <$ty > for Value { fn from ( n : $ty )-> Self { Value :: Number ( n . into ())}})* }; } +macro_rules! __ra_macro_fixture279 {($($eq : ident [$($ty : ty )*])*)=>{$($(impl PartialEq <$ty > for Value { fn eq (& self , other : &$ty )-> bool {$eq ( self , * other as _)}} impl PartialEq < Value > for $ty { fn eq (& self , other : & Value )-> bool {$eq ( other , * self as _)}} impl < 'a > PartialEq <$ty > for & 'a Value { fn eq (& self , other : &$ty )-> bool {$eq (* self , * other as _)}} impl < 'a > PartialEq <$ty > for & 'a mut Value { fn eq (& self , other : &$ty )-> bool {$eq (* self , * other as _)}})*)* }} +macro_rules! __ra_macro_fixture280 {($($ty : ty ),* )=>{$(impl From <$ty > for Number {# [ inline ] fn from ( u : $ty )-> Self { let n = {# [ cfg ( not ( feature = "arbitrary_precision" ))]{ N :: PosInt ( u as u64 )}# [ cfg ( feature = "arbitrary_precision" )]{ itoa :: Buffer :: new (). format ( u ). to_owned ()}}; Number { n }}})* }; } +macro_rules! __ra_macro_fixture281 {($($ty : ty ),* )=>{$(impl From <$ty > for Number {# [ inline ] fn from ( i : $ty )-> Self { let n = {# [ cfg ( not ( feature = "arbitrary_precision" ))]{ if i < 0 { N :: NegInt ( i as i64 )} else { N :: PosInt ( i as u64 )}}# [ cfg ( feature = "arbitrary_precision" )]{ itoa :: Buffer :: new (). format ( i ). to_owned ()}}; Number { n }}})* }; } +macro_rules! __ra_macro_fixture282 (($($size : expr ),+)=>{$(unsafe impl < T > Array for [ T ; $size ]{ type Item = T ; fn size ()-> usize {$size }})+ }); +macro_rules! __ra_macro_fixture283 {($($name : ident ( repeats : $repeats : expr , latches : $latches : expr , delay : $delay : expr , threads : $threads : expr , single_unparks : $single_unparks : expr ); )* )=>{$(# [ test ] fn $name (){ let delay = Duration :: from_micros ($delay ); for _ in 0 ..$repeats { run_parking_test ($latches , delay , $threads , $single_unparks ); }})* }; } +macro_rules! __ra_macro_fixture284 {($C : ident $P : ident ; $A : ident , $($I : ident ),* ; $($X : ident )*)=>(# [ derive ( Clone , Debug )] pub struct $C < I : Iterator > { item : Option < I :: Item >, iter : I , c : $P < I >, } impl < I : Iterator + Clone > From < I > for $C < I > { fn from ( mut iter : I )-> Self {$C { item : iter . next (), iter : iter . clone (), c : $P :: from ( iter ), }}} impl < I : Iterator + Clone > From < I > for $C < Fuse < I >> { fn from ( iter : I )-> Self { let mut iter = iter . fuse (); $C { item : iter . next (), iter : iter . clone (), c : $P :: from ( iter ), }}} impl < I , $A > Iterator for $C < I > where I : Iterator < Item = $A > + Clone , I :: Item : Clone { type Item = ($($I ),*); fn next (& mut self )-> Option < Self :: Item > { if let Some (($($X ),*,))= self . c . next (){ let z = self . item . clone (). unwrap (); Some (( z , $($X ),*))} else { self . item = self . iter . next (); self . item . clone (). and_then (| z | { self . c = $P :: from ( self . iter . clone ()); self . c . next (). map (| ($($X ),*,)| ( z , $($X ),*))})}}} impl < I , $A > HasCombination < I > for ($($I ),*) where I : Iterator < Item = $A > + Clone , I :: Item : Clone { type Combination = $C < Fuse < I >>; })} +macro_rules! __ra_macro_fixture285 (($_A : ident , $_B : ident , )=>(); ($A : ident , $($B : ident ,)*)=>( impl_cons_iter ! ($($B ,)*); # [ allow ( non_snake_case )] impl < X , Iter , $($B ),*> Iterator for ConsTuples < Iter , (($($B ,)*), X )> where Iter : Iterator < Item = (($($B ,)*), X )>, { type Item = ($($B ,)* X , ); fn next (& mut self )-> Option < Self :: Item > { self . iter . next (). map (| (($($B ,)*), x )| ($($B ,)* x , ))} fn size_hint (& self )-> ( usize , Option < usize >){ self . iter . size_hint ()} fn fold < Acc , Fold > ( self , accum : Acc , mut f : Fold )-> Acc where Fold : FnMut ( Acc , Self :: Item )-> Acc , { self . iter . fold ( accum , move | acc , (($($B ,)*), x )| f ( acc , ($($B ,)* x , )))}}# [ allow ( non_snake_case )] impl < X , Iter , $($B ),*> DoubleEndedIterator for ConsTuples < Iter , (($($B ,)*), X )> where Iter : DoubleEndedIterator < Item = (($($B ,)*), X )>, { fn next_back (& mut self )-> Option < Self :: Item > { self . iter . next (). map (| (($($B ,)*), x )| ($($B ,)* x , ))}}); ); +macro_rules! __ra_macro_fixture286 {($($fmt_trait : ident )*)=>{$(impl < 'a , I > fmt ::$fmt_trait for Format < 'a , I > where I : Iterator , I :: Item : fmt ::$fmt_trait , { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { self . format ( f , fmt ::$fmt_trait :: fmt )}})* }} +macro_rules! __ra_macro_fixture287 {([$($typarm : tt )*]$type_ : ty )=>{ impl <$($typarm )*> PeekingNext for $type_ { fn peeking_next < F > (& mut self , accept : F )-> Option < Self :: Item > where F : FnOnce (& Self :: Item )-> bool { let saved_state = self . clone (); if let Some ( r )= self . next (){ if ! accept (& r ){* self = saved_state ; } else { return Some ( r )}} None }}}} +macro_rules! __ra_macro_fixture288 {()=>(); ($N : expr ; $A : ident ; $($X : ident ),* ; $($Y : ident ),* ; $($Y_rev : ident ),*)=>( impl <$A > TupleCollect for ($($X ),*,){ type Item = $A ; type Buffer = [ Option <$A >; $N - 1 ]; # [ allow ( unused_assignments , unused_mut )] fn collect_from_iter < I > ( iter : I , buf : & mut Self :: Buffer )-> Option < Self > where I : IntoIterator < Item = $A > { let mut iter = iter . into_iter (); $(let mut $Y = None ; )* loop {$($Y = iter . next (); if $Y . is_none (){ break })* return Some (($($Y . unwrap ()),*,))} let mut i = 0 ; let mut s = buf . as_mut (); $(if i < s . len (){ s [ i ]= $Y ; i += 1 ; })* return None ; }# [ allow ( unused_assignments )] fn collect_from_iter_no_buf < I > ( iter : I )-> Option < Self > where I : IntoIterator < Item = $A > { let mut iter = iter . into_iter (); loop {$(let $Y = if let Some ($Y )= iter . next (){$Y } else { break ; }; )* return Some (($($Y ),*,))} return None ; } fn num_items ()-> usize {$N } fn left_shift_push (& mut self , item : $A ){ use std :: mem :: replace ; let & mut ($(ref mut $Y ),*,)= self ; let tmp = item ; $(let tmp = replace ($Y_rev , tmp ); )* drop ( tmp ); }})} +macro_rules! __ra_macro_fixture289 {($($B : ident ),*)=>(# [ allow ( non_snake_case )] impl <$($B : IntoIterator ),*> From < ($($B ,)*)> for Zip < ($($B :: IntoIter ,)*)> { fn from ( t : ($($B ,)*))-> Self { let ($($B ,)*)= t ; Zip { t : ($($B . into_iter (),)*)}}}# [ allow ( non_snake_case )]# [ allow ( unused_assignments )] impl <$($B ),*> Iterator for Zip < ($($B ,)*)> where $($B : Iterator , )* { type Item = ($($B :: Item ,)*); fn next (& mut self )-> Option < Self :: Item > { let ($(ref mut $B ,)*)= self . t ; $(let $B = match $B . next (){ None => return None , Some ( elt )=> elt }; )* Some (($($B ,)*))} fn size_hint (& self )-> ( usize , Option < usize >){ let sh = (:: std :: usize :: MAX , None ); let ($(ref $B ,)*)= self . t ; $(let sh = size_hint :: min ($B . size_hint (), sh ); )* sh }}# [ allow ( non_snake_case )] impl <$($B ),*> ExactSizeIterator for Zip < ($($B ,)*)> where $($B : ExactSizeIterator , )* {}); } +macro_rules! __ra_macro_fixture290 {( impl $Op : ident for TextRange by fn $f : ident = $op : tt )=>{ impl $Op <& TextSize > for TextRange { type Output = TextRange ; # [ inline ] fn $f ( self , other : & TextSize )-> TextRange { self $op * other }} impl < T > $Op < T > for & TextRange where TextRange : $Op < T , Output = TextRange >, { type Output = TextRange ; # [ inline ] fn $f ( self , other : T )-> TextRange {* self $op other }}}; } +macro_rules! __ra_macro_fixture291 {( impl $Op : ident for TextSize by fn $f : ident = $op : tt )=>{ impl $Op < TextSize > for TextSize { type Output = TextSize ; # [ inline ] fn $f ( self , other : TextSize )-> TextSize { TextSize { raw : self . raw $op other . raw }}} impl $Op <& TextSize > for TextSize { type Output = TextSize ; # [ inline ] fn $f ( self , other : & TextSize )-> TextSize { self $op * other }} impl < T > $Op < T > for & TextSize where TextSize : $Op < T , Output = TextSize >, { type Output = TextSize ; # [ inline ] fn $f ( self , other : T )-> TextSize {* self $op other }}}; } +macro_rules! __ra_macro_fixture292 {($expr : expr )=>{ const _: i32 = 0 / $expr as i32 ; }; } +macro_rules! __ra_macro_fixture293 {($index_type : ty , )=>(); ($index_type : ty , $($len : expr ,)*)=>($(fix_array_impl ! ($index_type , $len );)* ); } +macro_rules! __ra_macro_fixture294 {($index_type : ty , $len : expr )=>( unsafe impl < T > Array for [ T ; $len ]{ type Item = T ; type Index = $index_type ; const CAPACITY : usize = $len ; # [ doc ( hidden )] fn as_slice (& self )-> & [ Self :: Item ]{ self }# [ doc ( hidden )] fn as_mut_slice (& mut self )-> & mut [ Self :: Item ]{ self }})} +macro_rules! __ra_macro_fixture295 {($($variant : ident $(($($sub_variant : ident ),*))?),* for $enum : ident )=>{$(impl From <$variant > for $enum { fn from ( it : $variant )-> $enum {$enum ::$variant ( it )}}$($(impl From <$sub_variant > for $enum { fn from ( it : $sub_variant )-> $enum {$enum ::$variant ($variant ::$sub_variant ( it ))}})*)? )* }} +macro_rules! __ra_macro_fixture296 {($name : ident )=>{ impl $name { pub ( crate ) fn expand_tt (& self , invocation : & str )-> tt :: Subtree { self . try_expand_tt ( invocation ). unwrap ()} fn try_expand_tt (& self , invocation : & str )-> Result < tt :: Subtree , ExpandError > { let source_file = ast :: SourceFile :: parse ( invocation ). tree (); let macro_invocation = source_file . syntax (). descendants (). find_map ( ast :: MacroCall :: cast ). unwrap (); let ( invocation_tt , _)= ast_to_token_tree (& macro_invocation . token_tree (). unwrap ()). ok_or_else (|| ExpandError :: ConversionError )?; self . rules . expand (& invocation_tt ). result ()}# [ allow ( unused )] fn assert_expand_err (& self , invocation : & str , err : & ExpandError ){ assert_eq ! ( self . try_expand_tt ( invocation ). as_ref (), Err ( err )); }# [ allow ( unused )] fn expand_items (& self , invocation : & str )-> SyntaxNode { let expanded = self . expand_tt ( invocation ); token_tree_to_syntax_node (& expanded , FragmentKind :: Items ). unwrap (). 0 . syntax_node ()}# [ allow ( unused )] fn expand_statements (& self , invocation : & str )-> SyntaxNode { let expanded = self . expand_tt ( invocation ); token_tree_to_syntax_node (& expanded , FragmentKind :: Statements ). unwrap (). 0 . syntax_node ()}# [ allow ( unused )] fn expand_expr (& self , invocation : & str )-> SyntaxNode { let expanded = self . expand_tt ( invocation ); token_tree_to_syntax_node (& expanded , FragmentKind :: Expr ). unwrap (). 0 . syntax_node ()}# [ allow ( unused )] fn assert_expand_tt (& self , invocation : & str , expected : & str ){ let expansion = self . expand_tt ( invocation ); assert_eq ! ( expansion . to_string (), expected ); }# [ allow ( unused )] fn assert_expand (& self , invocation : & str , expected : & str ){ let expansion = self . expand_tt ( invocation ); let actual = format ! ( "{:?}" , expansion ); test_utils :: assert_eq_text ! (& expected . trim (), & actual . trim ()); } fn assert_expand_items (& self , invocation : & str , expected : & str )-> &$name { self . assert_expansion ( FragmentKind :: Items , invocation , expected ); self }# [ allow ( unused )] fn assert_expand_statements (& self , invocation : & str , expected : & str )-> &$name { self . assert_expansion ( FragmentKind :: Statements , invocation , expected ); self } fn assert_expansion (& self , kind : FragmentKind , invocation : & str , expected : & str ){ let expanded = self . expand_tt ( invocation ); assert_eq ! ( expanded . to_string (), expected ); let expected = expected . replace ( "$crate" , "C_C__C" ); let expected = { let wrapped = format ! ( "wrap_macro!( {} )" , expected ); let wrapped = ast :: SourceFile :: parse (& wrapped ); let wrapped = wrapped . tree (). syntax (). descendants (). find_map ( ast :: TokenTree :: cast ). unwrap (); let mut wrapped = ast_to_token_tree (& wrapped ). unwrap (). 0 ; wrapped . delimiter = None ; wrapped }; let expanded_tree = token_tree_to_syntax_node (& expanded , kind ). unwrap (). 0 . syntax_node (); let expanded_tree = debug_dump_ignore_spaces (& expanded_tree ). trim (). to_string (); let expected_tree = token_tree_to_syntax_node (& expected , kind ). unwrap (). 0 . syntax_node (); let expected_tree = debug_dump_ignore_spaces (& expected_tree ). trim (). to_string (); let expected_tree = expected_tree . replace ( "C_C__C" , "$crate" ); assert_eq ! ( expanded_tree , expected_tree , "\nleft:\n{}\nright:\n{}" , expanded_tree , expected_tree , ); }}}; } +macro_rules! __ra_macro_fixture297 {($($name : ident ( num_producers : $num_producers : expr , num_consumers : $num_consumers : expr , max_queue_size : $max_queue_size : expr , messages_per_producer : $messages_per_producer : expr , notification_style : $notification_style : expr , timeout : $timeout : expr , delay_seconds : $delay_seconds : expr ); )* )=>{$(# [ test ] fn $name (){ let delay = Duration :: from_secs ($delay_seconds ); run_queue_test ($num_producers , $num_consumers , $max_queue_size , $messages_per_producer , $notification_style , $timeout , delay , ); })* }; } +macro_rules! __ra_macro_fixture298 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_camel_case (), $s2 )}}} +macro_rules! __ra_macro_fixture299 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_kebab_case (), $s2 )}}} +macro_rules! __ra_macro_fixture300 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_mixed_case (), $s2 )}}} +macro_rules! __ra_macro_fixture301 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_shouty_kebab_case (), $s2 )}}} +macro_rules! __ra_macro_fixture302 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_shouty_snake_case (), $s2 )}}} +macro_rules! __ra_macro_fixture303 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_snake_case (), $s2 )}}} +macro_rules! __ra_macro_fixture304 {($t : ident : $s1 : expr =>$s2 : expr )=>{# [ test ] fn $t (){ assert_eq ! ($s1 . to_title_case (), $s2 )}}} +macro_rules! __ra_macro_fixture305 {($($struct_name : ident ),+ $(,)?)=>{$(unsafe impl < E : Endian > Pod for $struct_name < E > {})+ }} +macro_rules! __ra_macro_fixture306 {($($struct_name : ident ),+ $(,)?)=>{$(unsafe impl Pod for $struct_name {})+ }} +macro_rules! __ra_macro_fixture307 {($name : ident , {$($in : tt )* })=>{# [ test ] fn $name (){ syn :: parse_file ( stringify ! ($($in )*)). unwrap (); }}} +macro_rules! __ra_macro_fixture308 {($name : ident , $op : ident )=>{ fn $name ( sets : Vec < Vec <& str >>)-> Vec < String > { let fsts : Vec < Fst <_>> = sets . into_iter (). map ( fst_set ). collect (); let op : OpBuilder = fsts . iter (). collect (); let mut stream = op .$op (). into_stream (); let mut keys = vec ! []; while let Some (( key , _))= stream . next (){ keys . push ( String :: from_utf8 ( key . to_vec ()). unwrap ()); } keys }}; } +macro_rules! __ra_macro_fixture309 {($name : ident , $op : ident )=>{ fn $name ( sets : Vec < Vec < (& str , u64 )>>)-> Vec < ( String , u64 )> { let fsts : Vec < Fst <_>> = sets . into_iter (). map ( fst_map ). collect (); let op : OpBuilder = fsts . iter (). collect (); let mut stream = op .$op (). into_stream (); let mut keys = vec ! []; while let Some (( key , outs ))= stream . next (){ let merged = outs . iter (). fold ( 0 , | a , b | a + b . value ); let s = String :: from_utf8 ( key . to_vec ()). unwrap (); keys . push (( s , merged )); } keys }}; } +macro_rules! __ra_macro_fixture310 {($name : ident , $($s : expr ),+)=>{# [ test ] fn $name (){ let mut items = vec ! [$($s ),*]; let fst = fst_set (& items ); let mut rdr = fst . stream (); items . sort (); items . dedup (); for item in & items { assert_eq ! ( rdr . next (). unwrap (). 0 , item . as_bytes ()); } assert_eq ! ( rdr . next (), None ); for item in & items { assert ! ( fst . get ( item ). is_some ()); }}}} +macro_rules! __ra_macro_fixture311 {($name : ident , $($s : expr ),+)=>{# [ test ]# [ should_panic ] fn $name (){ let mut bfst = Builder :: memory (); $(bfst . add ($s ). unwrap ();)* }}} +macro_rules! __ra_macro_fixture312 {($name : ident , $($s : expr , $o : expr ),+)=>{# [ test ] fn $name (){ let fst = fst_map ( vec ! [$(($s , $o )),*]); let mut rdr = fst . stream (); $({let ( s , o )= rdr . next (). unwrap (); assert_eq ! (( s , o . value ()), ($s . as_bytes (), $o )); })* assert_eq ! ( rdr . next (), None ); $({assert_eq ! ( fst . get ($s . as_bytes ()), Some ( Output :: new ($o ))); })* }}} +macro_rules! __ra_macro_fixture313 {($name : ident , $($s : expr , $o : expr ),+)=>{# [ test ]# [ should_panic ] fn $name (){ let mut bfst = Builder :: memory (); $(bfst . insert ($s , $o ). unwrap ();)* }}} +macro_rules! __ra_macro_fixture314 {($name : ident , min : $min : expr , max : $max : expr , imin : $imin : expr , imax : $imax : expr , $($s : expr ),* )=>{# [ test ] fn $name (){ let items : Vec <& 'static str > = vec ! [$($s ),*]; let items : Vec <_> = items . into_iter (). enumerate (). map (| ( i , k )| ( k , i as u64 )). collect (); let fst = fst_map ( items . clone ()); let mut rdr = Stream :: new ( fst . as_ref (), AlwaysMatch , $min , $max ); for i in $imin ..$imax { assert_eq ! ( rdr . next (). unwrap (), ( items [ i ]. 0 . as_bytes (), Output :: new ( items [ i ]. 1 )), ); } assert_eq ! ( rdr . next (), None ); }}} +macro_rules! __ra_macro_fixture315 {($ty : ty , $tag : ident )=>{ impl TryFrom < Response > for $ty { type Error = & 'static str ; fn try_from ( value : Response )-> Result < Self , Self :: Error > { match value { Response ::$tag ( res )=> Ok ( res ), _ => Err ( concat ! ( "Failed to convert response to " , stringify ! ($tag ))), }}}}; } +macro_rules! __ra_macro_fixture316 {( CloneAny )=>{# [ doc = " A type to emulate dynamic typing." ]# [ doc = "" ]# [ doc = " Every type with no non-`\\\'static` references implements `Any`." ] define ! ( CloneAny remainder ); }; ( Any )=>{# [ doc = " A type to emulate dynamic typing with cloning." ]# [ doc = "" ]# [ doc = " Every type with no non-`\\\'static` references that implements `Clone` implements `Any`." ] define ! ( Any remainder ); }; ($t : ident remainder )=>{# [ doc = " See the [`std::any` documentation](https://doc.rust-lang.org/std/any/index.html) for" ]# [ doc = " more details on `Any` in general." ]# [ doc = "" ]# [ doc = " This trait is not `std::any::Any` but rather a type extending that for this library\\u{2019}s" ]# [ doc = " purposes so that it can be combined with marker traits like " ]# [ doc = " <code><a class=trait title=core::marker::Send" ]# [ doc = " href=http://doc.rust-lang.org/std/marker/trait.Send.html>Send</a></code> and" ]# [ doc = " <code><a class=trait title=core::marker::Sync" ]# [ doc = " href=http://doc.rust-lang.org/std/marker/trait.Sync.html>Sync</a></code>." ]# [ doc = "" ] define ! ($t trait ); }; ( CloneAny trait )=>{# [ doc = " See also [`Any`](trait.Any.html) for a version without the `Clone` requirement." ] pub trait CloneAny : Any + CloneToAny {} impl < T : StdAny + Clone > CloneAny for T {}}; ( Any trait )=>{# [ doc = " See also [`CloneAny`](trait.CloneAny.html) for a cloneable version of this trait." ] pub trait Any : StdAny {} impl < T : StdAny > Any for T {}}; } +macro_rules! __ra_macro_fixture317 {($base : ident , $(+ $bounds : ident )*)=>{ impl fmt :: Debug for $base $(+ $bounds )* {# [ inline ] fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { f . pad ( stringify ! ($base $(+ $bounds )*))}} impl UncheckedAnyExt for $base $(+ $bounds )* {# [ inline ] unsafe fn downcast_ref_unchecked < T : 'static > (& self )-> & T {&* ( self as * const Self as * const T )}# [ inline ] unsafe fn downcast_mut_unchecked < T : 'static > (& mut self )-> & mut T {& mut * ( self as * mut Self as * mut T )}# [ inline ] unsafe fn downcast_unchecked < T : 'static > ( self : Box < Self >)-> Box < T > { Box :: from_raw ( Box :: into_raw ( self ) as * mut T )}} impl < T : $base $(+ $bounds )*> IntoBox <$base $(+ $bounds )*> for T {# [ inline ] fn into_box ( self )-> Box <$base $(+ $bounds )*> { Box :: new ( self )}}}} +macro_rules! __ra_macro_fixture318 {($t : ty , $method : ident )=>{ impl Clone for Box <$t > {# [ inline ] fn clone (& self )-> Box <$t > {(** self ).$method ()}}}} +macro_rules! __ra_macro_fixture319 {( field : $t : ident .$field : ident ; new ()=>$new : expr ; with_capacity ($with_capacity_arg : ident )=>$with_capacity : expr ; )=>{ impl < A : ? Sized + UncheckedAnyExt > $t < A > {# [ doc = " Create an empty collection." ]# [ inline ] pub fn new ()-> $t < A > {$t {$field : $new , }}# [ doc = " Creates an empty collection with the given initial capacity." ]# [ inline ] pub fn with_capacity ($with_capacity_arg : usize )-> $t < A > {$t {$field : $with_capacity , }}# [ doc = " Returns the number of elements the collection can hold without reallocating." ]# [ inline ] pub fn capacity (& self )-> usize { self .$field . capacity ()}# [ doc = " Reserves capacity for at least `additional` more elements to be inserted" ]# [ doc = " in the collection. The collection may reserve more space to avoid" ]# [ doc = " frequent reallocations." ]# [ doc = "" ]# [ doc = " # Panics" ]# [ doc = "" ]# [ doc = " Panics if the new allocation size overflows `usize`." ]# [ inline ] pub fn reserve (& mut self , additional : usize ){ self .$field . reserve ( additional )}# [ doc = " Shrinks the capacity of the collection as much as possible. It will drop" ]# [ doc = " down as much as possible while maintaining the internal rules" ]# [ doc = " and possibly leaving some space in accordance with the resize policy." ]# [ inline ] pub fn shrink_to_fit (& mut self ){ self .$field . shrink_to_fit ()}# [ doc = " Returns the number of items in the collection." ]# [ inline ] pub fn len (& self )-> usize { self .$field . len ()}# [ doc = " Returns true if there are no items in the collection." ]# [ inline ] pub fn is_empty (& self )-> bool { self .$field . is_empty ()}# [ doc = " Removes all items from the collection. Keeps the allocated memory for reuse." ]# [ inline ] pub fn clear (& mut self ){ self .$field . clear ()}}}} +macro_rules! __ra_macro_fixture320 {($name : ident , $init : ty )=>{# [ test ] fn $name (){ let mut map = <$init >:: new (); assert_eq ! ( map . insert ( A ( 10 )), None ); assert_eq ! ( map . insert ( B ( 20 )), None ); assert_eq ! ( map . insert ( C ( 30 )), None ); assert_eq ! ( map . insert ( D ( 40 )), None ); assert_eq ! ( map . insert ( E ( 50 )), None ); assert_eq ! ( map . insert ( F ( 60 )), None ); match map . entry ::< A > (){ Entry :: Vacant (_)=> unreachable ! (), Entry :: Occupied ( mut view )=>{ assert_eq ! ( view . get (), & A ( 10 )); assert_eq ! ( view . insert ( A ( 100 )), A ( 10 )); }} assert_eq ! ( map . get ::< A > (). unwrap (), & A ( 100 )); assert_eq ! ( map . len (), 6 ); match map . entry ::< B > (){ Entry :: Vacant (_)=> unreachable ! (), Entry :: Occupied ( mut view )=>{ let v = view . get_mut (); let new_v = B ( v . 0 * 10 ); * v = new_v ; }} assert_eq ! ( map . get ::< B > (). unwrap (), & B ( 200 )); assert_eq ! ( map . len (), 6 ); match map . entry ::< C > (){ Entry :: Vacant (_)=> unreachable ! (), Entry :: Occupied ( view )=>{ assert_eq ! ( view . remove (), C ( 30 )); }} assert_eq ! ( map . get ::< C > (), None ); assert_eq ! ( map . len (), 5 ); match map . entry ::< J > (){ Entry :: Occupied (_)=> unreachable ! (), Entry :: Vacant ( view )=>{ assert_eq ! (* view . insert ( J ( 1000 )), J ( 1000 )); }} assert_eq ! ( map . get ::< J > (). unwrap (), & J ( 1000 )); assert_eq ! ( map . len (), 6 ); map . entry ::< B > (). or_insert ( B ( 71 )). 0 += 1 ; assert_eq ! ( map . get ::< B > (). unwrap (), & B ( 201 )); assert_eq ! ( map . len (), 6 ); map . entry ::< C > (). or_insert ( C ( 300 )). 0 += 1 ; assert_eq ! ( map . get ::< C > (). unwrap (), & C ( 301 )); assert_eq ! ( map . len (), 7 ); }}} +macro_rules! __ra_macro_fixture321 {($(# [$outer : meta ])* pub struct $BitFlags : ident : $T : ty {$($(# [$inner : ident $($args : tt )*])* const $Flag : ident = $value : expr ; )+ })=>{ __bitflags ! {$(# [$outer ])* ( pub )$BitFlags : $T {$($(# [$inner $($args )*])* $Flag = $value ; )+ }}}; ($(# [$outer : meta ])* struct $BitFlags : ident : $T : ty {$($(# [$inner : ident $($args : tt )*])* const $Flag : ident = $value : expr ; )+ })=>{ __bitflags ! {$(# [$outer ])* ()$BitFlags : $T {$($(# [$inner $($args )*])* $Flag = $value ; )+ }}}; ($(# [$outer : meta ])* pub ($($vis : tt )+) struct $BitFlags : ident : $T : ty {$($(# [$inner : ident $($args : tt )*])* const $Flag : ident = $value : expr ; )+ })=>{ __bitflags ! {$(# [$outer ])* ( pub ($($vis )+))$BitFlags : $T {$($(# [$inner $($args )*])* $Flag = $value ; )+ }}}; } +macro_rules! __ra_macro_fixture322 {($(# [$outer : meta ])* ($($vis : tt )*)$BitFlags : ident : $T : ty {$($(# [$inner : ident $($args : tt )*])* $Flag : ident = $value : expr ; )+ })=>{$(# [$outer ])* # [ derive ( Copy , PartialEq , Eq , Clone , PartialOrd , Ord , Hash )]$($vis )* struct $BitFlags { bits : $T , } __impl_bitflags ! {$BitFlags : $T {$($(# [$inner $($args )*])* $Flag = $value ; )+ }}}; } +macro_rules! __ra_macro_fixture323 {($BitFlags : ident : $T : ty {$($(# [$attr : ident $($args : tt )*])* $Flag : ident = $value : expr ; )+ })=>{ impl $crate :: _core :: fmt :: Debug for $BitFlags { fn fmt (& self , f : & mut $crate :: _core :: fmt :: Formatter )-> $crate :: _core :: fmt :: Result {# [ allow ( non_snake_case )] trait __BitFlags {$(# [ inline ] fn $Flag (& self )-> bool { false })+ } impl __BitFlags for $BitFlags {$(__impl_bitflags ! {# [ allow ( deprecated )]# [ inline ]$(? # [$attr $($args )*])* fn $Flag (& self )-> bool { if Self ::$Flag . bits == 0 && self . bits != 0 { false } else { self . bits & Self ::$Flag . bits == Self ::$Flag . bits }}})+ } let mut first = true ; $(if <$BitFlags as __BitFlags >::$Flag ( self ){ if ! first { f . write_str ( " | " )?; } first = false ; f . write_str ( __bitflags_stringify ! ($Flag ))?; })+ let extra_bits = self . bits & !$BitFlags :: all (). bits (); if extra_bits != 0 { if ! first { f . write_str ( " | " )?; } first = false ; f . write_str ( "0x" )?; $crate :: _core :: fmt :: LowerHex :: fmt (& extra_bits , f )?; } if first { f . write_str ( "(empty)" )?; } Ok (())}} impl $crate :: _core :: fmt :: Binary for $BitFlags { fn fmt (& self , f : & mut $crate :: _core :: fmt :: Formatter )-> $crate :: _core :: fmt :: Result {$crate :: _core :: fmt :: Binary :: fmt (& self . bits , f )}} impl $crate :: _core :: fmt :: Octal for $BitFlags { fn fmt (& self , f : & mut $crate :: _core :: fmt :: Formatter )-> $crate :: _core :: fmt :: Result {$crate :: _core :: fmt :: Octal :: fmt (& self . bits , f )}} impl $crate :: _core :: fmt :: LowerHex for $BitFlags { fn fmt (& self , f : & mut $crate :: _core :: fmt :: Formatter )-> $crate :: _core :: fmt :: Result {$crate :: _core :: fmt :: LowerHex :: fmt (& self . bits , f )}} impl $crate :: _core :: fmt :: UpperHex for $BitFlags { fn fmt (& self , f : & mut $crate :: _core :: fmt :: Formatter )-> $crate :: _core :: fmt :: Result {$crate :: _core :: fmt :: UpperHex :: fmt (& self . bits , f )}}# [ allow ( dead_code )] impl $BitFlags {$($(# [$attr $($args )*])* pub const $Flag : $BitFlags = $BitFlags { bits : $value }; )+ __fn_bitflags ! {# [ doc = " Returns an empty set of flags" ]# [ inline ] pub const fn empty ()-> $BitFlags {$BitFlags { bits : 0 }}} __fn_bitflags ! {# [ doc = " Returns the set containing all flags." ]# [ inline ] pub const fn all ()-> $BitFlags {# [ allow ( non_snake_case )] trait __BitFlags {$(const $Flag : $T = 0 ; )+ } impl __BitFlags for $BitFlags {$(__impl_bitflags ! {# [ allow ( deprecated )]$(? # [$attr $($args )*])* const $Flag : $T = Self ::$Flag . bits ; })+ }$BitFlags { bits : $(<$BitFlags as __BitFlags >::$Flag )|+ }}} __fn_bitflags ! {# [ doc = " Returns the raw value of the flags currently stored." ]# [ inline ] pub const fn bits (& self )-> $T { self . bits }}# [ doc = " Convert from underlying bit representation, unless that" ]# [ doc = " representation contains bits that do not correspond to a flag." ]# [ inline ] pub fn from_bits ( bits : $T )-> $crate :: _core :: option :: Option <$BitFlags > { if ( bits & !$BitFlags :: all (). bits ())== 0 {$crate :: _core :: option :: Option :: Some ($BitFlags { bits })} else {$crate :: _core :: option :: Option :: None }} __fn_bitflags ! {# [ doc = " Convert from underlying bit representation, dropping any bits" ]# [ doc = " that do not correspond to flags." ]# [ inline ] pub const fn from_bits_truncate ( bits : $T )-> $BitFlags {$BitFlags { bits : bits & $BitFlags :: all (). bits }}} __fn_bitflags ! {# [ doc = " Convert from underlying bit representation, preserving all" ]# [ doc = " bits (even those not corresponding to a defined flag)." ]# [ inline ] pub const unsafe fn from_bits_unchecked ( bits : $T )-> $BitFlags {$BitFlags { bits }}} __fn_bitflags ! {# [ doc = " Returns `true` if no flags are currently stored." ]# [ inline ] pub const fn is_empty (& self )-> bool { self . bits ()== $BitFlags :: empty (). bits ()}} __fn_bitflags ! {# [ doc = " Returns `true` if all flags are currently set." ]# [ inline ] pub const fn is_all (& self )-> bool { self . bits == $BitFlags :: all (). bits }} __fn_bitflags ! {# [ doc = " Returns `true` if there are flags common to both `self` and `other`." ]# [ inline ] pub const fn intersects (& self , other : $BitFlags )-> bool {!$BitFlags { bits : self . bits & other . bits }. is_empty ()}} __fn_bitflags ! {# [ doc = " Returns `true` all of the flags in `other` are contained within `self`." ]# [ inline ] pub const fn contains (& self , other : $BitFlags )-> bool {( self . bits & other . bits )== other . bits }}# [ doc = " Inserts the specified flags in-place." ]# [ inline ] pub fn insert (& mut self , other : $BitFlags ){ self . bits |= other . bits ; }# [ doc = " Removes the specified flags in-place." ]# [ inline ] pub fn remove (& mut self , other : $BitFlags ){ self . bits &= ! other . bits ; }# [ doc = " Toggles the specified flags in-place." ]# [ inline ] pub fn toggle (& mut self , other : $BitFlags ){ self . bits ^= other . bits ; }# [ doc = " Inserts or removes the specified flags depending on the passed value." ]# [ inline ] pub fn set (& mut self , other : $BitFlags , value : bool ){ if value { self . insert ( other ); } else { self . remove ( other ); }}} impl $crate :: _core :: ops :: BitOr for $BitFlags { type Output = $BitFlags ; # [ doc = " Returns the union of the two sets of flags." ]# [ inline ] fn bitor ( self , other : $BitFlags )-> $BitFlags {$BitFlags { bits : self . bits | other . bits }}} impl $crate :: _core :: ops :: BitOrAssign for $BitFlags {# [ doc = " Adds the set of flags." ]# [ inline ] fn bitor_assign (& mut self , other : $BitFlags ){ self . bits |= other . bits ; }} impl $crate :: _core :: ops :: BitXor for $BitFlags { type Output = $BitFlags ; # [ doc = " Returns the left flags, but with all the right flags toggled." ]# [ inline ] fn bitxor ( self , other : $BitFlags )-> $BitFlags {$BitFlags { bits : self . bits ^ other . bits }}} impl $crate :: _core :: ops :: BitXorAssign for $BitFlags {# [ doc = " Toggles the set of flags." ]# [ inline ] fn bitxor_assign (& mut self , other : $BitFlags ){ self . bits ^= other . bits ; }} impl $crate :: _core :: ops :: BitAnd for $BitFlags { type Output = $BitFlags ; # [ doc = " Returns the intersection between the two sets of flags." ]# [ inline ] fn bitand ( self , other : $BitFlags )-> $BitFlags {$BitFlags { bits : self . bits & other . bits }}} impl $crate :: _core :: ops :: BitAndAssign for $BitFlags {# [ doc = " Disables all flags disabled in the set." ]# [ inline ] fn bitand_assign (& mut self , other : $BitFlags ){ self . bits &= other . bits ; }} impl $crate :: _core :: ops :: Sub for $BitFlags { type Output = $BitFlags ; # [ doc = " Returns the set difference of the two sets of flags." ]# [ inline ] fn sub ( self , other : $BitFlags )-> $BitFlags {$BitFlags { bits : self . bits & ! other . bits }}} impl $crate :: _core :: ops :: SubAssign for $BitFlags {# [ doc = " Disables all flags enabled in the set." ]# [ inline ] fn sub_assign (& mut self , other : $BitFlags ){ self . bits &= ! other . bits ; }} impl $crate :: _core :: ops :: Not for $BitFlags { type Output = $BitFlags ; # [ doc = " Returns the complement of this set of flags." ]# [ inline ] fn not ( self )-> $BitFlags {$BitFlags { bits : ! self . bits }& $BitFlags :: all ()}} impl $crate :: _core :: iter :: Extend <$BitFlags > for $BitFlags { fn extend < T : $crate :: _core :: iter :: IntoIterator < Item =$BitFlags >> (& mut self , iterator : T ){ for item in iterator { self . insert ( item )}}} impl $crate :: _core :: iter :: FromIterator <$BitFlags > for $BitFlags { fn from_iter < T : $crate :: _core :: iter :: IntoIterator < Item =$BitFlags >> ( iterator : T )-> $BitFlags { let mut result = Self :: empty (); result . extend ( iterator ); result }}}; ($(# [$filtered : meta ])* ? # [ cfg $($cfgargs : tt )*]$(? # [$rest : ident $($restargs : tt )*])* fn $($item : tt )* )=>{ __impl_bitflags ! {$(# [$filtered ])* # [ cfg $($cfgargs )*]$(? # [$rest $($restargs )*])* fn $($item )* }}; ($(# [$filtered : meta ])* ? # [$next : ident $($nextargs : tt )*]$(? # [$rest : ident $($restargs : tt )*])* fn $($item : tt )* )=>{ __impl_bitflags ! {$(# [$filtered ])* $(? # [$rest $($restargs )*])* fn $($item )* }}; ($(# [$filtered : meta ])* fn $($item : tt )* )=>{$(# [$filtered ])* fn $($item )* }; ($(# [$filtered : meta ])* ? # [ cfg $($cfgargs : tt )*]$(? # [$rest : ident $($restargs : tt )*])* const $($item : tt )* )=>{ __impl_bitflags ! {$(# [$filtered ])* # [ cfg $($cfgargs )*]$(? # [$rest $($restargs )*])* const $($item )* }}; ($(# [$filtered : meta ])* ? # [$next : ident $($nextargs : tt )*]$(? # [$rest : ident $($restargs : tt )*])* const $($item : tt )* )=>{ __impl_bitflags ! {$(# [$filtered ])* $(? # [$rest $($restargs )*])* const $($item )* }}; ($(# [$filtered : meta ])* const $($item : tt )* )=>{$(# [$filtered ])* const $($item )* }; } +macro_rules! __ra_macro_fixture324 {($($item : item )*)=>{$(# [ cfg ( feature = "os-poll" )]# [ cfg_attr ( docsrs , doc ( cfg ( feature = "os-poll" )))]$item )* }} +macro_rules! __ra_macro_fixture325 {($($item : item )*)=>{$(# [ cfg ( not ( feature = "os-poll" ))]$item )* }} +macro_rules! __ra_macro_fixture326 {($($item : item )*)=>{$(# [ cfg ( any ( feature = "net" , all ( unix , feature = "os-ext" )))]# [ cfg_attr ( docsrs , doc ( any ( feature = "net" , all ( unix , feature = "os-ext" ))))]$item )* }} +macro_rules! __ra_macro_fixture327 {($($item : item )*)=>{$(# [ cfg ( feature = "net" )]# [ cfg_attr ( docsrs , doc ( cfg ( feature = "net" )))]$item )* }} +macro_rules! __ra_macro_fixture328 {($($item : item )*)=>{$(# [ cfg ( feature = "os-ext" )]# [ cfg_attr ( docsrs , doc ( cfg ( feature = "os-ext" )))]$item )* }} +macro_rules! __ra_macro_fixture329 {($name : ident , $read : ident , $bytes : expr , $data : expr )=>{ mod $name { use byteorder :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; use test :: black_box as bb ; use test :: Bencher ; const NITER : usize = 100_000 ; # [ bench ] fn read_big_endian ( b : & mut Bencher ){ let buf = $data ; b . iter (|| { for _ in 0 .. NITER { bb ( BigEndian ::$read (& buf , $bytes )); }}); }# [ bench ] fn read_little_endian ( b : & mut Bencher ){ let buf = $data ; b . iter (|| { for _ in 0 .. NITER { bb ( LittleEndian ::$read (& buf , $bytes )); }}); }# [ bench ] fn read_native_endian ( b : & mut Bencher ){ let buf = $data ; b . iter (|| { for _ in 0 .. NITER { bb ( NativeEndian ::$read (& buf , $bytes )); }}); }}}; ($ty : ident , $max : ident , $read : ident , $write : ident , $size : expr , $data : expr )=>{ mod $ty { use byteorder :: { BigEndian , ByteOrder , LittleEndian , NativeEndian , }; use std ::$ty ; use test :: black_box as bb ; use test :: Bencher ; const NITER : usize = 100_000 ; # [ bench ] fn read_big_endian ( b : & mut Bencher ){ let buf = $data ; b . iter (|| { for _ in 0 .. NITER { bb ( BigEndian ::$read (& buf )); }}); }# [ bench ] fn read_little_endian ( b : & mut Bencher ){ let buf = $data ; b . iter (|| { for _ in 0 .. NITER { bb ( LittleEndian ::$read (& buf )); }}); }# [ bench ] fn read_native_endian ( b : & mut Bencher ){ let buf = $data ; b . iter (|| { for _ in 0 .. NITER { bb ( NativeEndian ::$read (& buf )); }}); }# [ bench ] fn write_big_endian ( b : & mut Bencher ){ let mut buf = $data ; let n = $ty ::$max ; b . iter (|| { for _ in 0 .. NITER { bb ( BigEndian ::$write (& mut buf , n )); }}); }# [ bench ] fn write_little_endian ( b : & mut Bencher ){ let mut buf = $data ; let n = $ty ::$max ; b . iter (|| { for _ in 0 .. NITER { bb ( LittleEndian ::$write (& mut buf , n )); }}); }# [ bench ] fn write_native_endian ( b : & mut Bencher ){ let mut buf = $data ; let n = $ty ::$max ; b . iter (|| { for _ in 0 .. NITER { bb ( NativeEndian ::$write (& mut buf , n )); }}); }}}; } +macro_rules! __ra_macro_fixture330 {($name : ident , $numty : ty , $read : ident , $write : ident )=>{ mod $name { use std :: mem :: size_of ; use byteorder :: { BigEndian , ByteOrder , LittleEndian }; use rand :: distributions ; use rand :: { self , Rng }; use test :: Bencher ; # [ bench ] fn read_big_endian ( b : & mut Bencher ){ let mut numbers : Vec <$numty > = rand :: thread_rng (). sample_iter (& distributions :: Standard ). take ( 100000 ). collect (); let mut bytes = vec ! [ 0 ; numbers . len ()* size_of ::<$numty > ()]; BigEndian ::$write (& numbers , & mut bytes ); b . bytes = bytes . len () as u64 ; b . iter (|| { BigEndian ::$read (& bytes , & mut numbers ); }); }# [ bench ] fn read_little_endian ( b : & mut Bencher ){ let mut numbers : Vec <$numty > = rand :: thread_rng (). sample_iter (& distributions :: Standard ). take ( 100000 ). collect (); let mut bytes = vec ! [ 0 ; numbers . len ()* size_of ::<$numty > ()]; LittleEndian ::$write (& numbers , & mut bytes ); b . bytes = bytes . len () as u64 ; b . iter (|| { LittleEndian ::$read (& bytes , & mut numbers ); }); }# [ bench ] fn write_big_endian ( b : & mut Bencher ){ let numbers : Vec <$numty > = rand :: thread_rng (). sample_iter (& distributions :: Standard ). take ( 100000 ). collect (); let mut bytes = vec ! [ 0 ; numbers . len ()* size_of ::<$numty > ()]; b . bytes = bytes . len () as u64 ; b . iter (|| { BigEndian ::$write (& numbers , & mut bytes ); }); }# [ bench ] fn write_little_endian ( b : & mut Bencher ){ let numbers : Vec <$numty > = rand :: thread_rng (). sample_iter (& distributions :: Standard ). take ( 100000 ). collect (); let mut bytes = vec ! [ 0 ; numbers . len ()* size_of ::<$numty > ()]; b . bytes = bytes . len () as u64 ; b . iter (|| { LittleEndian ::$write (& numbers , & mut bytes ); }); }}}; } +macro_rules! __ra_macro_fixture331 {{$($(#$attr : tt )* fn $fn_name : ident ($($arg : tt )*)-> $ret : ty {$($code : tt )* })*}=>($(# [ test ]$(#$attr )* fn $fn_name (){ fn prop ($($arg )*)-> $ret {$($code )* }:: quickcheck :: quickcheck ( quickcheck ! (@ fn prop []$($arg )*)); })* ); (@ fn $f : ident [$($t : tt )*])=>{$f as fn ($($t ),*)-> _ }; (@ fn $f : ident [$($p : tt )*]: $($tail : tt )*)=>{ quickcheck ! (@ fn $f [$($p )* _]$($tail )*)}; (@ fn $f : ident [$($p : tt )*]$t : tt $($tail : tt )*)=>{ quickcheck ! (@ fn $f [$($p )*]$($tail )*)}; } +macro_rules! __ra_macro_fixture332 {($from : ty =>$to : ty ; $by : ident )=>( impl < 'a > From <$from > for UniCase <$to > { fn from ( s : $from )-> Self { UniCase :: unicode ( s .$by ())}}); ($from : ty =>$to : ty )=>( from_impl ! ($from =>$to ; into ); )} +macro_rules! __ra_macro_fixture333 {($to : ty )=>( impl < 'a > Into <$to > for UniCase <$to > { fn into ( self )-> $to { self . into_inner ()}}); } +macro_rules! __ra_macro_fixture334 {($name : ident , $ty : ident )=>{ fn $name ()-> usize { let mut rng = rand_xorshift :: XorShiftRng :: from_seed ([ 123u8 ; 16 ]); let mut mv = MeanAndVariance :: new (); let mut throwaway = 0 ; for _ in 0 .. SAMPLES { let f = loop { let f = $ty :: from_bits ( rng . gen ()); if f . is_finite (){ break f ; }}; let t1 = std :: time :: SystemTime :: now (); for _ in 0 .. ITERATIONS { throwaway += ryu :: Buffer :: new (). format_finite ( f ). len (); } let duration = t1 . elapsed (). unwrap (); let nanos = duration . as_secs ()* 1_000_000_000 + duration . subsec_nanos () as u64 ; mv . update ( nanos as f64 / ITERATIONS as f64 ); } println ! ( "{:12} {:8.3} {:8.3}" , concat ! ( stringify ! ($name ), ":" ), mv . mean , mv . stddev (), ); throwaway }}; } +macro_rules! __ra_macro_fixture335 {($(# [$doc : meta ])* pub trait $name : ident $($methods : tt )*)=>{ macro_rules ! $name {($m : ident $extra : tt )=>{$m ! {$extra pub trait $name $($methods )* }}} remove_sections ! {[]$(# [$doc ])* pub trait $name $($methods )* }}} +macro_rules! __ra_macro_fixture336 {($name : ident <$($typarm : tt ),*> where {$($bounds : tt )* } item : $item : ty , iter : $iter : ty , )=>( pub struct $name <$($typarm ),*> where $($bounds )* { iter : $iter , } impl <$($typarm ),*> Iterator for $name <$($typarm ),*> where $($bounds )* { type Item = $item ; # [ inline ] fn next (& mut self )-> Option < Self :: Item > { self . iter . next ()}# [ inline ] fn size_hint (& self )-> ( usize , Option < usize >){ self . iter . size_hint ()}}); } +macro_rules! __ra_macro_fixture337 {($($fmt_trait : ident )*)=>{$(impl < 'a , I > fmt ::$fmt_trait for Format < 'a , I > where I : Iterator , I :: Item : fmt ::$fmt_trait , { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { self . format ( f , fmt ::$fmt_trait :: fmt )}})* }} +macro_rules! __ra_macro_fixture338 {($($t : ty ),*)=>{$(not_zero_impl ! ($t , 0 ); )* }} +macro_rules! __ra_macro_fixture339 {($name : ident )=>{ impl Clone for $name {# [ inline ] fn clone (& self )-> Self {* self }}}; } +macro_rules! __ra_macro_fixture340 {([$($stack : tt )*])=>{$($stack )* }; ([$($stack : tt )*]{$($tail : tt )* })=>{$($stack )* { remove_sections_inner ! ([]$($tail )*); }}; ([$($stack : tt )*]$t : tt $($tail : tt )*)=>{ remove_sections ! ([$($stack )* $t ]$($tail )*); }; } +macro_rules! __ra_macro_fixture341 {($t : ty ,$z : expr )=>{ impl Zero for $t { fn zero ()-> Self {$z as $t } fn is_zero (& self )-> bool { self == & Self :: zero ()}}}; } +macro_rules! __ra_macro_fixture342 {($($ident : ident ),* $(,)?)=>{$(# [ allow ( bad_style )] pub const $ident : super :: Name = super :: Name :: new_inline ( stringify ! ($ident )); )* }; } +macro_rules! __ra_macro_fixture343 {($($trait : ident =>$expand : ident ),* )=>{# [ derive ( Debug , Clone , Copy , PartialEq , Eq , Hash )] pub enum BuiltinDeriveExpander {$($trait ),* } impl BuiltinDeriveExpander { pub fn expand (& self , db : & dyn AstDatabase , id : LazyMacroId , tt : & tt :: Subtree , )-> Result < tt :: Subtree , mbe :: ExpandError > { let expander = match * self {$(BuiltinDeriveExpander ::$trait =>$expand , )* }; expander ( db , id , tt )} fn find_by_name ( name : & name :: Name )-> Option < Self > { match name {$(id if id == & name :: name ! [$trait ]=> Some ( BuiltinDeriveExpander ::$trait ), )* _ => None , }}}}; } +macro_rules! __ra_macro_fixture344 {( LAZY : $(($name : ident , $kind : ident )=>$expand : ident ),* , EAGER : $(($e_name : ident , $e_kind : ident )=>$e_expand : ident ),* )=>{# [ derive ( Debug , Clone , Copy , PartialEq , Eq , Hash )] pub enum BuiltinFnLikeExpander {$($kind ),* }# [ derive ( Debug , Clone , Copy , PartialEq , Eq , Hash )] pub enum EagerExpander {$($e_kind ),* } impl BuiltinFnLikeExpander { pub fn expand (& self , db : & dyn AstDatabase , id : LazyMacroId , tt : & tt :: Subtree , )-> ExpandResult < tt :: Subtree > { let expander = match * self {$(BuiltinFnLikeExpander ::$kind =>$expand , )* }; expander ( db , id , tt )}} impl EagerExpander { pub fn expand (& self , db : & dyn AstDatabase , arg_id : EagerMacroId , tt : & tt :: Subtree , )-> ExpandResult < Option < ( tt :: Subtree , FragmentKind )>> { let expander = match * self {$(EagerExpander ::$e_kind =>$e_expand , )* }; expander ( db , arg_id , tt )}} fn find_by_name ( ident : & name :: Name )-> Option < Either < BuiltinFnLikeExpander , EagerExpander >> { match ident {$(id if id == & name :: name ! [$name ]=> Some ( Either :: Left ( BuiltinFnLikeExpander ::$kind )), )* $(id if id == & name :: name ! [$e_name ]=> Some ( Either :: Right ( EagerExpander ::$e_kind )), )* _ => return None , }}}; } +macro_rules! __ra_macro_fixture345 {($($ty : ty =>$this : ident $im : block );*)=>{$(impl ToTokenTree for $ty { fn to_token ($this )-> tt :: TokenTree { let leaf : tt :: Leaf = $im . into (); leaf . into ()}} impl ToTokenTree for &$ty { fn to_token ($this )-> tt :: TokenTree { let leaf : tt :: Leaf = $im . clone (). into (); leaf . into ()}})* }} +macro_rules! __ra_macro_fixture346 {($name : ident )=>{ impl $crate :: salsa :: InternKey for $name { fn from_intern_id ( v : $crate :: salsa :: InternId )-> Self {$name ( v )} fn as_intern_id (& self )-> $crate :: salsa :: InternId { self . 0 }}}; } +macro_rules! __ra_macro_fixture347 {($($var : ident ($t : ty )),+ )=>{$(impl From <$t > for AttrOwner { fn from ( t : $t )-> AttrOwner { AttrOwner ::$var ( t )}})+ }; } +macro_rules! __ra_macro_fixture348 {($($typ : ident in $fld : ident -> $ast : ty ),+ $(,)? )=>{# [ derive ( Debug , Copy , Clone , Eq , PartialEq , Hash )] pub enum ModItem {$($typ ( FileItemTreeId <$typ >), )+ }$(impl From < FileItemTreeId <$typ >> for ModItem { fn from ( id : FileItemTreeId <$typ >)-> ModItem { ModItem ::$typ ( id )}})+ $(impl ItemTreeNode for $typ { type Source = $ast ; fn ast_id (& self )-> FileAstId < Self :: Source > { self . ast_id } fn lookup ( tree : & ItemTree , index : Idx < Self >)-> & Self {& tree . data ().$fld [ index ]} fn id_from_mod_item ( mod_item : ModItem )-> Option < FileItemTreeId < Self >> { if let ModItem ::$typ ( id )= mod_item { Some ( id )} else { None }} fn id_to_mod_item ( id : FileItemTreeId < Self >)-> ModItem { ModItem ::$typ ( id )}} impl Index < Idx <$typ >> for ItemTree { type Output = $typ ; fn index (& self , index : Idx <$typ >)-> & Self :: Output {& self . data ().$fld [ index ]}})+ }; } +macro_rules! __ra_macro_fixture349 {($($fld : ident : $t : ty ),+ $(,)? )=>{$(impl Index < Idx <$t >> for ItemTree { type Output = $t ; fn index (& self , index : Idx <$t >)-> & Self :: Output {& self . data ().$fld [ index ]}})+ }; } +macro_rules! __ra_macro_fixture350 {($e : ident {$($v : ident ($t : ty )),* $(,)? })=>{$(impl From <$t > for $e { fn from ( it : $t )-> $e {$e ::$v ( it )}})* }} +macro_rules! __ra_macro_fixture351 {($id : ident , $loc : ident , $intern : ident , $lookup : ident )=>{ impl_intern_key ! ($id ); impl Intern for $loc { type ID = $id ; fn intern ( self , db : & dyn db :: DefDatabase )-> $id { db .$intern ( self )}} impl Lookup for $id { type Data = $loc ; fn lookup (& self , db : & dyn db :: DefDatabase )-> $loc { db .$lookup (* self )}}}; } +macro_rules! __ra_macro_fixture352 {([$derives : ident $($derive_t : tt )*]=>$(# [$($attrs : tt )*])* $inner : path )=>{# [ proc_macro_derive ($derives $($derive_t )*)]# [ allow ( non_snake_case )]$(# [$($attrs )*])* pub fn $derives ( i : $crate :: macros :: TokenStream )-> $crate :: macros :: TokenStream { match $crate :: macros :: parse ::<$crate :: macros :: DeriveInput > ( i ){ Ok ( p )=>{ match $crate :: Structure :: try_new (& p ){ Ok ( s )=>$crate :: MacroResult :: into_stream ($inner ( s )), Err ( e )=> e . to_compile_error (). into (), }} Err ( e )=> e . to_compile_error (). into (), }}}; } +macro_rules! __ra_macro_fixture353 {($I : ident =>$t : ty )=>{ impl <$I : Interner > Zip <$I > for $t { fn zip_with < 'i , Z : Zipper < 'i , $I >> ( _zipper : & mut Z , _variance : Variance , a : & Self , b : & Self , )-> Fallible < ()> where I : 'i , { if a != b { return Err ( NoSolution ); } Ok (())}}}; } +macro_rules! __ra_macro_fixture354 {($($n : ident ),*)=>{ impl <$($n : Fold < I >,)* I : Interner > Fold < I > for ($($n ,)*){ type Result = ($($n :: Result ,)*); fn fold_with < 'i > ( self , folder : & mut dyn Folder < 'i , I >, outer_binder : DebruijnIndex )-> Fallible < Self :: Result > where I : 'i , {# [ allow ( non_snake_case )] let ($($n ),*)= self ; Ok (($($n . fold_with ( folder , outer_binder )?,)*))}}}} +macro_rules! __ra_macro_fixture355 {($t : ty )=>{ impl < I : Interner > $crate :: fold :: Fold < I > for $t { type Result = Self ; fn fold_with < 'i > ( self , _folder : & mut dyn ($crate :: fold :: Folder < 'i , I >), _outer_binder : DebruijnIndex , )-> :: chalk_ir :: Fallible < Self :: Result > where I : 'i , { Ok ( self )}}}; } +macro_rules! __ra_macro_fixture356 {($t : ident )=>{ impl < I : Interner > $crate :: fold :: Fold < I > for $t < I > { type Result = $t < I >; fn fold_with < 'i > ( self , _folder : & mut dyn ($crate :: fold :: Folder < 'i , I >), _outer_binder : DebruijnIndex , )-> :: chalk_ir :: Fallible < Self :: Result > where I : 'i , { Ok ( self )}}}; } +macro_rules! __ra_macro_fixture357 {($($n : ident ),*)=>{ impl <$($n : Visit < I >,)* I : Interner > Visit < I > for ($($n ,)*){ fn visit_with < 'i , BT > (& self , visitor : & mut dyn Visitor < 'i , I , BreakTy = BT >, outer_binder : DebruijnIndex )-> ControlFlow < BT > where I : 'i {# [ allow ( non_snake_case )] let & ($(ref $n ),*)= self ; $(try_break ! ($n . visit_with ( visitor , outer_binder )); )* ControlFlow :: CONTINUE }}}} +macro_rules! __ra_macro_fixture358 {($t : ty )=>{ impl < I : Interner > $crate :: visit :: Visit < I > for $t { fn visit_with < 'i , B > (& self , _visitor : & mut dyn ($crate :: visit :: Visitor < 'i , I , BreakTy = B >), _outer_binder : DebruijnIndex , )-> ControlFlow < B > where I : 'i , { ControlFlow :: CONTINUE }}}; } +macro_rules! __ra_macro_fixture359 {($t : ident )=>{ impl < I : Interner > $crate :: visit :: Visit < I > for $t < I > { fn visit_with < 'i , B > (& self , _visitor : & mut dyn ($crate :: visit :: Visitor < 'i , I , BreakTy = B >), _outer_binder : DebruijnIndex , )-> ControlFlow < B > where I : 'i , { ControlFlow :: CONTINUE }}}; } +macro_rules! __ra_macro_fixture360 {( for ($($t : tt )*)$u : ty )=>{ impl <$($t )*> CastTo <$u > for $u { fn cast_to ( self , _interner : &<$u as HasInterner >:: Interner )-> $u { self }}}; ($u : ty )=>{ impl CastTo <$u > for $u { fn cast_to ( self , interner : &<$u as HasInterner >:: Interner )-> $u { self }}}; } +macro_rules! __ra_macro_fixture361 {($($id : ident ), *)=>{$(impl < I : Interner > std :: fmt :: Debug for $id < I > { fn fmt (& self , fmt : & mut std :: fmt :: Formatter < '_ >)-> Result < (), std :: fmt :: Error > { write ! ( fmt , "{}({:?})" , stringify ! ($id ), self . 0 )}})* }; } +macro_rules! __ra_macro_fixture362 {($seq : ident , $data : ident =>$elem : ty , $intern : ident =>$interned : ident )=>{ interned_slice_common ! ($seq , $data =>$elem , $intern =>$interned ); impl < I : Interner > $seq < I > {# [ doc = " Tries to create a sequence using an iterator of element-like things." ] pub fn from_fallible < E > ( interner : & I , elements : impl IntoIterator < Item = Result < impl CastTo <$elem >, E >>, )-> Result < Self , E > { Ok ( Self { interned : I ::$intern ( interner , elements . into_iter (). casted ( interner ))?, })}# [ doc = " Create a sequence from elements" ] pub fn from_iter ( interner : & I , elements : impl IntoIterator < Item = impl CastTo <$elem >>, )-> Self { Self :: from_fallible ( interner , elements . into_iter (). map (| el | -> Result <$elem , ()> { Ok ( el . cast ( interner ))}), ). unwrap ()}# [ doc = " Create a sequence from a single element." ] pub fn from1 ( interner : & I , element : impl CastTo <$elem >)-> Self { Self :: from_iter ( interner , Some ( element ))}}}; } +macro_rules! __ra_macro_fixture363 {($seq : ident , $data : ident =>$elem : ty , $intern : ident =>$interned : ident )=>{# [ doc = " List of interned elements." ]# [ derive ( Copy , Clone , PartialEq , Eq , Hash , PartialOrd , Ord , HasInterner )] pub struct $seq < I : Interner > { interned : I ::$interned , } impl < I : Interner > $seq < I > {# [ doc = " Get the interned elements." ] pub fn interned (& self )-> & I ::$interned {& self . interned }# [ doc = " Returns a slice containing the elements." ] pub fn as_slice (& self , interner : & I )-> & [$elem ]{ Interner ::$data ( interner , & self . interned )}# [ doc = " Index into the sequence." ] pub fn at (& self , interner : & I , index : usize )-> &$elem {& self . as_slice ( interner )[ index ]}# [ doc = " Create an empty sequence." ] pub fn empty ( interner : & I )-> Self { Self :: from_iter ( interner , None ::<$elem >)}# [ doc = " Check whether this is an empty sequence." ] pub fn is_empty (& self , interner : & I )-> bool { self . as_slice ( interner ). is_empty ()}# [ doc = " Get an iterator over the elements of the sequence." ] pub fn iter (& self , interner : & I )-> std :: slice :: Iter < '_ , $elem > { self . as_slice ( interner ). iter ()}# [ doc = " Get the length of the sequence." ] pub fn len (& self , interner : & I )-> usize { self . as_slice ( interner ). len ()}}}; } +macro_rules! __ra_macro_fixture364 {($(# [$attrs : meta ])* $vis : vis static $name : ident : $ty : ty )=>($(# [$attrs ])* $vis static $name : $crate :: ScopedKey <$ty > = $crate :: ScopedKey { inner : { thread_local ! ( static FOO : :: std :: cell :: Cell < usize > = {:: std :: cell :: Cell :: new ( 0 )}); & FOO }, _marker : :: std :: marker :: PhantomData , }; )} +macro_rules! __ra_macro_fixture365 {($(($def : path , $ast : path , $meth : ident )),* ,)=>{$(impl ToDef for $ast { type Def = $def ; fn to_def ( sema : & SemanticsImpl , src : InFile < Self >)-> Option < Self :: Def > { sema . with_ctx (| ctx | ctx .$meth ( src )). map (<$def >:: from )}})*}} +macro_rules! __ra_macro_fixture366 {($(($id : path , $ty : path )),*)=>{$(impl From <$id > for $ty { fn from ( id : $id )-> $ty {$ty { id }}} impl From <$ty > for $id { fn from ( ty : $ty )-> $id { ty . id }})*}} +macro_rules! __ra_macro_fixture367 {($(($def : ident , $def_id : ident ),)*)=>{$(impl HasAttrs for $def { fn attrs ( self , db : & dyn HirDatabase )-> Attrs { let def = AttrDefId ::$def_id ( self . into ()); db . attrs ( def )} fn docs ( self , db : & dyn HirDatabase )-> Option < Documentation > { let def = AttrDefId ::$def_id ( self . into ()); db . attrs ( def ). docs ()} fn resolve_doc_path ( self , db : & dyn HirDatabase , link : & str , ns : Option < Namespace >)-> Option < ModuleDef > { let def = AttrDefId ::$def_id ( self . into ()); resolve_doc_path ( db , def , link , ns ). map ( ModuleDef :: from )}})*}; } +macro_rules! __ra_macro_fixture368 {($($variant : ident ),* for $enum : ident )=>{$(impl HasAttrs for $variant { fn attrs ( self , db : & dyn HirDatabase )-> Attrs {$enum ::$variant ( self ). attrs ( db )} fn docs ( self , db : & dyn HirDatabase )-> Option < Documentation > {$enum ::$variant ( self ). docs ( db )} fn resolve_doc_path ( self , db : & dyn HirDatabase , link : & str , ns : Option < Namespace >)-> Option < ModuleDef > {$enum ::$variant ( self ). resolve_doc_path ( db , link , ns )}})*}; } +macro_rules! __ra_macro_fixture369 {{$($(#$attr : tt )* fn $fn_name : ident ($($arg : tt )*)-> $ret : ty {$($code : tt )* })*}=>($(# [ test ]$(#$attr )* fn $fn_name (){ fn prop ($($arg )*)-> $ret {$($code )* }:: quickcheck :: quickcheck ( quickcheck ! (@ fn prop []$($arg )*)); })* ); (@ fn $f : ident [$($t : tt )*])=>{$f as fn ($($t ),*)-> _ }; (@ fn $f : ident [$($p : tt )*]: $($tail : tt )*)=>{ quickcheck ! (@ fn $f [$($p )* _]$($tail )*)}; (@ fn $f : ident [$($p : tt )*]$t : tt $($tail : tt )*)=>{ quickcheck ! (@ fn $f [$($p )*]$($tail )*)}; } +macro_rules! __ra_macro_fixture370 {($($bool : expr , )+)=>{ fn _static_assert (){$(let _ = std :: mem :: transmute ::< [ u8 ; $bool as usize ], u8 >; )+ }}} +macro_rules! __ra_macro_fixture371 {($ty : ident is $($marker : ident ) and +)=>{# [ test ]# [ allow ( non_snake_case )] fn $ty (){ fn assert_implemented < T : $($marker +)+> (){} assert_implemented ::<$ty > (); }}; ($ty : ident is not $($marker : ident ) or +)=>{# [ test ]# [ allow ( non_snake_case )] fn $ty (){$({trait IsNotImplemented { fn assert_not_implemented (){}} impl < T : $marker > IsNotImplemented for T {} trait IsImplemented { fn assert_not_implemented (){}} impl IsImplemented for $ty {}<$ty >:: assert_not_implemented (); })+ }}; } +macro_rules! __ra_macro_fixture372 {($($types : ident )*)=>{$(assert_impl ! ($types is UnwindSafe and RefUnwindSafe ); )* }; } +macro_rules! __ra_macro_fixture373 {($($(# [$attr : meta ])* $name : ident ($value : expr , $expected : expr )),* )=>{$($(# [$attr ])* # [ test ] fn $name (){# [ cfg ( feature = "std" )]{ let mut buf = [ b'\0' ; 40 ]; let len = itoa :: write (& mut buf [..], $value ). unwrap (); assert_eq ! (& buf [ 0 .. len ], $expected . as_bytes ()); } let mut s = String :: new (); itoa :: fmt (& mut s , $value ). unwrap (); assert_eq ! ( s , $expected ); })* }} +macro_rules! __ra_macro_fixture374 {($($name : ident =>$description : expr ,)+)=>{# [ doc = " Errors that can occur during parsing." ]# [ doc = "" ]# [ doc = " This may be extended in the future so exhaustive matching is" ]# [ doc = " discouraged with an unused variant." ]# [ allow ( clippy :: manual_non_exhaustive )]# [ derive ( PartialEq , Eq , Clone , Copy , Debug )] pub enum ParseError {$($name , )+ # [ doc = " Unused variant enable non-exhaustive matching" ]# [ doc ( hidden )] __FutureProof , } impl fmt :: Display for ParseError { fn fmt (& self , fmt : & mut Formatter < '_ >)-> fmt :: Result { match * self {$(ParseError ::$name => fmt . write_str ($description ), )+ ParseError :: __FutureProof =>{ unreachable ! ( "Don't abuse the FutureProof!" ); }}}}}} +macro_rules! __ra_macro_fixture375 {($($name : ident =>$description : expr ,)+)=>{# [ doc = " Non-fatal syntax violations that can occur during parsing." ]# [ doc = "" ]# [ doc = " This may be extended in the future so exhaustive matching is" ]# [ doc = " discouraged with an unused variant." ]# [ allow ( clippy :: manual_non_exhaustive )]# [ derive ( PartialEq , Eq , Clone , Copy , Debug )] pub enum SyntaxViolation {$($name , )+ # [ doc = " Unused variant enable non-exhaustive matching" ]# [ doc ( hidden )] __FutureProof , } impl SyntaxViolation { pub fn description (& self )-> & 'static str { match * self {$(SyntaxViolation ::$name =>$description , )+ SyntaxViolation :: __FutureProof =>{ unreachable ! ( "Don't abuse the FutureProof!" ); }}}}}} +macro_rules! __ra_macro_fixture376 {('owned : $($oty : ident ,)* 'interned : $($ity : ident ,)* )=>{# [ repr ( C )]# [ allow ( non_snake_case )] pub struct HandleCounters {$($oty : AtomicUsize ,)* $($ity : AtomicUsize ,)* } impl HandleCounters { extern "C" fn get ()-> & 'static Self { static COUNTERS : HandleCounters = HandleCounters {$($oty : AtomicUsize :: new ( 1 ),)* $($ity : AtomicUsize :: new ( 1 ),)* }; & COUNTERS }}# [ repr ( C )]# [ allow ( non_snake_case )] pub ( super ) struct HandleStore < S : server :: Types > {$($oty : handle :: OwnedStore < S ::$oty >,)* $($ity : handle :: InternedStore < S ::$ity >,)* } impl < S : server :: Types > HandleStore < S > { pub ( super ) fn new ( handle_counters : & 'static HandleCounters )-> Self { HandleStore {$($oty : handle :: OwnedStore :: new (& handle_counters .$oty ),)* $($ity : handle :: InternedStore :: new (& handle_counters .$ity ),)* }}}$(# [ repr ( C )] pub struct $oty ( pub ( crate ) handle :: Handle ); impl Drop for $oty { fn drop (& mut self ){$oty ( self . 0 ). drop (); }} impl < S > Encode < S > for $oty { fn encode ( self , w : & mut Writer , s : & mut S ){ let handle = self . 0 ; mem :: forget ( self ); handle . encode ( w , s ); }} impl < S : server :: Types > DecodeMut < '_ , '_ , HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$oty , $oty > { fn decode ( r : & mut Reader < '_ >, s : & mut HandleStore < server :: MarkedTypes < S >>)-> Self { s .$oty . take ( handle :: Handle :: decode ( r , & mut ()))}} impl < S > Encode < S > for &$oty { fn encode ( self , w : & mut Writer , s : & mut S ){ self . 0 . encode ( w , s ); }} impl < 's , S : server :: Types ,> Decode < '_ , 's , HandleStore < server :: MarkedTypes < S >>> for & 's Marked < S ::$oty , $oty > { fn decode ( r : & mut Reader < '_ >, s : & 's HandleStore < server :: MarkedTypes < S >>)-> Self {& s .$oty [ handle :: Handle :: decode ( r , & mut ())]}} impl < S > Encode < S > for & mut $oty { fn encode ( self , w : & mut Writer , s : & mut S ){ self . 0 . encode ( w , s ); }} impl < 's , S : server :: Types > DecodeMut < '_ , 's , HandleStore < server :: MarkedTypes < S >>> for & 's mut Marked < S ::$oty , $oty > { fn decode ( r : & mut Reader < '_ >, s : & 's mut HandleStore < server :: MarkedTypes < S >> )-> Self {& mut s .$oty [ handle :: Handle :: decode ( r , & mut ())]}} impl < S : server :: Types > Encode < HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$oty , $oty > { fn encode ( self , w : & mut Writer , s : & mut HandleStore < server :: MarkedTypes < S >>){ s .$oty . alloc ( self ). encode ( w , s ); }} impl < S > DecodeMut < '_ , '_ , S > for $oty { fn decode ( r : & mut Reader < '_ >, s : & mut S )-> Self {$oty ( handle :: Handle :: decode ( r , s ))}})* $(# [ repr ( C )]# [ derive ( Copy , Clone , PartialEq , Eq , Hash )] pub ( crate ) struct $ity ( handle :: Handle ); impl < S > Encode < S > for $ity { fn encode ( self , w : & mut Writer , s : & mut S ){ self . 0 . encode ( w , s ); }} impl < S : server :: Types > DecodeMut < '_ , '_ , HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$ity , $ity > { fn decode ( r : & mut Reader < '_ >, s : & mut HandleStore < server :: MarkedTypes < S >>)-> Self { s .$ity . copy ( handle :: Handle :: decode ( r , & mut ()))}} impl < S : server :: Types > Encode < HandleStore < server :: MarkedTypes < S >>> for Marked < S ::$ity , $ity > { fn encode ( self , w : & mut Writer , s : & mut HandleStore < server :: MarkedTypes < S >>){ s .$ity . alloc ( self ). encode ( w , s ); }} impl < S > DecodeMut < '_ , '_ , S > for $ity { fn decode ( r : & mut Reader < '_ >, s : & mut S )-> Self {$ity ( handle :: Handle :: decode ( r , s ))}})* }} +macro_rules! __ra_macro_fixture377 {($S : ident , $self : ident , $m : ident )=>{$m ! { FreeFunctions { fn drop ($self : $S :: FreeFunctions ); fn track_env_var ( var : & str , value : Option <& str >); }, TokenStream { fn drop ($self : $S :: TokenStream ); fn clone ($self : &$S :: TokenStream )-> $S :: TokenStream ; fn new ()-> $S :: TokenStream ; fn is_empty ($self : &$S :: TokenStream )-> bool ; fn from_str ( src : & str )-> $S :: TokenStream ; fn to_string ($self : &$S :: TokenStream )-> String ; fn from_token_tree ( tree : TokenTree <$S :: Group , $S :: Punct , $S :: Ident , $S :: Literal >, )-> $S :: TokenStream ; fn into_iter ($self : $S :: TokenStream )-> $S :: TokenStreamIter ; }, TokenStreamBuilder { fn drop ($self : $S :: TokenStreamBuilder ); fn new ()-> $S :: TokenStreamBuilder ; fn push ($self : & mut $S :: TokenStreamBuilder , stream : $S :: TokenStream ); fn build ($self : $S :: TokenStreamBuilder )-> $S :: TokenStream ; }, TokenStreamIter { fn drop ($self : $S :: TokenStreamIter ); fn clone ($self : &$S :: TokenStreamIter )-> $S :: TokenStreamIter ; fn next ($self : & mut $S :: TokenStreamIter , )-> Option < TokenTree <$S :: Group , $S :: Punct , $S :: Ident , $S :: Literal >>; }, Group { fn drop ($self : $S :: Group ); fn clone ($self : &$S :: Group )-> $S :: Group ; fn new ( delimiter : Delimiter , stream : $S :: TokenStream )-> $S :: Group ; fn delimiter ($self : &$S :: Group )-> Delimiter ; fn stream ($self : &$S :: Group )-> $S :: TokenStream ; fn span ($self : &$S :: Group )-> $S :: Span ; fn span_open ($self : &$S :: Group )-> $S :: Span ; fn span_close ($self : &$S :: Group )-> $S :: Span ; fn set_span ($self : & mut $S :: Group , span : $S :: Span ); }, Punct { fn new ( ch : char , spacing : Spacing )-> $S :: Punct ; fn as_char ($self : $S :: Punct )-> char ; fn spacing ($self : $S :: Punct )-> Spacing ; fn span ($self : $S :: Punct )-> $S :: Span ; fn with_span ($self : $S :: Punct , span : $S :: Span )-> $S :: Punct ; }, Ident { fn new ( string : & str , span : $S :: Span , is_raw : bool )-> $S :: Ident ; fn span ($self : $S :: Ident )-> $S :: Span ; fn with_span ($self : $S :: Ident , span : $S :: Span )-> $S :: Ident ; }, Literal { fn drop ($self : $S :: Literal ); fn clone ($self : &$S :: Literal )-> $S :: Literal ; fn debug_kind ($self : &$S :: Literal )-> String ; fn symbol ($self : &$S :: Literal )-> String ; fn suffix ($self : &$S :: Literal )-> Option < String >; fn integer ( n : & str )-> $S :: Literal ; fn typed_integer ( n : & str , kind : & str )-> $S :: Literal ; fn float ( n : & str )-> $S :: Literal ; fn f32 ( n : & str )-> $S :: Literal ; fn f64 ( n : & str )-> $S :: Literal ; fn string ( string : & str )-> $S :: Literal ; fn character ( ch : char )-> $S :: Literal ; fn byte_string ( bytes : & [ u8 ])-> $S :: Literal ; fn span ($self : &$S :: Literal )-> $S :: Span ; fn set_span ($self : & mut $S :: Literal , span : $S :: Span ); fn subspan ($self : &$S :: Literal , start : Bound < usize >, end : Bound < usize >, )-> Option <$S :: Span >; }, SourceFile { fn drop ($self : $S :: SourceFile ); fn clone ($self : &$S :: SourceFile )-> $S :: SourceFile ; fn eq ($self : &$S :: SourceFile , other : &$S :: SourceFile )-> bool ; fn path ($self : &$S :: SourceFile )-> String ; fn is_real ($self : &$S :: SourceFile )-> bool ; }, MultiSpan { fn drop ($self : $S :: MultiSpan ); fn new ()-> $S :: MultiSpan ; fn push ($self : & mut $S :: MultiSpan , span : $S :: Span ); }, Diagnostic { fn drop ($self : $S :: Diagnostic ); fn new ( level : Level , msg : & str , span : $S :: MultiSpan )-> $S :: Diagnostic ; fn sub ($self : & mut $S :: Diagnostic , level : Level , msg : & str , span : $S :: MultiSpan , ); fn emit ($self : $S :: Diagnostic ); }, Span { fn debug ($self : $S :: Span )-> String ; fn def_site ()-> $S :: Span ; fn call_site ()-> $S :: Span ; fn mixed_site ()-> $S :: Span ; fn source_file ($self : $S :: Span )-> $S :: SourceFile ; fn parent ($self : $S :: Span )-> Option <$S :: Span >; fn source ($self : $S :: Span )-> $S :: Span ; fn start ($self : $S :: Span )-> LineColumn ; fn end ($self : $S :: Span )-> LineColumn ; fn join ($self : $S :: Span , other : $S :: Span )-> Option <$S :: Span >; fn resolved_at ($self : $S :: Span , at : $S :: Span )-> $S :: Span ; fn source_text ($self : $S :: Span )-> Option < String >; }, }}; } +macro_rules! __ra_macro_fixture378 {( le $ty : ty )=>{ impl < S > Encode < S > for $ty { fn encode ( self , w : & mut Writer , _: & mut S ){ w . write_all (& self . to_le_bytes ()). unwrap (); }} impl < S > DecodeMut < '_ , '_ , S > for $ty { fn decode ( r : & mut Reader < '_ >, _: & mut S )-> Self { const N : usize = :: std :: mem :: size_of ::<$ty > (); let mut bytes = [ 0 ; N ]; bytes . copy_from_slice (& r [.. N ]); * r = & r [ N ..]; Self :: from_le_bytes ( bytes )}}}; ( struct $name : ident {$($field : ident ),* $(,)? })=>{ impl < S > Encode < S > for $name { fn encode ( self , w : & mut Writer , s : & mut S ){$(self .$field . encode ( w , s );)* }} impl < S > DecodeMut < '_ , '_ , S > for $name { fn decode ( r : & mut Reader < '_ >, s : & mut S )-> Self {$name {$($field : DecodeMut :: decode ( r , s )),* }}}}; ( enum $name : ident $(<$($T : ident ),+>)? {$($variant : ident $(($field : ident ))*),* $(,)? })=>{ impl < S , $($($T : Encode < S >),+)?> Encode < S > for $name $(<$($T ),+>)? { fn encode ( self , w : & mut Writer , s : & mut S ){# [ allow ( non_upper_case_globals )] mod tag {# [ repr ( u8 )] enum Tag {$($variant ),* }$(pub const $variant : u8 = Tag ::$variant as u8 ;)* } match self {$($name ::$variant $(($field ))* =>{ tag ::$variant . encode ( w , s ); $($field . encode ( w , s );)* })* }}} impl < 'a , S , $($($T : for < 's > DecodeMut < 'a , 's , S >),+)?> DecodeMut < 'a , '_ , S > for $name $(<$($T ),+>)? { fn decode ( r : & mut Reader < 'a >, s : & mut S )-> Self {# [ allow ( non_upper_case_globals )] mod tag {# [ repr ( u8 )] enum Tag {$($variant ),* }$(pub const $variant : u8 = Tag ::$variant as u8 ;)* } match u8 :: decode ( r , s ){$(tag ::$variant =>{$(let $field = DecodeMut :: decode ( r , s );)* $name ::$variant $(($field ))* })* _ => unreachable ! (), }}}}} +macro_rules! __ra_macro_fixture379 {($($ty : ty ),* $(,)?)=>{$(impl Mark for $ty { type Unmarked = Self ; fn mark ( unmarked : Self :: Unmarked )-> Self { unmarked }} impl Unmark for $ty { type Unmarked = Self ; fn unmark ( self )-> Self :: Unmarked { self }})* }} +macro_rules! __ra_macro_fixture380 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )*;)* }),* $(,)?)=>{$(impl $name {# [ allow ( unused )]$(pub ( crate ) fn $method ($($arg : $arg_ty ),*)$(-> $ret_ty )* { panic ! ( "hello" ); })* })* }} +macro_rules! __ra_macro_fixture381 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )?;)* }),* $(,)?)=>{ pub trait Types {$(associated_item ! ( type $name );)* }$(pub trait $name : Types {$(associated_item ! ( fn $method (& mut self , $($arg : $arg_ty ),*)$(-> $ret_ty )?);)* })* pub trait Server : Types $(+ $name )* {} impl < S : Types $(+ $name )*> Server for S {}}} +macro_rules! __ra_macro_fixture382 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )?;)* }),* $(,)?)=>{ impl < S : Types > Types for MarkedTypes < S > {$(type $name = Marked < S ::$name , client ::$name >;)* }$(impl < S : $name > $name for MarkedTypes < S > {$(fn $method (& mut self , $($arg : $arg_ty ),*)$(-> $ret_ty )? {<_>:: mark ($name ::$method (& mut self . 0 , $($arg . unmark ()),*))})* })* }} +macro_rules! __ra_macro_fixture383 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )?;)* }),* $(,)?)=>{ pub trait DispatcherTrait {$(type $name ;)* fn dispatch (& mut self , b : Buffer < u8 >)-> Buffer < u8 >; } impl < S : Server > DispatcherTrait for Dispatcher < MarkedTypes < S >> {$(type $name = < MarkedTypes < S > as Types >::$name ;)* fn dispatch (& mut self , mut b : Buffer < u8 >)-> Buffer < u8 > { let Dispatcher { handle_store , server }= self ; let mut reader = & b [..]; match api_tags :: Method :: decode (& mut reader , & mut ()){$(api_tags :: Method ::$name ( m )=> match m {$(api_tags ::$name ::$method =>{ let mut call_method = || { reverse_decode ! ( reader , handle_store ; $($arg : $arg_ty ),*); $name ::$method ( server , $($arg ),*)}; let r = if thread :: panicking (){ Ok ( call_method ())} else { panic :: catch_unwind ( panic :: AssertUnwindSafe ( call_method )). map_err ( PanicMessage :: from )}; b . clear (); r . encode (& mut b , handle_store ); })* }),* } b }}}} +macro_rules! __ra_macro_fixture384 {($($name : ident {$(fn $method : ident ($($arg : ident : $arg_ty : ty ),* $(,)?)$(-> $ret_ty : ty )*;)* }),* $(,)?)=>{$(pub ( super ) enum $name {$($method ),* } rpc_encode_decode ! ( enum $name {$($method ),* }); )* pub ( super ) enum Method {$($name ($name )),* } rpc_encode_decode ! ( enum Method {$($name ( m )),* }); }} +macro_rules! __ra_macro_fixture385 {($(($ident : ident , $string : literal )),*$(,)?)=>{$(pub ( crate ) const $ident : SemanticTokenType = SemanticTokenType :: new ($string );)* pub ( crate ) const SUPPORTED_TYPES : & [ SemanticTokenType ]= & [ SemanticTokenType :: COMMENT , SemanticTokenType :: KEYWORD , SemanticTokenType :: STRING , SemanticTokenType :: NUMBER , SemanticTokenType :: REGEXP , SemanticTokenType :: OPERATOR , SemanticTokenType :: NAMESPACE , SemanticTokenType :: TYPE , SemanticTokenType :: STRUCT , SemanticTokenType :: CLASS , SemanticTokenType :: INTERFACE , SemanticTokenType :: ENUM , SemanticTokenType :: ENUM_MEMBER , SemanticTokenType :: TYPE_PARAMETER , SemanticTokenType :: FUNCTION , SemanticTokenType :: METHOD , SemanticTokenType :: PROPERTY , SemanticTokenType :: MACRO , SemanticTokenType :: VARIABLE , SemanticTokenType :: PARAMETER , $($ident ),* ]; }; } +macro_rules! __ra_macro_fixture386 {($(($ident : ident , $string : literal )),*$(,)?)=>{$(pub ( crate ) const $ident : SemanticTokenModifier = SemanticTokenModifier :: new ($string );)* pub ( crate ) const SUPPORTED_MODIFIERS : & [ SemanticTokenModifier ]= & [ SemanticTokenModifier :: DOCUMENTATION , SemanticTokenModifier :: DECLARATION , SemanticTokenModifier :: DEFINITION , SemanticTokenModifier :: STATIC , SemanticTokenModifier :: ABSTRACT , SemanticTokenModifier :: DEPRECATED , SemanticTokenModifier :: READONLY , $($ident ),* ]; }; } +macro_rules! __ra_macro_fixture387 {( struct $name : ident {$($(# [ doc =$doc : literal ])* $field : ident $(| $alias : ident )?: $ty : ty = $default : expr , )* })=>{# [ allow ( non_snake_case )]# [ derive ( Debug , Clone )] struct $name {$($field : $ty ,)* } impl $name { fn from_json ( mut json : serde_json :: Value )-> $name {$name {$($field : get_field (& mut json , stringify ! ($field ), None $(. or ( Some ( stringify ! ($alias ))))?, $default , ), )*}} fn json_schema ()-> serde_json :: Value { schema (& [$({let field = stringify ! ($field ); let ty = stringify ! ($ty ); ( field , ty , & [$($doc ),*], $default )},)* ])}# [ cfg ( test )] fn manual ()-> String { manual (& [$({let field = stringify ! ($field ); let ty = stringify ! ($ty ); ( field , ty , & [$($doc ),*], $default )},)* ])}}}; } +macro_rules! __ra_macro_fixture388 {($($name : ident ($value : expr ),)*)=>{ mod bench_ryu { use super ::*; $(# [ bench ] fn $name ( b : & mut Bencher ){ let mut buf = ryu :: Buffer :: new (); b . iter ( move || { let value = black_box ($value ); let formatted = buf . format_finite ( value ); black_box ( formatted ); }); })* } mod bench_std_fmt { use super ::*; $(# [ bench ] fn $name ( b : & mut Bencher ){ let mut buf = Vec :: with_capacity ( 20 ); b . iter (|| { buf . clear (); let value = black_box ($value ); write ! (& mut buf , "{}" , value ). unwrap (); black_box ( buf . as_slice ()); }); })* }}; } +macro_rules! __ra_macro_fixture389 {($($T : ident ),*)=>{$(mod $T { use test :: Bencher ; use num_integer :: { Average , Integer }; use super :: { UncheckedAverage , NaiveAverage , ModuloAverage }; use super :: { bench_ceil , bench_floor , bench_unchecked }; naive_average ! ($T ); unchecked_average ! ($T ); modulo_average ! ($T ); const SIZE : $T = 30 ; fn overflowing ()-> Vec < ($T , $T )> {(($T :: max_value ()- SIZE )..$T :: max_value ()). flat_map (| x | -> Vec <_> {(($T :: max_value ()- 100 ).. ($T :: max_value ()- 100 + SIZE )). map (| y | ( x , y )). collect ()}). collect ()} fn small ()-> Vec < ($T , $T )> {( 0 .. SIZE ). flat_map (| x | -> Vec <_> {( 0 .. SIZE ). map (| y | ( x , y )). collect ()}). collect ()} fn rand ()-> Vec < ($T , $T )> { small (). into_iter (). map (| ( x , y )| ( super :: lcg ( x ), super :: lcg ( y ))). collect ()} mod ceil { use super ::*; mod small { use super ::*; # [ bench ] fn optimized ( b : & mut Bencher ){ let v = small (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . average_ceil ( y )); }# [ bench ] fn naive ( b : & mut Bencher ){ let v = small (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . naive_average_ceil ( y )); }# [ bench ] fn unchecked ( b : & mut Bencher ){ let v = small (); bench_unchecked ( b , & v , | x : &$T , y : &$T | x . unchecked_average_ceil ( y )); }# [ bench ] fn modulo ( b : & mut Bencher ){ let v = small (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . modulo_average_ceil ( y )); }} mod overflowing { use super ::*; # [ bench ] fn optimized ( b : & mut Bencher ){ let v = overflowing (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . average_ceil ( y )); }# [ bench ] fn naive ( b : & mut Bencher ){ let v = overflowing (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . naive_average_ceil ( y )); }# [ bench ] fn unchecked ( b : & mut Bencher ){ let v = overflowing (); bench_unchecked ( b , & v , | x : &$T , y : &$T | x . unchecked_average_ceil ( y )); }# [ bench ] fn modulo ( b : & mut Bencher ){ let v = overflowing (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . modulo_average_ceil ( y )); }} mod rand { use super ::*; # [ bench ] fn optimized ( b : & mut Bencher ){ let v = rand (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . average_ceil ( y )); }# [ bench ] fn naive ( b : & mut Bencher ){ let v = rand (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . naive_average_ceil ( y )); }# [ bench ] fn unchecked ( b : & mut Bencher ){ let v = rand (); bench_unchecked ( b , & v , | x : &$T , y : &$T | x . unchecked_average_ceil ( y )); }# [ bench ] fn modulo ( b : & mut Bencher ){ let v = rand (); bench_ceil ( b , & v , | x : &$T , y : &$T | x . modulo_average_ceil ( y )); }}} mod floor { use super ::*; mod small { use super ::*; # [ bench ] fn optimized ( b : & mut Bencher ){ let v = small (); bench_floor ( b , & v , | x : &$T , y : &$T | x . average_floor ( y )); }# [ bench ] fn naive ( b : & mut Bencher ){ let v = small (); bench_floor ( b , & v , | x : &$T , y : &$T | x . naive_average_floor ( y )); }# [ bench ] fn unchecked ( b : & mut Bencher ){ let v = small (); bench_unchecked ( b , & v , | x : &$T , y : &$T | x . unchecked_average_floor ( y )); }# [ bench ] fn modulo ( b : & mut Bencher ){ let v = small (); bench_floor ( b , & v , | x : &$T , y : &$T | x . modulo_average_floor ( y )); }} mod overflowing { use super ::*; # [ bench ] fn optimized ( b : & mut Bencher ){ let v = overflowing (); bench_floor ( b , & v , | x : &$T , y : &$T | x . average_floor ( y )); }# [ bench ] fn naive ( b : & mut Bencher ){ let v = overflowing (); bench_floor ( b , & v , | x : &$T , y : &$T | x . naive_average_floor ( y )); }# [ bench ] fn unchecked ( b : & mut Bencher ){ let v = overflowing (); bench_unchecked ( b , & v , | x : &$T , y : &$T | x . unchecked_average_floor ( y )); }# [ bench ] fn modulo ( b : & mut Bencher ){ let v = overflowing (); bench_floor ( b , & v , | x : &$T , y : &$T | x . modulo_average_floor ( y )); }} mod rand { use super ::*; # [ bench ] fn optimized ( b : & mut Bencher ){ let v = rand (); bench_floor ( b , & v , | x : &$T , y : &$T | x . average_floor ( y )); }# [ bench ] fn naive ( b : & mut Bencher ){ let v = rand (); bench_floor ( b , & v , | x : &$T , y : &$T | x . naive_average_floor ( y )); }# [ bench ] fn unchecked ( b : & mut Bencher ){ let v = rand (); bench_unchecked ( b , & v , | x : &$T , y : &$T | x . unchecked_average_floor ( y )); }# [ bench ] fn modulo ( b : & mut Bencher ){ let v = rand (); bench_floor ( b , & v , | x : &$T , y : &$T | x . modulo_average_floor ( y )); }}}})*}} +macro_rules! __ra_macro_fixture390 {($T : ident )=>{ impl super :: NaiveAverage for $T { fn naive_average_floor (& self , other : &$T )-> $T { match self . checked_add (* other ){ Some ( z )=> z . div_floor (& 2 ), None =>{ if self > other { let diff = self - other ; other + diff . div_floor (& 2 )} else { let diff = other - self ; self + diff . div_floor (& 2 )}}}} fn naive_average_ceil (& self , other : &$T )-> $T { match self . checked_add (* other ){ Some ( z )=> z . div_ceil (& 2 ), None =>{ if self > other { let diff = self - other ; self - diff . div_floor (& 2 )} else { let diff = other - self ; other - diff . div_floor (& 2 )}}}}}}; } +macro_rules! __ra_macro_fixture391 {($T : ident )=>{ impl super :: UncheckedAverage for $T { fn unchecked_average_floor (& self , other : &$T )-> $T { self . wrapping_add (* other )/ 2 } fn unchecked_average_ceil (& self , other : &$T )-> $T {( self . wrapping_add (* other )/ 2 ). wrapping_add ( 1 )}}}; } +macro_rules! __ra_macro_fixture392 {($T : ident )=>{ impl super :: ModuloAverage for $T { fn modulo_average_ceil (& self , other : &$T )-> $T { let ( q1 , r1 )= self . div_mod_floor (& 2 ); let ( q2 , r2 )= other . div_mod_floor (& 2 ); q1 + q2 + ( r1 | r2 )} fn modulo_average_floor (& self , other : &$T )-> $T { let ( q1 , r1 )= self . div_mod_floor (& 2 ); let ( q2 , r2 )= other . div_mod_floor (& 2 ); q1 + q2 + ( r1 * r2 )}}}; } +macro_rules! __ra_macro_fixture393 {($N : expr , $FUN : ident , $BENCH_NAME : ident , )=>( mod $BENCH_NAME { use super ::*; pub fn sum ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N ). collect (); c . bench_function (& ( stringify ! ($BENCH_NAME ). replace ( '_' , " " )+ " sum" ), move | b | { b . iter (|| { cloned (& v ).$FUN (| x , y | x + y )})}); } pub fn complex_iter ( c : & mut Criterion ){ let u = ( 3 ..). take ($N / 2 ); let v = ( 5 ..). take ($N / 2 ); let it = u . chain ( v ); c . bench_function (& ( stringify ! ($BENCH_NAME ). replace ( '_' , " " )+ " complex iter" ), move | b | { b . iter (|| { it . clone (). map (| x | x as f32 ).$FUN ( f32 :: atan2 )})}); } pub fn string_format ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. ($N / 4 )). collect (); c . bench_function (& ( stringify ! ($BENCH_NAME ). replace ( '_' , " " )+ " string format" ), move | b | { b . iter (|| { cloned (& v ). map (| x | x . to_string ()).$FUN (| x , y | format ! ( "{} + {}" , x , y ))})}); }} criterion_group ! ($BENCH_NAME , $BENCH_NAME :: sum , $BENCH_NAME :: complex_iter , $BENCH_NAME :: string_format , ); )} +macro_rules! __ra_macro_fixture394 {($ast : ident , $kind : ident )=>{# [ derive ( PartialEq , Eq , Hash )]# [ repr ( transparent )] struct $ast ( SyntaxNode ); impl $ast {# [ allow ( unused )] fn cast ( node : SyntaxNode )-> Option < Self > { if node . kind ()== $kind { Some ( Self ( node ))} else { None }}}}; } +macro_rules! __ra_macro_fixture395 {($I : ident , $U : ident )=>{ mod $I { mod ceil { use num_integer :: Average ; # [ test ] fn same_sign (){ assert_eq ! (( 14 as $I ). average_ceil (& 16 ), 15 as $I ); assert_eq ! (( 14 as $I ). average_ceil (& 17 ), 16 as $I ); let max = $crate :: std ::$I :: MAX ; assert_eq ! (( max - 3 ). average_ceil (& ( max - 1 )), max - 2 ); assert_eq ! (( max - 3 ). average_ceil (& ( max - 2 )), max - 2 ); }# [ test ] fn different_sign (){ assert_eq ! (( 14 as $I ). average_ceil (&- 4 ), 5 as $I ); assert_eq ! (( 14 as $I ). average_ceil (&- 5 ), 5 as $I ); let min = $crate :: std ::$I :: MIN ; let max = $crate :: std ::$I :: MAX ; assert_eq ! ( min . average_ceil (& max ), 0 as $I ); }} mod floor { use num_integer :: Average ; # [ test ] fn same_sign (){ assert_eq ! (( 14 as $I ). average_floor (& 16 ), 15 as $I ); assert_eq ! (( 14 as $I ). average_floor (& 17 ), 15 as $I ); let max = $crate :: std ::$I :: MAX ; assert_eq ! (( max - 3 ). average_floor (& ( max - 1 )), max - 2 ); assert_eq ! (( max - 3 ). average_floor (& ( max - 2 )), max - 3 ); }# [ test ] fn different_sign (){ assert_eq ! (( 14 as $I ). average_floor (&- 4 ), 5 as $I ); assert_eq ! (( 14 as $I ). average_floor (&- 5 ), 4 as $I ); let min = $crate :: std ::$I :: MIN ; let max = $crate :: std ::$I :: MAX ; assert_eq ! ( min . average_floor (& max ), - 1 as $I ); }}} mod $U { mod ceil { use num_integer :: Average ; # [ test ] fn bounded (){ assert_eq ! (( 14 as $U ). average_ceil (& 16 ), 15 as $U ); assert_eq ! (( 14 as $U ). average_ceil (& 17 ), 16 as $U ); }# [ test ] fn overflow (){ let max = $crate :: std ::$U :: MAX ; assert_eq ! (( max - 3 ). average_ceil (& ( max - 1 )), max - 2 ); assert_eq ! (( max - 3 ). average_ceil (& ( max - 2 )), max - 2 ); }} mod floor { use num_integer :: Average ; # [ test ] fn bounded (){ assert_eq ! (( 14 as $U ). average_floor (& 16 ), 15 as $U ); assert_eq ! (( 14 as $U ). average_floor (& 17 ), 15 as $U ); }# [ test ] fn overflow (){ let max = $crate :: std ::$U :: MAX ; assert_eq ! (( max - 3 ). average_floor (& ( max - 1 )), max - 2 ); assert_eq ! (( max - 3 ). average_floor (& ( max - 2 )), max - 3 ); }}}}; } +macro_rules! __ra_macro_fixture396 {($N : expr ; $BENCH_GROUP : ident , $TUPLE_FUN : ident , $TUPLES : ident , $TUPLE_WINDOWS : ident ; $SLICE_FUN : ident , $CHUNKS : ident , $WINDOWS : ident ; $FOR_CHUNKS : ident , $FOR_WINDOWS : ident )=>( fn $FOR_CHUNKS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N * 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($FOR_CHUNKS ). replace ( '_' , " " ), move | b | { b . iter (|| { let mut j = 0 ; for _ in 0 .. 1_000 { s += $SLICE_FUN (& v [ j .. ( j + $N )]); j += $N ; } s })}); } fn $FOR_WINDOWS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($FOR_WINDOWS ). replace ( '_' , " " ), move | b | { b . iter (|| { for i in 0 .. ( 1_000 - $N ){ s += $SLICE_FUN (& v [ i .. ( i + $N )]); } s })}); } fn $TUPLES ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N * 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($TUPLES ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . iter (). tuples (){ s += $TUPLE_FUN (& x ); } s })}); } fn $CHUNKS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N * 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($CHUNKS ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . chunks ($N ){ s += $SLICE_FUN ( x ); } s })}); } fn $TUPLE_WINDOWS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($TUPLE_WINDOWS ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . iter (). tuple_windows (){ s += $TUPLE_FUN (& x ); } s })}); } fn $WINDOWS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($WINDOWS ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . windows ($N ){ s += $SLICE_FUN ( x ); } s })}); } criterion_group ! ($BENCH_GROUP , $FOR_CHUNKS , $FOR_WINDOWS , $TUPLES , $CHUNKS , $TUPLE_WINDOWS , $WINDOWS , ); )} +macro_rules! __ra_macro_fixture397 {($N : expr , $FUN : ident , $BENCH_NAME : ident , )=>( mod $BENCH_NAME { use super ::*; pub fn sum ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N ). collect (); c . bench_function (& ( stringify ! ($BENCH_NAME ). replace ( '_' , " " )+ " sum" ), move | b | { b . iter (|| { cloned (& v ).$FUN (| x , y | x + y )})}); } pub fn complex_iter ( c : & mut Criterion ){ let u = ( 3 ..). take ($N / 2 ); let v = ( 5 ..). take ($N / 2 ); let it = u . chain ( v ); c . bench_function (& ( stringify ! ($BENCH_NAME ). replace ( '_' , " " )+ " complex iter" ), move | b | { b . iter (|| { it . clone (). map (| x | x as f32 ).$FUN ( f32 :: atan2 )})}); } pub fn string_format ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. ($N / 4 )). collect (); c . bench_function (& ( stringify ! ($BENCH_NAME ). replace ( '_' , " " )+ " string format" ), move | b | { b . iter (|| { cloned (& v ). map (| x | x . to_string ()).$FUN (| x , y | format ! ( "{} + {}" , x , y ))})}); }} criterion_group ! ($BENCH_NAME , $BENCH_NAME :: sum , $BENCH_NAME :: complex_iter , $BENCH_NAME :: string_format , ); )} +macro_rules! __ra_macro_fixture398 {($N : expr ; $BENCH_GROUP : ident , $TUPLE_FUN : ident , $TUPLES : ident , $TUPLE_WINDOWS : ident ; $SLICE_FUN : ident , $CHUNKS : ident , $WINDOWS : ident ; $FOR_CHUNKS : ident , $FOR_WINDOWS : ident )=>( fn $FOR_CHUNKS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N * 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($FOR_CHUNKS ). replace ( '_' , " " ), move | b | { b . iter (|| { let mut j = 0 ; for _ in 0 .. 1_000 { s += $SLICE_FUN (& v [ j .. ( j + $N )]); j += $N ; } s })}); } fn $FOR_WINDOWS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($FOR_WINDOWS ). replace ( '_' , " " ), move | b | { b . iter (|| { for i in 0 .. ( 1_000 - $N ){ s += $SLICE_FUN (& v [ i .. ( i + $N )]); } s })}); } fn $TUPLES ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N * 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($TUPLES ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . iter (). tuples (){ s += $TUPLE_FUN (& x ); } s })}); } fn $CHUNKS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. $N * 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($CHUNKS ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . chunks ($N ){ s += $SLICE_FUN ( x ); } s })}); } fn $TUPLE_WINDOWS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($TUPLE_WINDOWS ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . iter (). tuple_windows (){ s += $TUPLE_FUN (& x ); } s })}); } fn $WINDOWS ( c : & mut Criterion ){ let v : Vec < u32 > = ( 0 .. 1_000 ). collect (); let mut s = 0 ; c . bench_function (& stringify ! ($WINDOWS ). replace ( '_' , " " ), move | b | { b . iter (|| { for x in v . windows ($N ){ s += $SLICE_FUN ( x ); } s })}); } criterion_group ! ($BENCH_GROUP , $FOR_CHUNKS , $FOR_WINDOWS , $TUPLES , $CHUNKS , $TUPLE_WINDOWS , $WINDOWS , ); )} +macro_rules! __ra_macro_fixture399 {($name : ident : $e : expr )=>{# [ cfg_attr ( target_arch = "wasm32" , wasm_bindgen_test :: wasm_bindgen_test )]# [ test ] fn $name (){ let ( subscriber , handle )= subscriber :: mock (). event ( event :: mock (). with_fields ( field :: mock ( "answer" ). with_value (& 42 ). and ( field :: mock ( "to_question" ). with_value (& "life, the universe, and everything" ), ). only (), ), ). done (). run_with_handle (); with_default ( subscriber , || { info ! ( answer = $e , to_question = "life, the universe, and everything" ); }); handle . assert_finished (); }}; } +macro_rules! __ra_macro_fixture400 {($T : ty )=>{ impl GcdOld for $T {# [ doc = " Calculates the Greatest Common Divisor (GCD) of the number and" ]# [ doc = " `other`. The result is always positive." ]# [ inline ] fn gcd_old (& self , other : & Self )-> Self { let mut m = * self ; let mut n = * other ; if m == 0 || n == 0 { return ( m | n ). abs (); } let shift = ( m | n ). trailing_zeros (); if m == Self :: min_value ()|| n == Self :: min_value (){ return ( 1 << shift ). abs (); } m = m . abs (); n = n . abs (); n >>= n . trailing_zeros (); while m != 0 { m >>= m . trailing_zeros (); if n > m { std :: mem :: swap (& mut n , & mut m )} m -= n ; } n << shift }}}; } +macro_rules! __ra_macro_fixture401 {($T : ty )=>{ impl GcdOld for $T {# [ doc = " Calculates the Greatest Common Divisor (GCD) of the number and" ]# [ doc = " `other`. The result is always positive." ]# [ inline ] fn gcd_old (& self , other : & Self )-> Self { let mut m = * self ; let mut n = * other ; if m == 0 || n == 0 { return m | n ; } let shift = ( m | n ). trailing_zeros (); n >>= n . trailing_zeros (); while m != 0 { m >>= m . trailing_zeros (); if n > m { std :: mem :: swap (& mut n , & mut m )} m -= n ; } n << shift }}}; } +macro_rules! __ra_macro_fixture402 {($T : ident )=>{ mod $T { use crate :: { run_bench , GcdOld }; use num_integer :: Integer ; use test :: Bencher ; # [ bench ] fn bench_gcd ( b : & mut Bencher ){ run_bench ( b , $T :: gcd ); }# [ bench ] fn bench_gcd_old ( b : & mut Bencher ){ run_bench ( b , $T :: gcd_old ); }}}; } +macro_rules! __ra_macro_fixture403 {($f : ident , $($t : ty ),+)=>{$(paste :: item ! { qc :: quickcheck ! { fn [< $f _ $t >]( i : RandIter <$t >, k : u16 )-> (){$f ( i , k )}}})+ }; } +macro_rules! __ra_macro_fixture404 {($name : ident )=>{# [ derive ( Debug )] struct $name { message : & 'static str , drop : DetectDrop , } impl Display for $name { fn fmt (& self , f : & mut fmt :: Formatter )-> fmt :: Result { f . write_str ( self . message )}}}; } +macro_rules! __ra_macro_fixture405 {($($(# [$attr : meta ])* $name : ident ($value : expr )),* )=>{ mod bench_itoa_write { use test :: { Bencher , black_box }; $($(# [$attr ])* # [ bench ] fn $name ( b : & mut Bencher ){ use itoa ; let mut buf = Vec :: with_capacity ( 40 ); b . iter (|| { buf . clear (); itoa :: write (& mut buf , black_box ($value )). unwrap ()}); })* } mod bench_itoa_fmt { use test :: { Bencher , black_box }; $($(# [$attr ])* # [ bench ] fn $name ( b : & mut Bencher ){ use itoa ; let mut buf = String :: with_capacity ( 40 ); b . iter (|| { buf . clear (); itoa :: fmt (& mut buf , black_box ($value )). unwrap ()}); })* } mod bench_std_fmt { use test :: { Bencher , black_box }; $($(# [$attr ])* # [ bench ] fn $name ( b : & mut Bencher ){ use std :: io :: Write ; let mut buf = Vec :: with_capacity ( 40 ); b . iter (|| { buf . clear (); write ! (& mut buf , "{}" , black_box ($value )). unwrap ()}); })* }}} +macro_rules! __ra_macro_fixture406 {($typ : ty {$($b_name : ident =>$g_name : ident ($($args : expr ),*),)* })=>{$(# [ bench ] fn $b_name ( b : & mut Bencher ){$g_name ::<$typ > ($($args ,)* b )})* }} +macro_rules! __ra_macro_fixture407 {($($T : ident ),*)=>{$(mod $T { use test :: Bencher ; use num_integer :: Roots ; # [ bench ] fn sqrt_rand ( b : & mut Bencher ){:: bench_rand_pos ( b , $T :: sqrt , 2 ); }# [ bench ] fn sqrt_small ( b : & mut Bencher ){:: bench_small_pos ( b , $T :: sqrt , 2 ); }# [ bench ] fn cbrt_rand ( b : & mut Bencher ){:: bench_rand ( b , $T :: cbrt , 3 ); }# [ bench ] fn cbrt_small ( b : & mut Bencher ){:: bench_small ( b , $T :: cbrt , 3 ); }# [ bench ] fn fourth_root_rand ( b : & mut Bencher ){:: bench_rand_pos ( b , | x : &$T | x . nth_root ( 4 ), 4 ); }# [ bench ] fn fourth_root_small ( b : & mut Bencher ){:: bench_small_pos ( b , | x : &$T | x . nth_root ( 4 ), 4 ); }# [ bench ] fn fifth_root_rand ( b : & mut Bencher ){:: bench_rand ( b , | x : &$T | x . nth_root ( 5 ), 5 ); }# [ bench ] fn fifth_root_small ( b : & mut Bencher ){:: bench_small ( b , | x : &$T | x . nth_root ( 5 ), 5 ); }})*}} +macro_rules! __ra_macro_fixture408 {($name : ident , $level : expr )=>{# [ doc = " Creates a new `Diagnostic` with the given `message` at the span" ]# [ doc = " `self`." ] pub fn $name < T : Into < String >> ( self , message : T )-> Diagnostic { Diagnostic :: spanned ( self , $level , message )}}; } +macro_rules! __ra_macro_fixture409 {($($name : ident =>$kind : ident ,)*)=>($(# [ doc = " Creates a new suffixed integer literal with the specified value." ]# [ doc = "" ]# [ doc = " This function will create an integer like `1u32` where the integer" ]# [ doc = " value specified is the first part of the token and the integral is" ]# [ doc = " also suffixed at the end." ]# [ doc = " Literals created from negative numbers may not survive round-trips through" ]# [ doc = " `TokenStream` or strings and may be broken into two tokens (`-` and positive literal)." ]# [ doc = "" ]# [ doc = " Literals created through this method have the `Span::call_site()`" ]# [ doc = " span by default, which can be configured with the `set_span` method" ]# [ doc = " below." ] pub fn $name ( n : $kind )-> Literal { Literal ( bridge :: client :: Literal :: typed_integer (& n . to_string (), stringify ! ($kind )))})*)} +macro_rules! __ra_macro_fixture410 {($($name : ident =>$kind : ident ,)*)=>($(# [ doc = " Creates a new unsuffixed integer literal with the specified value." ]# [ doc = "" ]# [ doc = " This function will create an integer like `1` where the integer" ]# [ doc = " value specified is the first part of the token. No suffix is" ]# [ doc = " specified on this token, meaning that invocations like" ]# [ doc = " `Literal::i8_unsuffixed(1)` are equivalent to" ]# [ doc = " `Literal::u32_unsuffixed(1)`." ]# [ doc = " Literals created from negative numbers may not survive rountrips through" ]# [ doc = " `TokenStream` or strings and may be broken into two tokens (`-` and positive literal)." ]# [ doc = "" ]# [ doc = " Literals created through this method have the `Span::call_site()`" ]# [ doc = " span by default, which can be configured with the `set_span` method" ]# [ doc = " below." ] pub fn $name ( n : $kind )-> Literal { Literal ( bridge :: client :: Literal :: integer (& n . to_string ()))})*)} +macro_rules! __ra_macro_fixture411 {($spanned : ident , $regular : ident , $level : expr )=>{# [ doc = " Adds a new child diagnostic message to `self` with the level" ]# [ doc = " identified by this method\\\'s name with the given `spans` and" ]# [ doc = " `message`." ] pub fn $spanned < S , T > ( mut self , spans : S , message : T )-> Diagnostic where S : MultiSpan , T : Into < String >, { self . children . push ( Diagnostic :: spanned ( spans , $level , message )); self }# [ doc = " Adds a new child diagnostic message to `self` with the level" ]# [ doc = " identified by this method\\\'s name with the given `message`." ] pub fn $regular < T : Into < String >> ( mut self , message : T )-> Diagnostic { self . children . push ( Diagnostic :: new ($level , message )); self }}; } +macro_rules! __ra_macro_fixture412 {($($arg : tt )*)=>{{ let res = $crate :: fmt :: format ($crate :: __export :: format_args ! ($($arg )*)); res }}} +macro_rules! __ra_macro_fixture413 {($dst : expr , $($arg : tt )*)=>($dst . write_fmt ($crate :: format_args ! ($($arg )*)))} +macro_rules! __ra_macro_fixture414 {($dst : expr $(,)?)=>($crate :: write ! ($dst , "\n" )); ($dst : expr , $($arg : tt )*)=>($dst . write_fmt ($crate :: format_args_nl ! ($($arg )*))); } +macro_rules! __ra_macro_fixture415 {($($name : ident =>$kind : ident ,)*)=>($(# [ doc = " Creates a new suffixed integer literal with the specified value." ]# [ doc = "" ]# [ doc = " This function will create an integer like `1u32` where the integer" ]# [ doc = " value specified is the first part of the token and the integral is" ]# [ doc = " also suffixed at the end. Literals created from negative numbers may" ]# [ doc = " not survive rountrips through `TokenStream` or strings and may be" ]# [ doc = " broken into two tokens (`-` and positive literal)." ]# [ doc = "" ]# [ doc = " Literals created through this method have the `Span::call_site()`" ]# [ doc = " span by default, which can be configured with the `set_span` method" ]# [ doc = " below." ] pub fn $name ( n : $kind )-> Literal { Literal :: _new ( imp :: Literal ::$name ( n ))})*)} +macro_rules! __ra_macro_fixture416 {($($name : ident =>$kind : ident ,)*)=>($(# [ doc = " Creates a new unsuffixed integer literal with the specified value." ]# [ doc = "" ]# [ doc = " This function will create an integer like `1` where the integer" ]# [ doc = " value specified is the first part of the token. No suffix is" ]# [ doc = " specified on this token, meaning that invocations like" ]# [ doc = " `Literal::i8_unsuffixed(1)` are equivalent to" ]# [ doc = " `Literal::u32_unsuffixed(1)`. Literals created from negative numbers" ]# [ doc = " may not survive rountrips through `TokenStream` or strings and may" ]# [ doc = " be broken into two tokens (`-` and positive literal)." ]# [ doc = "" ]# [ doc = " Literals created through this method have the `Span::call_site()`" ]# [ doc = " span by default, which can be configured with the `set_span` method" ]# [ doc = " below." ] pub fn $name ( n : $kind )-> Literal { Literal :: _new ( imp :: Literal ::$name ( n ))})*)} +macro_rules! __ra_macro_fixture417 {($($name : ident =>$kind : ident ,)*)=>($(pub fn $name ( n : $kind )-> Literal { Literal :: _new ( format ! ( concat ! ( "{}" , stringify ! ($kind )), n ))})*)} +macro_rules! __ra_macro_fixture418 {($($name : ident =>$kind : ident ,)*)=>($(pub fn $name ( n : $kind )-> Literal { Literal :: _new ( n . to_string ())})*)} +macro_rules! __ra_macro_fixture419 {(<$visitor : ident : Visitor <$lifetime : tt >> $($func : ident )*)=>{$(forward_to_deserialize_any_helper ! {$func <$lifetime , $visitor >})* }; ($($func : ident )*)=>{$(forward_to_deserialize_any_helper ! {$func < 'de , V >})* }; } +macro_rules! __ra_macro_fixture420 {( bool <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_bool <$l , $v > ()}}; ( i8 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_i8 <$l , $v > ()}}; ( i16 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_i16 <$l , $v > ()}}; ( i32 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_i32 <$l , $v > ()}}; ( i64 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_i64 <$l , $v > ()}}; ( i128 <$l : tt , $v : ident >)=>{ serde_if_integer128 ! { forward_to_deserialize_any_method ! { deserialize_i128 <$l , $v > ()}}}; ( u8 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_u8 <$l , $v > ()}}; ( u16 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_u16 <$l , $v > ()}}; ( u32 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_u32 <$l , $v > ()}}; ( u64 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_u64 <$l , $v > ()}}; ( u128 <$l : tt , $v : ident >)=>{ serde_if_integer128 ! { forward_to_deserialize_any_method ! { deserialize_u128 <$l , $v > ()}}}; ( f32 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_f32 <$l , $v > ()}}; ( f64 <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_f64 <$l , $v > ()}}; ( char <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_char <$l , $v > ()}}; ( str <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_str <$l , $v > ()}}; ( string <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_string <$l , $v > ()}}; ( bytes <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_bytes <$l , $v > ()}}; ( byte_buf <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_byte_buf <$l , $v > ()}}; ( option <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_option <$l , $v > ()}}; ( unit <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_unit <$l , $v > ()}}; ( unit_struct <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_unit_struct <$l , $v > ( name : & 'static str )}}; ( newtype_struct <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_newtype_struct <$l , $v > ( name : & 'static str )}}; ( seq <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_seq <$l , $v > ()}}; ( tuple <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_tuple <$l , $v > ( len : usize )}}; ( tuple_struct <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_tuple_struct <$l , $v > ( name : & 'static str , len : usize )}}; ( map <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_map <$l , $v > ()}}; ( struct <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_struct <$l , $v > ( name : & 'static str , fields : & 'static [& 'static str ])}}; ( enum <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_enum <$l , $v > ( name : & 'static str , variants : & 'static [& 'static str ])}}; ( identifier <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_identifier <$l , $v > ()}}; ( ignored_any <$l : tt , $v : ident >)=>{ forward_to_deserialize_any_method ! { deserialize_ignored_any <$l , $v > ()}}; } +macro_rules! __ra_macro_fixture421 {($func : ident <$l : tt , $v : ident > ($($arg : ident : $ty : ty ),*))=>{# [ inline ] fn $func <$v > ( self , $($arg : $ty ,)* visitor : $v )-> $crate :: __private :: Result <$v :: Value , Self :: Error > where $v : $crate :: de :: Visitor <$l >, {$(let _ = $arg ; )* self . deserialize_any ( visitor )}}; } +macro_rules! __ra_macro_fixture422 {($($f : ident : $t : ty ,)*)=>{$(fn $f ( self , v : $t )-> fmt :: Result { Display :: fmt (& v , self )})* }; } +macro_rules! __ra_macro_fixture423 {($name : ident , $level : expr )=>{# [ doc = " Creates a new `Diagnostic` with the given `message` at the span" ]# [ doc = " `self`." ]# [ unstable ( feature = "proc_macro_diagnostic" , issue = "54140" )] pub fn $name < T : Into < String >> ( self , message : T )-> Diagnostic { Diagnostic :: spanned ( self , $level , message )}}; } +macro_rules! __ra_macro_fixture424 {($($name : ident =>$kind : ident ,)*)=>($(# [ doc = " Creates a new suffixed integer literal with the specified value." ]# [ doc = "" ]# [ doc = " This function will create an integer like `1u32` where the integer" ]# [ doc = " value specified is the first part of the token and the integral is" ]# [ doc = " also suffixed at the end." ]# [ doc = " Literals created from negative numbers may not survive round-trips through" ]# [ doc = " `TokenStream` or strings and may be broken into two tokens (`-` and positive literal)." ]# [ doc = "" ]# [ doc = " Literals created through this method have the `Span::call_site()`" ]# [ doc = " span by default, which can be configured with the `set_span` method" ]# [ doc = " below." ]# [ stable ( feature = "proc_macro_lib2" , since = "1.29.0" )] pub fn $name ( n : $kind )-> Literal { Literal ( bridge :: client :: Literal :: typed_integer (& n . to_string (), stringify ! ($kind )))})*)} +macro_rules! __ra_macro_fixture425 {($($name : ident =>$kind : ident ,)*)=>($(# [ doc = " Creates a new unsuffixed integer literal with the specified value." ]# [ doc = "" ]# [ doc = " This function will create an integer like `1` where the integer" ]# [ doc = " value specified is the first part of the token. No suffix is" ]# [ doc = " specified on this token, meaning that invocations like" ]# [ doc = " `Literal::i8_unsuffixed(1)` are equivalent to" ]# [ doc = " `Literal::u32_unsuffixed(1)`." ]# [ doc = " Literals created from negative numbers may not survive rountrips through" ]# [ doc = " `TokenStream` or strings and may be broken into two tokens (`-` and positive literal)." ]# [ doc = "" ]# [ doc = " Literals created through this method have the `Span::call_site()`" ]# [ doc = " span by default, which can be configured with the `set_span` method" ]# [ doc = " below." ]# [ stable ( feature = "proc_macro_lib2" , since = "1.29.0" )] pub fn $name ( n : $kind )-> Literal { Literal ( bridge :: client :: Literal :: integer (& n . to_string ()))})*)} +macro_rules! __ra_macro_fixture426 {( type FreeFunctions )=>( type FreeFunctions : 'static ;); ( type TokenStream )=>( type TokenStream : 'static + Clone ;); ( type TokenStreamBuilder )=>( type TokenStreamBuilder : 'static ;); ( type TokenStreamIter )=>( type TokenStreamIter : 'static + Clone ;); ( type Group )=>( type Group : 'static + Clone ;); ( type Punct )=>( type Punct : 'static + Copy + Eq + Hash ;); ( type Ident )=>( type Ident : 'static + Copy + Eq + Hash ;); ( type Literal )=>( type Literal : 'static + Clone ;); ( type SourceFile )=>( type SourceFile : 'static + Clone ;); ( type MultiSpan )=>( type MultiSpan : 'static ;); ( type Diagnostic )=>( type Diagnostic : 'static ;); ( type Span )=>( type Span : 'static + Copy + Eq + Hash ;); ( fn drop (& mut self , $arg : ident : $arg_ty : ty ))=>( fn drop (& mut self , $arg : $arg_ty ){ mem :: drop ($arg )}); ( fn clone (& mut self , $arg : ident : $arg_ty : ty )-> $ret_ty : ty )=>( fn clone (& mut self , $arg : $arg_ty )-> $ret_ty {$arg . clone ()}); ($($item : tt )*)=>($($item )*;)} +macro_rules! __ra_macro_fixture427 {($spanned : ident , $regular : ident , $level : expr )=>{# [ doc = " Adds a new child diagnostic message to `self` with the level" ]# [ doc = " identified by this method\\\'s name with the given `spans` and" ]# [ doc = " `message`." ]# [ unstable ( feature = "proc_macro_diagnostic" , issue = "54140" )] pub fn $spanned < S , T > ( mut self , spans : S , message : T )-> Diagnostic where S : MultiSpan , T : Into < String >, { self . children . push ( Diagnostic :: spanned ( spans , $level , message )); self }# [ doc = " Adds a new child diagnostic message to `self` with the level" ]# [ doc = " identified by this method\\\'s name with the given `message`." ]# [ unstable ( feature = "proc_macro_diagnostic" , issue = "54140" )] pub fn $regular < T : Into < String >> ( mut self , message : T )-> Diagnostic { self . children . push ( Diagnostic :: new ($level , message )); self }}; } +macro_rules! __ra_macro_fixture428 {($SelfT : ty , $ActualT : ident , $UnsignedT : ty , $BITS : expr , $Min : expr , $Max : expr , $Feature : expr , $EndFeature : expr , $rot : expr , $rot_op : expr , $rot_result : expr , $swap_op : expr , $swapped : expr , $reversed : expr , $le_bytes : expr , $be_bytes : expr , $to_xe_bytes_doc : expr , $from_xe_bytes_doc : expr )=>{ doc_comment ! { concat ! ( "The smallest value that can be represented by this integer type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MIN, " , stringify ! ($Min ), ");" , $EndFeature , "\n```" ), # [ stable ( feature = "assoc_int_consts" , since = "1.43.0" )] pub const MIN : Self = ! 0 ^ ((! 0 as $UnsignedT )>> 1 ) as Self ; } doc_comment ! { concat ! ( "The largest value that can be represented by this integer type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MAX, " , stringify ! ($Max ), ");" , $EndFeature , "\n```" ), # [ stable ( feature = "assoc_int_consts" , since = "1.43.0" )] pub const MAX : Self = ! Self :: MIN ; } doc_comment ! { concat ! ( "The size of this integer type in bits.\n\n# Examples\n\n```\n" , $Feature , "#![feature(int_bits_const)]\nassert_eq!(" , stringify ! ($SelfT ), "::BITS, " , stringify ! ($BITS ), ");" , $EndFeature , "\n```" ), # [ unstable ( feature = "int_bits_const" , issue = "76904" )] pub const BITS : u32 = $BITS ; } doc_comment ! { concat ! ( "Converts a string slice in a given base to an integer.\n\nThe string is expected to be an optional `+` or `-` sign followed by digits.\nLeading and trailing whitespace represent an error. Digits are a subset of these characters,\ndepending on `radix`:\n\n * `0-9`\n * `a-z`\n * `A-Z`\n\n# Panics\n\nThis function panics if `radix` is not in the range from 2 to 36.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::from_str_radix(\"A\", 16), Ok(10));" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )] pub fn from_str_radix ( src : & str , radix : u32 )-> Result < Self , ParseIntError > { from_str_radix ( src , radix )}} doc_comment ! { concat ! ( "Returns the number of ones in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0b100_0000" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.count_ones(), 1);" , $EndFeature , "\n```\n" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn count_ones ( self )-> u32 {( self as $UnsignedT ). count_ones ()}} doc_comment ! { concat ! ( "Returns the number of zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MAX.count_zeros(), 1);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn count_zeros ( self )-> u32 {(! self ). count_ones ()}} doc_comment ! { concat ! ( "Returns the number of leading zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = -1" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.leading_zeros(), 0);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn leading_zeros ( self )-> u32 {( self as $UnsignedT ). leading_zeros ()}} doc_comment ! { concat ! ( "Returns the number of trailing zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = -4" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.trailing_zeros(), 2);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn trailing_zeros ( self )-> u32 {( self as $UnsignedT ). trailing_zeros ()}} doc_comment ! { concat ! ( "Returns the number of leading ones in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = -1" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.leading_ones(), " , stringify ! ($BITS ), ");" , $EndFeature , "\n```" ), # [ stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ rustc_const_stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ inline ] pub const fn leading_ones ( self )-> u32 {( self as $UnsignedT ). leading_ones ()}} doc_comment ! { concat ! ( "Returns the number of trailing ones in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 3" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.trailing_ones(), 2);" , $EndFeature , "\n```" ), # [ stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ rustc_const_stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ inline ] pub const fn trailing_ones ( self )-> u32 {( self as $UnsignedT ). trailing_ones ()}} doc_comment ! { concat ! ( "Shifts the bits to the left by a specified amount, `n`,\nwrapping the truncated bits to the end of the resulting integer.\n\nPlease note this isn't the same operation as the `<<` shifting operator!\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $rot_op , stringify ! ($SelfT ), ";\nlet m = " , $rot_result , ";\n\nassert_eq!(n.rotate_left(" , $rot , "), m);\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn rotate_left ( self , n : u32 )-> Self {( self as $UnsignedT ). rotate_left ( n ) as Self }} doc_comment ! { concat ! ( "Shifts the bits to the right by a specified amount, `n`,\nwrapping the truncated bits to the beginning of the resulting\ninteger.\n\nPlease note this isn't the same operation as the `>>` shifting operator!\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $rot_result , stringify ! ($SelfT ), ";\nlet m = " , $rot_op , ";\n\nassert_eq!(n.rotate_right(" , $rot , "), m);\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn rotate_right ( self , n : u32 )-> Self {( self as $UnsignedT ). rotate_right ( n ) as Self }} doc_comment ! { concat ! ( "Reverses the byte order of the integer.\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $swap_op , stringify ! ($SelfT ), ";\n\nlet m = n.swap_bytes();\n\nassert_eq!(m, " , $swapped , ");\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn swap_bytes ( self )-> Self {( self as $UnsignedT ). swap_bytes () as Self }} doc_comment ! { concat ! ( "Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,\n second least-significant bit becomes second most-significant bit, etc.\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $swap_op , stringify ! ($SelfT ), ";\nlet m = n.reverse_bits();\n\nassert_eq!(m, " , $reversed , ");\nassert_eq!(0, 0" , stringify ! ($SelfT ), ".reverse_bits());\n```" ), # [ stable ( feature = "reverse_bits" , since = "1.37.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ]# [ must_use ] pub const fn reverse_bits ( self )-> Self {( self as $UnsignedT ). reverse_bits () as Self }} doc_comment ! { concat ! ( "Converts an integer from big endian to the target's endianness.\n\nOn big endian this is a no-op. On little endian the bytes are swapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(" , stringify ! ($SelfT ), "::from_be(n), n)\n} else {\n assert_eq!(" , stringify ! ($SelfT ), "::from_be(n), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_conversions" , since = "1.32.0" )]# [ inline ] pub const fn from_be ( x : Self )-> Self {# [ cfg ( target_endian = "big" )]{ x }# [ cfg ( not ( target_endian = "big" ))]{ x . swap_bytes ()}}} doc_comment ! { concat ! ( "Converts an integer from little endian to the target's endianness.\n\nOn little endian this is a no-op. On big endian the bytes are swapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(" , stringify ! ($SelfT ), "::from_le(n), n)\n} else {\n assert_eq!(" , stringify ! ($SelfT ), "::from_le(n), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_conversions" , since = "1.32.0" )]# [ inline ] pub const fn from_le ( x : Self )-> Self {# [ cfg ( target_endian = "little" )]{ x }# [ cfg ( not ( target_endian = "little" ))]{ x . swap_bytes ()}}} doc_comment ! { concat ! ( "Converts `self` to big endian from the target's endianness.\n\nOn big endian this is a no-op. On little endian the bytes are swapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(n.to_be(), n)\n} else {\n assert_eq!(n.to_be(), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_conversions" , since = "1.32.0" )]# [ inline ] pub const fn to_be ( self )-> Self {# [ cfg ( target_endian = "big" )]{ self }# [ cfg ( not ( target_endian = "big" ))]{ self . swap_bytes ()}}} doc_comment ! { concat ! ( "Converts `self` to little endian from the target's endianness.\n\nOn little endian this is a no-op. On big endian the bytes are swapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(n.to_le(), n)\n} else {\n assert_eq!(n.to_le(), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_conversions" , since = "1.32.0" )]# [ inline ] pub const fn to_le ( self )-> Self {# [ cfg ( target_endian = "little" )]{ self }# [ cfg ( not ( target_endian = "little" ))]{ self . swap_bytes ()}}} doc_comment ! { concat ! ( "Checked integer addition. Computes `self + rhs`, returning `None`\nif overflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!((" , stringify ! ($SelfT ), "::MAX - 2).checked_add(1), Some(" , stringify ! ($SelfT ), "::MAX - 1));\nassert_eq!((" , stringify ! ($SelfT ), "::MAX - 2).checked_add(3), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_add ( self , rhs : Self )-> Option < Self > { let ( a , b )= self . overflowing_add ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Unchecked integer addition. Computes `self + rhs`, assuming overflow\ncannot occur. This results in undefined behavior when `self + rhs > " , stringify ! ($SelfT ), "::MAX` or `self + rhs < " , stringify ! ($SelfT ), "::MIN`." ), # [ unstable ( feature = "unchecked_math" , reason = "niche optimization path" , issue = "none" , )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub unsafe fn unchecked_add ( self , rhs : Self )-> Self { unsafe { intrinsics :: unchecked_add ( self , rhs )}}} doc_comment ! { concat ! ( "Checked integer subtraction. Computes `self - rhs`, returning `None` if\noverflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!((" , stringify ! ($SelfT ), "::MIN + 2).checked_sub(1), Some(" , stringify ! ($SelfT ), "::MIN + 1));\nassert_eq!((" , stringify ! ($SelfT ), "::MIN + 2).checked_sub(3), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_sub ( self , rhs : Self )-> Option < Self > { let ( a , b )= self . overflowing_sub ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Unchecked integer subtraction. Computes `self - rhs`, assuming overflow\ncannot occur. This results in undefined behavior when `self - rhs > " , stringify ! ($SelfT ), "::MAX` or `self - rhs < " , stringify ! ($SelfT ), "::MIN`." ), # [ unstable ( feature = "unchecked_math" , reason = "niche optimization path" , issue = "none" , )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub unsafe fn unchecked_sub ( self , rhs : Self )-> Self { unsafe { intrinsics :: unchecked_sub ( self , rhs )}}} doc_comment ! { concat ! ( "Checked integer multiplication. Computes `self * rhs`, returning `None` if\noverflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MAX.checked_mul(1), Some(" , stringify ! ($SelfT ), "::MAX));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.checked_mul(2), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_mul ( self , rhs : Self )-> Option < Self > { let ( a , b )= self . overflowing_mul ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Unchecked integer multiplication. Computes `self * rhs`, assuming overflow\ncannot occur. This results in undefined behavior when `self * rhs > " , stringify ! ($SelfT ), "::MAX` or `self * rhs < " , stringify ! ($SelfT ), "::MIN`." ), # [ unstable ( feature = "unchecked_math" , reason = "niche optimization path" , issue = "none" , )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub unsafe fn unchecked_mul ( self , rhs : Self )-> Self { unsafe { intrinsics :: unchecked_mul ( self , rhs )}}} doc_comment ! { concat ! ( "Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`\nor the division results in overflow.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!((" , stringify ! ($SelfT ), "::MIN + 1).checked_div(-1), Some(" , stringify ! ($Max ), "));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.checked_div(-1), None);\nassert_eq!((1" , stringify ! ($SelfT ), ").checked_div(0), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_unstable ( feature = "const_checked_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_div ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 || ( self == Self :: MIN && rhs == - 1 )){ None } else { Some ( unsafe { intrinsics :: unchecked_div ( self , rhs )})}}} doc_comment ! { concat ! ( "Checked Euclidean division. Computes `self.div_euclid(rhs)`,\nreturning `None` if `rhs == 0` or the division results in overflow.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!((" , stringify ! ($SelfT ), "::MIN + 1).checked_div_euclid(-1), Some(" , stringify ! ($Max ), "));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.checked_div_euclid(-1), None);\nassert_eq!((1" , stringify ! ($SelfT ), ").checked_div_euclid(0), None);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_div_euclid ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 || ( self == Self :: MIN && rhs == - 1 )){ None } else { Some ( self . div_euclid ( rhs ))}}} doc_comment ! { concat ! ( "Checked integer remainder. Computes `self % rhs`, returning `None` if\n`rhs == 0` or the division results in overflow.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem(2), Some(1));\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem(0), None);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.checked_rem(-1), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_unstable ( feature = "const_checked_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_rem ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 || ( self == Self :: MIN && rhs == - 1 )){ None } else { Some ( unsafe { intrinsics :: unchecked_rem ( self , rhs )})}}} doc_comment ! { concat ! ( "Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`\nif `rhs == 0` or the division results in overflow.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem_euclid(2), Some(1));\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem_euclid(0), None);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.checked_rem_euclid(-1), None);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_rem_euclid ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 || ( self == Self :: MIN && rhs == - 1 )){ None } else { Some ( self . rem_euclid ( rhs ))}}} doc_comment ! { concat ! ( "Checked negation. Computes `-self`, returning `None` if `self == MIN`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_neg(), Some(-5));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.checked_neg(), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn checked_neg ( self )-> Option < Self > { let ( a , b )= self . overflowing_neg (); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger\nthan or equal to the number of bits in `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0x1" , stringify ! ($SelfT ), ".checked_shl(4), Some(0x10));\nassert_eq!(0x1" , stringify ! ($SelfT ), ".checked_shl(129), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_shl ( self , rhs : u32 )-> Option < Self > { let ( a , b )= self . overflowing_shl ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is\nlarger than or equal to the number of bits in `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0x10" , stringify ! ($SelfT ), ".checked_shr(4), Some(0x1));\nassert_eq!(0x10" , stringify ! ($SelfT ), ".checked_shr(128), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_shr ( self , rhs : u32 )-> Option < Self > { let ( a , b )= self . overflowing_shr ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Checked absolute value. Computes `self.abs()`, returning `None` if\n`self == MIN`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!((-5" , stringify ! ($SelfT ), ").checked_abs(), Some(5));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.checked_abs(), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_abs" , since = "1.13.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn checked_abs ( self )-> Option < Self > { if self . is_negative (){ self . checked_neg ()} else { Some ( self )}}} doc_comment ! { concat ! ( "Checked exponentiation. Computes `self.pow(exp)`, returning `None` if\noverflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(8" , stringify ! ($SelfT ), ".checked_pow(2), Some(64));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.checked_pow(2), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_pow ( self , mut exp : u32 )-> Option < Self > { if exp == 0 { return Some ( 1 ); } let mut base = self ; let mut acc : Self = 1 ; while exp > 1 { if ( exp & 1 )== 1 { acc = try_opt ! ( acc . checked_mul ( base )); } exp /= 2 ; base = try_opt ! ( base . checked_mul ( base )); } Some ( try_opt ! ( acc . checked_mul ( base )))}} doc_comment ! { concat ! ( "Saturating integer addition. Computes `self + rhs`, saturating at the numeric\nbounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".saturating_add(1), 101);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.saturating_add(100), " , stringify ! ($SelfT ), "::MAX);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_add(-1), " , stringify ! ($SelfT ), "::MIN);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn saturating_add ( self , rhs : Self )-> Self { intrinsics :: saturating_add ( self , rhs )}} doc_comment ! { concat ! ( "Saturating integer subtraction. Computes `self - rhs`, saturating at the\nnumeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".saturating_sub(127), -27);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_sub(100), " , stringify ! ($SelfT ), "::MIN);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.saturating_sub(-1), " , stringify ! ($SelfT ), "::MAX);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn saturating_sub ( self , rhs : Self )-> Self { intrinsics :: saturating_sub ( self , rhs )}} doc_comment ! { concat ! ( "Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`\ninstead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".saturating_neg(), -100);\nassert_eq!((-100" , stringify ! ($SelfT ), ").saturating_neg(), 100);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_neg(), " , stringify ! ($SelfT ), "::MAX);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.saturating_neg(), " , stringify ! ($SelfT ), "::MIN + 1);" , $EndFeature , "\n```" ), # [ stable ( feature = "saturating_neg" , since = "1.45.0" )]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn saturating_neg ( self )-> Self { intrinsics :: saturating_sub ( 0 , self )}} doc_comment ! { concat ! ( "Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==\nMIN` instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".saturating_abs(), 100);\nassert_eq!((-100" , stringify ! ($SelfT ), ").saturating_abs(), 100);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_abs(), " , stringify ! ($SelfT ), "::MAX);\nassert_eq!((" , stringify ! ($SelfT ), "::MIN + 1).saturating_abs(), " , stringify ! ($SelfT ), "::MAX);" , $EndFeature , "\n```" ), # [ stable ( feature = "saturating_neg" , since = "1.45.0" )]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn saturating_abs ( self )-> Self { if self . is_negative (){ self . saturating_neg ()} else { self }}} doc_comment ! { concat ! ( "Saturating integer multiplication. Computes `self * rhs`, saturating at the\nnumeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(10" , stringify ! ($SelfT ), ".saturating_mul(12), 120);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.saturating_mul(10), " , stringify ! ($SelfT ), "::MAX);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_mul(10), " , stringify ! ($SelfT ), "::MIN);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn saturating_mul ( self , rhs : Self )-> Self { match self . checked_mul ( rhs ){ Some ( x )=> x , None => if ( self < 0 )== ( rhs < 0 ){ Self :: MAX } else { Self :: MIN }}}} doc_comment ! { concat ! ( "Saturating integer exponentiation. Computes `self.pow(exp)`,\nsaturating at the numeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!((-4" , stringify ! ($SelfT ), ").saturating_pow(3), -64);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_pow(2), " , stringify ! ($SelfT ), "::MAX);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.saturating_pow(3), " , stringify ! ($SelfT ), "::MIN);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn saturating_pow ( self , exp : u32 )-> Self { match self . checked_pow ( exp ){ Some ( x )=> x , None if self < 0 && exp % 2 == 1 => Self :: MIN , None => Self :: MAX , }}} doc_comment ! { concat ! ( "Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the\nboundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_add(27), 127);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.wrapping_add(2), " , stringify ! ($SelfT ), "::MIN + 1);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_add ( self , rhs : Self )-> Self { intrinsics :: wrapping_add ( self , rhs )}} doc_comment ! { concat ! ( "Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the\nboundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0" , stringify ! ($SelfT ), ".wrapping_sub(127), -127);\nassert_eq!((-2" , stringify ! ($SelfT ), ").wrapping_sub(" , stringify ! ($SelfT ), "::MAX), " , stringify ! ($SelfT ), "::MAX);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_sub ( self , rhs : Self )-> Self { intrinsics :: wrapping_sub ( self , rhs )}} doc_comment ! { concat ! ( "Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at\nthe boundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(10" , stringify ! ($SelfT ), ".wrapping_mul(12), 120);\nassert_eq!(11i8.wrapping_mul(12), -124);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_mul ( self , rhs : Self )-> Self { intrinsics :: wrapping_mul ( self , rhs )}} doc_comment ! { concat ! ( "Wrapping (modular) division. Computes `self / rhs`, wrapping around at the\nboundary of the type.\n\nThe only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where\n`MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value\nthat is too large to represent in the type. In such a case, this function returns `MIN` itself.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_div(10), 10);\nassert_eq!((-128i8).wrapping_div(-1), -128);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_unstable ( feature = "const_wrapping_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_div ( self , rhs : Self )-> Self { self . overflowing_div ( rhs ). 0 }} doc_comment ! { concat ! ( "Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,\nwrapping around at the boundary of the type.\n\nWrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value\nfor the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the\ntype. In this case, this method returns `MIN` itself.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(100" , stringify ! ($SelfT ), ".wrapping_div_euclid(10), 10);\nassert_eq!((-128i8).wrapping_div_euclid(-1), -128);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_div_euclid ( self , rhs : Self )-> Self { self . overflowing_div_euclid ( rhs ). 0 }} doc_comment ! { concat ! ( "Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the\nboundary of the type.\n\nSuch wrap-around never actually occurs mathematically; implementation artifacts make `x % y`\ninvalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,\nthis function returns `0`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_rem(10), 0);\nassert_eq!((-128i8).wrapping_rem(-1), 0);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_unstable ( feature = "const_wrapping_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_rem ( self , rhs : Self )-> Self { self . overflowing_rem ( rhs ). 0 }} doc_comment ! { concat ! ( "Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around\nat the boundary of the type.\n\nWrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value\nfor the type). In this case, this method returns 0.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(100" , stringify ! ($SelfT ), ".wrapping_rem_euclid(10), 0);\nassert_eq!((-128i8).wrapping_rem_euclid(-1), 0);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_rem_euclid ( self , rhs : Self )-> Self { self . overflowing_rem_euclid ( rhs ). 0 }} doc_comment ! { concat ! ( "Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary\nof the type.\n\nThe only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`\nis the negative minimal value for the type); this is a positive value that is too large to represent\nin the type. In such a case, this function returns `MIN` itself.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_neg(), -100);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.wrapping_neg(), " , stringify ! ($SelfT ), "::MIN);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn wrapping_neg ( self )-> Self { self . overflowing_neg (). 0 }} doc_comment ! { concat ! ( "Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes\nany high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.\n\nNote that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to\nthe range of the type, rather than the bits shifted out of the LHS being returned to the other end.\nThe primitive integer types all implement a `[`rotate_left`](#method.rotate_left) function,\nwhich may be what you want instead.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!((-1" , stringify ! ($SelfT ), ").wrapping_shl(7), -128);\nassert_eq!((-1" , stringify ! ($SelfT ), ").wrapping_shl(128), -1);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_shl ( self , rhs : u32 )-> Self { unsafe { intrinsics :: unchecked_shl ( self , ( rhs & ($BITS - 1 )) as $SelfT )}}} doc_comment ! { concat ! ( "Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`\nremoves any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.\n\nNote that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted\nto the range of the type, rather than the bits shifted out of the LHS being returned to the other\nend. The primitive integer types all implement a [`rotate_right`](#method.rotate_right) function,\nwhich may be what you want instead.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!((-128" , stringify ! ($SelfT ), ").wrapping_shr(7), -1);\nassert_eq!((-128i16).wrapping_shr(64), -128);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_shr ( self , rhs : u32 )-> Self { unsafe { intrinsics :: unchecked_shr ( self , ( rhs & ($BITS - 1 )) as $SelfT )}}} doc_comment ! { concat ! ( "Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at\nthe boundary of the type.\n\nThe only case where such wrapping can occur is when one takes the absolute value of the negative\nminimal value for the type; this is a positive value that is too large to represent in the type. In\nsuch a case, this function returns `MIN` itself.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_abs(), 100);\nassert_eq!((-100" , stringify ! ($SelfT ), ").wrapping_abs(), 100);\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.wrapping_abs(), " , stringify ! ($SelfT ), "::MIN);\nassert_eq!((-128i8).wrapping_abs() as u8, 128);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_abs" , since = "1.13.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ allow ( unused_attributes )]# [ inline ] pub const fn wrapping_abs ( self )-> Self { if self . is_negative (){ self . wrapping_neg ()} else { self }}} doc_comment ! { concat ! ( "Computes the absolute value of `self` without any wrapping\nor panicking.\n\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "#![feature(unsigned_abs)]\nassert_eq!(100" , stringify ! ($SelfT ), ".unsigned_abs(), 100" , stringify ! ($UnsignedT ), ");\nassert_eq!((-100" , stringify ! ($SelfT ), ").unsigned_abs(), 100" , stringify ! ($UnsignedT ), ");\nassert_eq!((-128i8).unsigned_abs(), 128u8);" , $EndFeature , "\n```" ), # [ unstable ( feature = "unsigned_abs" , issue = "74913" )]# [ inline ] pub const fn unsigned_abs ( self )-> $UnsignedT { self . wrapping_abs () as $UnsignedT }} doc_comment ! { concat ! ( "Wrapping (modular) exponentiation. Computes `self.pow(exp)`,\nwrapping around at the boundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(3" , stringify ! ($SelfT ), ".wrapping_pow(4), 81);\nassert_eq!(3i8.wrapping_pow(5), -13);\nassert_eq!(3i8.wrapping_pow(6), -39);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_pow ( self , mut exp : u32 )-> Self { if exp == 0 { return 1 ; } let mut base = self ; let mut acc : Self = 1 ; while exp > 1 { if ( exp & 1 )== 1 { acc = acc . wrapping_mul ( base ); } exp /= 2 ; base = base . wrapping_mul ( base ); } acc . wrapping_mul ( base )}} doc_comment ! { concat ! ( "Calculates `self` + `rhs`\n\nReturns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would\noccur. If an overflow would have occurred then the wrapped value is returned.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_add(2), (7, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.overflowing_add(1), (" , stringify ! ($SelfT ), "::MIN, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_add ( self , rhs : Self )-> ( Self , bool ){ let ( a , b )= intrinsics :: add_with_overflow ( self as $ActualT , rhs as $ActualT ); ( a as Self , b )}} doc_comment ! { concat ! ( "Calculates `self` - `rhs`\n\nReturns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow\nwould occur. If an overflow would have occurred then the wrapped value is returned.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_sub(2), (3, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.overflowing_sub(1), (" , stringify ! ($SelfT ), "::MAX, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_sub ( self , rhs : Self )-> ( Self , bool ){ let ( a , b )= intrinsics :: sub_with_overflow ( self as $ActualT , rhs as $ActualT ); ( a as Self , b )}} doc_comment ! { concat ! ( "Calculates the multiplication of `self` and `rhs`.\n\nReturns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow\nwould occur. If an overflow would have occurred then the wrapped value is returned.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(5" , stringify ! ($SelfT ), ".overflowing_mul(2), (10, false));\nassert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_mul ( self , rhs : Self )-> ( Self , bool ){ let ( a , b )= intrinsics :: mul_with_overflow ( self as $ActualT , rhs as $ActualT ); ( a as Self , b )}} doc_comment ! { concat ! ( "Calculates the divisor when `self` is divided by `rhs`.\n\nReturns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would\noccur. If an overflow would occur then self is returned.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_div(2), (2, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.overflowing_div(-1), (" , stringify ! ($SelfT ), "::MIN, true));" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_unstable ( feature = "const_overflowing_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_div ( self , rhs : Self )-> ( Self , bool ){ if unlikely ! ( self == Self :: MIN && rhs == - 1 ){( self , true )} else {( self / rhs , false )}}} doc_comment ! { concat ! ( "Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.\n\nReturns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would\noccur. If an overflow would occur then `self` is returned.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_div_euclid(2), (2, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.overflowing_div_euclid(-1), (" , stringify ! ($SelfT ), "::MIN, true));\n```" ), # [ inline ]# [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_div_euclid ( self , rhs : Self )-> ( Self , bool ){ if unlikely ! ( self == Self :: MIN && rhs == - 1 ){( self , true )} else {( self . div_euclid ( rhs ), false )}}} doc_comment ! { concat ! ( "Calculates the remainder when `self` is divided by `rhs`.\n\nReturns a tuple of the remainder after dividing along with a boolean indicating whether an\narithmetic overflow would occur. If an overflow would occur then 0 is returned.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_rem(2), (1, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.overflowing_rem(-1), (0, true));" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_unstable ( feature = "const_overflowing_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_rem ( self , rhs : Self )-> ( Self , bool ){ if unlikely ! ( self == Self :: MIN && rhs == - 1 ){( 0 , true )} else {( self % rhs , false )}}} doc_comment ! { concat ! ( "Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.\n\nReturns a tuple of the remainder after dividing along with a boolean indicating whether an\narithmetic overflow would occur. If an overflow would occur then 0 is returned.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_rem_euclid(2), (1, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.overflowing_rem_euclid(-1), (0, true));\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_rem_euclid ( self , rhs : Self )-> ( Self , bool ){ if unlikely ! ( self == Self :: MIN && rhs == - 1 ){( 0 , true )} else {( self . rem_euclid ( rhs ), false )}}} doc_comment ! { concat ! ( "Negates self, overflowing if this is equal to the minimum value.\n\nReturns a tuple of the negated version of self along with a boolean indicating whether an overflow\nhappened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the\nminimum value will be returned again and `true` will be returned for an overflow happening.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(2" , stringify ! ($SelfT ), ".overflowing_neg(), (-2, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MIN.overflowing_neg(), (" , stringify ! ($SelfT ), "::MIN, true));" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ allow ( unused_attributes )] pub const fn overflowing_neg ( self )-> ( Self , bool ){ if unlikely ! ( self == Self :: MIN ){( Self :: MIN , true )} else {(- self , false )}}} doc_comment ! { concat ! ( "Shifts self left by `rhs` bits.\n\nReturns a tuple of the shifted version of self along with a boolean indicating whether the shift\nvalue was larger than or equal to the number of bits. If the shift value is too large, then value is\nmasked (N-1) where N is the number of bits, and this value is then used to perform the shift.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0x1" , stringify ! ($SelfT ), ".overflowing_shl(4), (0x10, false));\nassert_eq!(0x1i32.overflowing_shl(36), (0x10, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_shl ( self , rhs : u32 )-> ( Self , bool ){( self . wrapping_shl ( rhs ), ( rhs > ($BITS - 1 )))}} doc_comment ! { concat ! ( "Shifts self right by `rhs` bits.\n\nReturns a tuple of the shifted version of self along with a boolean indicating whether the shift\nvalue was larger than or equal to the number of bits. If the shift value is too large, then value is\nmasked (N-1) where N is the number of bits, and this value is then used to perform the shift.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0x10" , stringify ! ($SelfT ), ".overflowing_shr(4), (0x1, false));\nassert_eq!(0x10i32.overflowing_shr(36), (0x1, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_shr ( self , rhs : u32 )-> ( Self , bool ){( self . wrapping_shr ( rhs ), ( rhs > ($BITS - 1 )))}} doc_comment ! { concat ! ( "Computes the absolute value of `self`.\n\nReturns a tuple of the absolute version of self along with a boolean indicating whether an overflow\nhappened. If self is the minimum value (e.g., " , stringify ! ($SelfT ), "::MIN for values of type\n " , stringify ! ($SelfT ), "), then the minimum value will be returned again and true will be returned\nfor an overflow happening.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(10" , stringify ! ($SelfT ), ".overflowing_abs(), (10, false));\nassert_eq!((-10" , stringify ! ($SelfT ), ").overflowing_abs(), (10, false));\nassert_eq!((" , stringify ! ($SelfT ), "::MIN).overflowing_abs(), (" , stringify ! ($SelfT ), "::MIN, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_abs" , since = "1.13.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn overflowing_abs ( self )-> ( Self , bool ){( self . wrapping_abs (), self == Self :: MIN )}} doc_comment ! { concat ! ( "Raises self to the power of `exp`, using exponentiation by squaring.\n\nReturns a tuple of the exponentiation along with a bool indicating\nwhether an overflow happened.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(3" , stringify ! ($SelfT ), ".overflowing_pow(4), (81, false));\nassert_eq!(3i8.overflowing_pow(5), (-13, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_pow ( self , mut exp : u32 )-> ( Self , bool ){ if exp == 0 { return ( 1 , false ); } let mut base = self ; let mut acc : Self = 1 ; let mut overflown = false ; let mut r ; while exp > 1 { if ( exp & 1 )== 1 { r = acc . overflowing_mul ( base ); acc = r . 0 ; overflown |= r . 1 ; } exp /= 2 ; r = base . overflowing_mul ( base ); base = r . 0 ; overflown |= r . 1 ; } r = acc . overflowing_mul ( base ); r . 1 |= overflown ; r }} doc_comment ! { concat ! ( "Raises self to the power of `exp`, using exponentiation by squaring.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let x: " , stringify ! ($SelfT ), " = 2; // or any other integer type\n\nassert_eq!(x.pow(5), 32);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn pow ( self , mut exp : u32 )-> Self { if exp == 0 { return 1 ; } let mut base = self ; let mut acc = 1 ; while exp > 1 { if ( exp & 1 )== 1 { acc = acc * base ; } exp /= 2 ; base = base * base ; } acc * base }} doc_comment ! { concat ! ( "Calculates the quotient of Euclidean division of `self` by `rhs`.\n\nThis computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,\nwith `0 <= self.rem_euclid(rhs) < rhs`.\n\nIn other words, the result is `self / rhs` rounded to the integer `n`\nsuch that `self >= n * rhs`.\nIf `self > 0`, this is equal to round towards zero (the default in Rust);\nif `self < 0`, this is equal to round towards +/- infinity.\n\n# Panics\n\nThis function will panic if `rhs` is 0 or the division results in overflow.\n\n# Examples\n\nBasic usage:\n\n```\nlet a: " , stringify ! ($SelfT ), " = 7; // or any other integer type\nlet b = 4;\n\nassert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1\nassert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1\nassert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2\nassert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn div_euclid ( self , rhs : Self )-> Self { let q = self / rhs ; if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 }} q }} doc_comment ! { concat ! ( "Calculates the least nonnegative remainder of `self (mod rhs)`.\n\nThis is done as if by the Euclidean division algorithm -- given\n`r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and\n`0 <= r < abs(rhs)`.\n\n# Panics\n\nThis function will panic if `rhs` is 0 or the division results in overflow.\n\n# Examples\n\nBasic usage:\n\n```\nlet a: " , stringify ! ($SelfT ), " = 7; // or any other integer type\nlet b = 4;\n\nassert_eq!(a.rem_euclid(b), 3);\nassert_eq!((-a).rem_euclid(b), 1);\nassert_eq!(a.rem_euclid(-b), 3);\nassert_eq!((-a).rem_euclid(-b), 1);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn rem_euclid ( self , rhs : Self )-> Self { let r = self % rhs ; if r < 0 { if rhs < 0 { r - rhs } else { r + rhs }} else { r }}} doc_comment ! { concat ! ( "Computes the absolute value of `self`.\n\n# Overflow behavior\n\nThe absolute value of `" , stringify ! ($SelfT ), "::MIN` cannot be represented as an\n`" , stringify ! ($SelfT ), "`, and attempting to calculate it will cause an overflow. This means that\ncode in debug mode will trigger a panic on this case and optimized code will return `" , stringify ! ($SelfT ), "::MIN` without a panic.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(10" , stringify ! ($SelfT ), ".abs(), 10);\nassert_eq!((-10" , stringify ! ($SelfT ), ").abs(), 10);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ allow ( unused_attributes )]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn abs ( self )-> Self { if self . is_negative (){- self } else { self }}} doc_comment ! { concat ! ( "Returns a number representing sign of `self`.\n\n - `0` if the number is zero\n - `1` if the number is positive\n - `-1` if the number is negative\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(10" , stringify ! ($SelfT ), ".signum(), 1);\nassert_eq!(0" , stringify ! ($SelfT ), ".signum(), 0);\nassert_eq!((-10" , stringify ! ($SelfT ), ").signum(), -1);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_sign" , since = "1.47.0" )]# [ inline ] pub const fn signum ( self )-> Self { match self { n if n > 0 => 1 , 0 => 0 , _ =>- 1 , }}} doc_comment ! { concat ! ( "Returns `true` if `self` is positive and `false` if the number is zero or\nnegative.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert!(10" , stringify ! ($SelfT ), ".is_positive());\nassert!(!(-10" , stringify ! ($SelfT ), ").is_positive());" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn is_positive ( self )-> bool { self > 0 }} doc_comment ! { concat ! ( "Returns `true` if `self` is negative and `false` if the number is zero or\npositive.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert!((-10" , stringify ! ($SelfT ), ").is_negative());\nassert!(!10" , stringify ! ($SelfT ), ".is_negative());" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_int_methods" , since = "1.32.0" )]# [ inline ] pub const fn is_negative ( self )-> bool { self < 0 }} doc_comment ! { concat ! ( "Return the memory representation of this integer as a byte array in\nbig-endian (network) byte order.\n" , $to_xe_bytes_doc , "\n# Examples\n\n```\nlet bytes = " , $swap_op , stringify ! ($SelfT ), ".to_be_bytes();\nassert_eq!(bytes, " , $be_bytes , ");\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn to_be_bytes ( self )-> [ u8 ; mem :: size_of ::< Self > ()]{ self . to_be (). to_ne_bytes ()}} doc_comment ! { concat ! ( "Return the memory representation of this integer as a byte array in\nlittle-endian byte order.\n" , $to_xe_bytes_doc , "\n# Examples\n\n```\nlet bytes = " , $swap_op , stringify ! ($SelfT ), ".to_le_bytes();\nassert_eq!(bytes, " , $le_bytes , ");\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn to_le_bytes ( self )-> [ u8 ; mem :: size_of ::< Self > ()]{ self . to_le (). to_ne_bytes ()}} doc_comment ! { concat ! ( "\nReturn the memory representation of this integer as a byte array in\nnative byte order.\n\nAs the target platform's native endianness is used, portable code\nshould use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,\ninstead.\n" , $to_xe_bytes_doc , "\n[`to_be_bytes`]: #method.to_be_bytes\n[`to_le_bytes`]: #method.to_le_bytes\n\n# Examples\n\n```\nlet bytes = " , $swap_op , stringify ! ($SelfT ), ".to_ne_bytes();\nassert_eq!(\n bytes,\n if cfg!(target_endian = \"big\") {\n " , $be_bytes , "\n } else {\n " , $le_bytes , "\n }\n);\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ cfg_attr ( not ( bootstrap ), rustc_allow_const_fn_unstable ( const_fn_transmute ))]# [ cfg_attr ( bootstrap , allow_internal_unstable ( const_fn_transmute ))]# [ inline ] pub const fn to_ne_bytes ( self )-> [ u8 ; mem :: size_of ::< Self > ()]{ unsafe { mem :: transmute ( self )}}} doc_comment ! { concat ! ( "\nReturn the memory representation of this integer as a byte array in\nnative byte order.\n\n[`to_ne_bytes`] should be preferred over this whenever possible.\n\n[`to_ne_bytes`]: #method.to_ne_bytes\n" , "\n# Examples\n\n```\n#![feature(num_as_ne_bytes)]\nlet num = " , $swap_op , stringify ! ($SelfT ), ";\nlet bytes = num.as_ne_bytes();\nassert_eq!(\n bytes,\n if cfg!(target_endian = \"big\") {\n &" , $be_bytes , "\n } else {\n &" , $le_bytes , "\n }\n);\n```" ), # [ unstable ( feature = "num_as_ne_bytes" , issue = "76976" )]# [ inline ] pub fn as_ne_bytes (& self )-> & [ u8 ; mem :: size_of ::< Self > ()]{ unsafe {&* ( self as * const Self as * const _)}}} doc_comment ! { concat ! ( "Create an integer value from its representation as a byte array in\nbig endian.\n" , $from_xe_bytes_doc , "\n# Examples\n\n```\nlet value = " , stringify ! ($SelfT ), "::from_be_bytes(" , $be_bytes , ");\nassert_eq!(value, " , $swap_op , ");\n```\n\nWhen starting from a slice rather than an array, fallible conversion APIs can be used:\n\n```\nuse std::convert::TryInto;\n\nfn read_be_" , stringify ! ($SelfT ), "(input: &mut &[u8]) -> " , stringify ! ($SelfT ), " {\n let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify ! ($SelfT ), ">());\n *input = rest;\n " , stringify ! ($SelfT ), "::from_be_bytes(int_bytes.try_into().unwrap())\n}\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn from_be_bytes ( bytes : [ u8 ; mem :: size_of ::< Self > ()])-> Self { Self :: from_be ( Self :: from_ne_bytes ( bytes ))}} doc_comment ! { concat ! ( "\nCreate an integer value from its representation as a byte array in\nlittle endian.\n" , $from_xe_bytes_doc , "\n# Examples\n\n```\nlet value = " , stringify ! ($SelfT ), "::from_le_bytes(" , $le_bytes , ");\nassert_eq!(value, " , $swap_op , ");\n```\n\nWhen starting from a slice rather than an array, fallible conversion APIs can be used:\n\n```\nuse std::convert::TryInto;\n\nfn read_le_" , stringify ! ($SelfT ), "(input: &mut &[u8]) -> " , stringify ! ($SelfT ), " {\n let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify ! ($SelfT ), ">());\n *input = rest;\n " , stringify ! ($SelfT ), "::from_le_bytes(int_bytes.try_into().unwrap())\n}\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn from_le_bytes ( bytes : [ u8 ; mem :: size_of ::< Self > ()])-> Self { Self :: from_le ( Self :: from_ne_bytes ( bytes ))}} doc_comment ! { concat ! ( "Create an integer value from its memory representation as a byte\narray in native endianness.\n\nAs the target platform's native endianness is used, portable code\nlikely wants to use [`from_be_bytes`] or [`from_le_bytes`], as\nappropriate instead.\n\n[`from_be_bytes`]: #method.from_be_bytes\n[`from_le_bytes`]: #method.from_le_bytes\n" , $from_xe_bytes_doc , "\n# Examples\n\n```\nlet value = " , stringify ! ($SelfT ), "::from_ne_bytes(if cfg!(target_endian = \"big\") {\n " , $be_bytes , "\n} else {\n " , $le_bytes , "\n});\nassert_eq!(value, " , $swap_op , ");\n```\n\nWhen starting from a slice rather than an array, fallible conversion APIs can be used:\n\n```\nuse std::convert::TryInto;\n\nfn read_ne_" , stringify ! ($SelfT ), "(input: &mut &[u8]) -> " , stringify ! ($SelfT ), " {\n let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify ! ($SelfT ), ">());\n *input = rest;\n " , stringify ! ($SelfT ), "::from_ne_bytes(int_bytes.try_into().unwrap())\n}\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ cfg_attr ( not ( bootstrap ), rustc_allow_const_fn_unstable ( const_fn_transmute ))]# [ cfg_attr ( bootstrap , allow_internal_unstable ( const_fn_transmute ))]# [ inline ] pub const fn from_ne_bytes ( bytes : [ u8 ; mem :: size_of ::< Self > ()])-> Self { unsafe { mem :: transmute ( bytes )}}} doc_comment ! { concat ! ( "**This method is soft-deprecated.**\n\nAlthough using it won’t cause a compilation warning,\nnew code should use [`" , stringify ! ($SelfT ), "::MIN" , "`](#associatedconstant.MIN) instead.\n\nReturns the smallest value that can be represented by this integer type." ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ inline ( always )]# [ rustc_promotable ]# [ rustc_const_stable ( feature = "const_min_value" , since = "1.32.0" )] pub const fn min_value ()-> Self { Self :: MIN }} doc_comment ! { concat ! ( "**This method is soft-deprecated.**\n\nAlthough using it won’t cause a compilation warning,\nnew code should use [`" , stringify ! ($SelfT ), "::MAX" , "`](#associatedconstant.MAX) instead.\n\nReturns the largest value that can be represented by this integer type." ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ inline ( always )]# [ rustc_promotable ]# [ rustc_const_stable ( feature = "const_max_value" , since = "1.32.0" )] pub const fn max_value ()-> Self { Self :: MAX }}}} +macro_rules! __ra_macro_fixture429 {($x : expr , $($tt : tt )*)=>{# [ doc = $x ]$($tt )* }; } +macro_rules! __ra_macro_fixture430 {()=>{ "\n\n**Note**: This function returns an array of length 2, 4 or 8 bytes\ndepending on the target pointer size.\n\n" }; } +macro_rules! __ra_macro_fixture431 {()=>{ "\n\n**Note**: This function takes an array of length 2, 4 or 8 bytes\ndepending on the target pointer size.\n\n" }; } +macro_rules! __ra_macro_fixture432 {($SelfT : ty , $ActualT : ty , $BITS : expr , $MaxV : expr , $Feature : expr , $EndFeature : expr , $rot : expr , $rot_op : expr , $rot_result : expr , $swap_op : expr , $swapped : expr , $reversed : expr , $le_bytes : expr , $be_bytes : expr , $to_xe_bytes_doc : expr , $from_xe_bytes_doc : expr )=>{ doc_comment ! { concat ! ( "The smallest value that can be represented by this integer type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MIN, 0);" , $EndFeature , "\n```" ), # [ stable ( feature = "assoc_int_consts" , since = "1.43.0" )] pub const MIN : Self = 0 ; } doc_comment ! { concat ! ( "The largest value that can be represented by this integer type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MAX, " , stringify ! ($MaxV ), ");" , $EndFeature , "\n```" ), # [ stable ( feature = "assoc_int_consts" , since = "1.43.0" )] pub const MAX : Self = ! 0 ; } doc_comment ! { concat ! ( "The size of this integer type in bits.\n\n# Examples\n\n```\n" , $Feature , "#![feature(int_bits_const)]\nassert_eq!(" , stringify ! ($SelfT ), "::BITS, " , stringify ! ($BITS ), ");" , $EndFeature , "\n```" ), # [ unstable ( feature = "int_bits_const" , issue = "76904" )] pub const BITS : u32 = $BITS ; } doc_comment ! { concat ! ( "Converts a string slice in a given base to an integer.\n\nThe string is expected to be an optional `+` sign\nfollowed by digits.\nLeading and trailing whitespace represent an error.\nDigits are a subset of these characters, depending on `radix`:\n\n* `0-9`\n* `a-z`\n* `A-Z`\n\n# Panics\n\nThis function panics if `radix` is not in the range from 2 to 36.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::from_str_radix(\"A\", 16), Ok(10));" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )] pub fn from_str_radix ( src : & str , radix : u32 )-> Result < Self , ParseIntError > { from_str_radix ( src , radix )}} doc_comment ! { concat ! ( "Returns the number of ones in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0b01001100" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.count_ones(), 3);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn count_ones ( self )-> u32 { intrinsics :: ctpop ( self as $ActualT ) as u32 }} doc_comment ! { concat ! ( "Returns the number of zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(" , stringify ! ($SelfT ), "::MAX.count_zeros(), 0);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn count_zeros ( self )-> u32 {(! self ). count_ones ()}} doc_comment ! { concat ! ( "Returns the number of leading zeros in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = " , stringify ! ($SelfT ), "::MAX >> 2;\n\nassert_eq!(n.leading_zeros(), 2);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn leading_zeros ( self )-> u32 { intrinsics :: ctlz ( self as $ActualT ) as u32 }} doc_comment ! { concat ! ( "Returns the number of trailing zeros in the binary representation\nof `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0b0101000" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.trailing_zeros(), 3);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn trailing_zeros ( self )-> u32 { intrinsics :: cttz ( self ) as u32 }} doc_comment ! { concat ! ( "Returns the number of leading ones in the binary representation of `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = !(" , stringify ! ($SelfT ), "::MAX >> 2);\n\nassert_eq!(n.leading_ones(), 2);" , $EndFeature , "\n```" ), # [ stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ rustc_const_stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ inline ] pub const fn leading_ones ( self )-> u32 {(! self ). leading_zeros ()}} doc_comment ! { concat ! ( "Returns the number of trailing ones in the binary representation\nof `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0b1010111" , stringify ! ($SelfT ), ";\n\nassert_eq!(n.trailing_ones(), 3);" , $EndFeature , "\n```" ), # [ stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ rustc_const_stable ( feature = "leading_trailing_ones" , since = "1.46.0" )]# [ inline ] pub const fn trailing_ones ( self )-> u32 {(! self ). trailing_zeros ()}} doc_comment ! { concat ! ( "Shifts the bits to the left by a specified amount, `n`,\nwrapping the truncated bits to the end of the resulting integer.\n\nPlease note this isn't the same operation as the `<<` shifting operator!\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $rot_op , stringify ! ($SelfT ), ";\nlet m = " , $rot_result , ";\n\nassert_eq!(n.rotate_left(" , $rot , "), m);\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn rotate_left ( self , n : u32 )-> Self { intrinsics :: rotate_left ( self , n as $SelfT )}} doc_comment ! { concat ! ( "Shifts the bits to the right by a specified amount, `n`,\nwrapping the truncated bits to the beginning of the resulting\ninteger.\n\nPlease note this isn't the same operation as the `>>` shifting operator!\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $rot_result , stringify ! ($SelfT ), ";\nlet m = " , $rot_op , ";\n\nassert_eq!(n.rotate_right(" , $rot , "), m);\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn rotate_right ( self , n : u32 )-> Self { intrinsics :: rotate_right ( self , n as $SelfT )}} doc_comment ! { concat ! ( "\nReverses the byte order of the integer.\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $swap_op , stringify ! ($SelfT ), ";\nlet m = n.swap_bytes();\n\nassert_eq!(m, " , $swapped , ");\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn swap_bytes ( self )-> Self { intrinsics :: bswap ( self as $ActualT ) as Self }} doc_comment ! { concat ! ( "Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,\n second least-significant bit becomes second most-significant bit, etc.\n\n# Examples\n\nBasic usage:\n\n```\nlet n = " , $swap_op , stringify ! ($SelfT ), ";\nlet m = n.reverse_bits();\n\nassert_eq!(m, " , $reversed , ");\nassert_eq!(0, 0" , stringify ! ($SelfT ), ".reverse_bits());\n```" ), # [ stable ( feature = "reverse_bits" , since = "1.37.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ]# [ must_use ] pub const fn reverse_bits ( self )-> Self { intrinsics :: bitreverse ( self as $ActualT ) as Self }} doc_comment ! { concat ! ( "Converts an integer from big endian to the target's endianness.\n\nOn big endian this is a no-op. On little endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(" , stringify ! ($SelfT ), "::from_be(n), n)\n} else {\n assert_eq!(" , stringify ! ($SelfT ), "::from_be(n), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn from_be ( x : Self )-> Self {# [ cfg ( target_endian = "big" )]{ x }# [ cfg ( not ( target_endian = "big" ))]{ x . swap_bytes ()}}} doc_comment ! { concat ! ( "Converts an integer from little endian to the target's endianness.\n\nOn little endian this is a no-op. On big endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(" , stringify ! ($SelfT ), "::from_le(n), n)\n} else {\n assert_eq!(" , stringify ! ($SelfT ), "::from_le(n), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn from_le ( x : Self )-> Self {# [ cfg ( target_endian = "little" )]{ x }# [ cfg ( not ( target_endian = "little" ))]{ x . swap_bytes ()}}} doc_comment ! { concat ! ( "Converts `self` to big endian from the target's endianness.\n\nOn big endian this is a no-op. On little endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(n.to_be(), n)\n} else {\n assert_eq!(n.to_be(), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn to_be ( self )-> Self {# [ cfg ( target_endian = "big" )]{ self }# [ cfg ( not ( target_endian = "big" ))]{ self . swap_bytes ()}}} doc_comment ! { concat ! ( "Converts `self` to little endian from the target's endianness.\n\nOn little endian this is a no-op. On big endian the bytes are\nswapped.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "let n = 0x1A" , stringify ! ($SelfT ), ";\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(n.to_le(), n)\n} else {\n assert_eq!(n.to_le(), n.swap_bytes())\n}" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_math" , since = "1.32.0" )]# [ inline ] pub const fn to_le ( self )-> Self {# [ cfg ( target_endian = "little" )]{ self }# [ cfg ( not ( target_endian = "little" ))]{ self . swap_bytes ()}}} doc_comment ! { concat ! ( "Checked integer addition. Computes `self + rhs`, returning `None`\nif overflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!((" , stringify ! ($SelfT ), "::MAX - 2).checked_add(1), " , "Some(" , stringify ! ($SelfT ), "::MAX - 1));\nassert_eq!((" , stringify ! ($SelfT ), "::MAX - 2).checked_add(3), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_add ( self , rhs : Self )-> Option < Self > { let ( a , b )= self . overflowing_add ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Unchecked integer addition. Computes `self + rhs`, assuming overflow\ncannot occur. This results in undefined behavior when `self + rhs > " , stringify ! ($SelfT ), "::MAX` or `self + rhs < " , stringify ! ($SelfT ), "::MIN`." ), # [ unstable ( feature = "unchecked_math" , reason = "niche optimization path" , issue = "none" , )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub unsafe fn unchecked_add ( self , rhs : Self )-> Self { unsafe { intrinsics :: unchecked_add ( self , rhs )}}} doc_comment ! { concat ! ( "Checked integer subtraction. Computes `self - rhs`, returning\n`None` if overflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(1" , stringify ! ($SelfT ), ".checked_sub(1), Some(0));\nassert_eq!(0" , stringify ! ($SelfT ), ".checked_sub(1), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_sub ( self , rhs : Self )-> Option < Self > { let ( a , b )= self . overflowing_sub ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Unchecked integer subtraction. Computes `self - rhs`, assuming overflow\ncannot occur. This results in undefined behavior when `self - rhs > " , stringify ! ($SelfT ), "::MAX` or `self - rhs < " , stringify ! ($SelfT ), "::MIN`." ), # [ unstable ( feature = "unchecked_math" , reason = "niche optimization path" , issue = "none" , )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub unsafe fn unchecked_sub ( self , rhs : Self )-> Self { unsafe { intrinsics :: unchecked_sub ( self , rhs )}}} doc_comment ! { concat ! ( "Checked integer multiplication. Computes `self * rhs`, returning\n`None` if overflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(5" , stringify ! ($SelfT ), ".checked_mul(1), Some(5));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.checked_mul(2), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_mul ( self , rhs : Self )-> Option < Self > { let ( a , b )= self . overflowing_mul ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Unchecked integer multiplication. Computes `self * rhs`, assuming overflow\ncannot occur. This results in undefined behavior when `self * rhs > " , stringify ! ($SelfT ), "::MAX` or `self * rhs < " , stringify ! ($SelfT ), "::MIN`." ), # [ unstable ( feature = "unchecked_math" , reason = "niche optimization path" , issue = "none" , )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub unsafe fn unchecked_mul ( self , rhs : Self )-> Self { unsafe { intrinsics :: unchecked_mul ( self , rhs )}}} doc_comment ! { concat ! ( "Checked integer division. Computes `self / rhs`, returning `None`\nif `rhs == 0`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(128" , stringify ! ($SelfT ), ".checked_div(2), Some(64));\nassert_eq!(1" , stringify ! ($SelfT ), ".checked_div(0), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_unstable ( feature = "const_checked_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_div ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 ){ None } else { Some ( unsafe { intrinsics :: unchecked_div ( self , rhs )})}}} doc_comment ! { concat ! ( "Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`\nif `rhs == 0`.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(128" , stringify ! ($SelfT ), ".checked_div_euclid(2), Some(64));\nassert_eq!(1" , stringify ! ($SelfT ), ".checked_div_euclid(0), None);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_div_euclid ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 ){ None } else { Some ( self . div_euclid ( rhs ))}}} doc_comment ! { concat ! ( "Checked integer remainder. Computes `self % rhs`, returning `None`\nif `rhs == 0`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(5" , stringify ! ($SelfT ), ".checked_rem(2), Some(1));\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem(0), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_unstable ( feature = "const_checked_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_rem ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 ){ None } else { Some ( unsafe { intrinsics :: unchecked_rem ( self , rhs )})}}} doc_comment ! { concat ! ( "Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`\nif `rhs == 0`.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem_euclid(2), Some(1));\nassert_eq!(5" , stringify ! ($SelfT ), ".checked_rem_euclid(0), None);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_rem_euclid ( self , rhs : Self )-> Option < Self > { if unlikely ! ( rhs == 0 ){ None } else { Some ( self . rem_euclid ( rhs ))}}} doc_comment ! { concat ! ( "Checked negation. Computes `-self`, returning `None` unless `self ==\n0`.\n\nNote that negating any positive integer will overflow.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0" , stringify ! ($SelfT ), ".checked_neg(), Some(0));\nassert_eq!(1" , stringify ! ($SelfT ), ".checked_neg(), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn checked_neg ( self )-> Option < Self > { let ( a , b )= self . overflowing_neg (); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Checked shift left. Computes `self << rhs`, returning `None`\nif `rhs` is larger than or equal to the number of bits in `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0x1" , stringify ! ($SelfT ), ".checked_shl(4), Some(0x10));\nassert_eq!(0x10" , stringify ! ($SelfT ), ".checked_shl(129), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_shl ( self , rhs : u32 )-> Option < Self > { let ( a , b )= self . overflowing_shl ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Checked shift right. Computes `self >> rhs`, returning `None`\nif `rhs` is larger than or equal to the number of bits in `self`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(0x10" , stringify ! ($SelfT ), ".checked_shr(4), Some(0x1));\nassert_eq!(0x10" , stringify ! ($SelfT ), ".checked_shr(129), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_checked_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_shr ( self , rhs : u32 )-> Option < Self > { let ( a , b )= self . overflowing_shr ( rhs ); if unlikely ! ( b ){ None } else { Some ( a )}}} doc_comment ! { concat ! ( "Checked exponentiation. Computes `self.pow(exp)`, returning `None` if\noverflow occurred.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(2" , stringify ! ($SelfT ), ".checked_pow(5), Some(32));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.checked_pow(2), None);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn checked_pow ( self , mut exp : u32 )-> Option < Self > { if exp == 0 { return Some ( 1 ); } let mut base = self ; let mut acc : Self = 1 ; while exp > 1 { if ( exp & 1 )== 1 { acc = try_opt ! ( acc . checked_mul ( base )); } exp /= 2 ; base = try_opt ! ( base . checked_mul ( base )); } Some ( try_opt ! ( acc . checked_mul ( base )))}} doc_comment ! { concat ! ( "Saturating integer addition. Computes `self + rhs`, saturating at\nthe numeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".saturating_add(1), 101);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.saturating_add(127), " , stringify ! ($SelfT ), "::MAX);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn saturating_add ( self , rhs : Self )-> Self { intrinsics :: saturating_add ( self , rhs )}} doc_comment ! { concat ! ( "Saturating integer subtraction. Computes `self - rhs`, saturating\nat the numeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".saturating_sub(27), 73);\nassert_eq!(13" , stringify ! ($SelfT ), ".saturating_sub(127), 0);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ inline ] pub const fn saturating_sub ( self , rhs : Self )-> Self { intrinsics :: saturating_sub ( self , rhs )}} doc_comment ! { concat ! ( "Saturating integer multiplication. Computes `self * rhs`,\nsaturating at the numeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(2" , stringify ! ($SelfT ), ".saturating_mul(10), 20);\nassert_eq!((" , stringify ! ($SelfT ), "::MAX).saturating_mul(10), " , stringify ! ($SelfT ), "::MAX);" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_saturating_int_methods" , since = "1.47.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn saturating_mul ( self , rhs : Self )-> Self { match self . checked_mul ( rhs ){ Some ( x )=> x , None => Self :: MAX , }}} doc_comment ! { concat ! ( "Saturating integer exponentiation. Computes `self.pow(exp)`,\nsaturating at the numeric bounds instead of overflowing.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "\nassert_eq!(4" , stringify ! ($SelfT ), ".saturating_pow(3), 64);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.saturating_pow(2), " , stringify ! ($SelfT ), "::MAX);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn saturating_pow ( self , exp : u32 )-> Self { match self . checked_pow ( exp ){ Some ( x )=> x , None => Self :: MAX , }}} doc_comment ! { concat ! ( "Wrapping (modular) addition. Computes `self + rhs`,\nwrapping around at the boundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(200" , stringify ! ($SelfT ), ".wrapping_add(55), 255);\nassert_eq!(200" , stringify ! ($SelfT ), ".wrapping_add(" , stringify ! ($SelfT ), "::MAX), 199);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_add ( self , rhs : Self )-> Self { intrinsics :: wrapping_add ( self , rhs )}} doc_comment ! { concat ! ( "Wrapping (modular) subtraction. Computes `self - rhs`,\nwrapping around at the boundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_sub(100), 0);\nassert_eq!(100" , stringify ! ($SelfT ), ".wrapping_sub(" , stringify ! ($SelfT ), "::MAX), 101);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_sub ( self , rhs : Self )-> Self { intrinsics :: wrapping_sub ( self , rhs )}}# [ doc = " Wrapping (modular) multiplication. Computes `self *" ]# [ doc = " rhs`, wrapping around at the boundary of the type." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " Please note that this example is shared between integer types." ]# [ doc = " Which explains why `u8` is used here." ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " assert_eq!(10u8.wrapping_mul(12), 120);" ]# [ doc = " assert_eq!(25u8.wrapping_mul(12), 44);" ]# [ doc = " ```" ]# [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_mul ( self , rhs : Self )-> Self { intrinsics :: wrapping_mul ( self , rhs )} doc_comment ! { concat ! ( "Wrapping (modular) division. Computes `self / rhs`.\nWrapped division on unsigned types is just normal division.\nThere's no way wrapping could ever happen.\nThis function exists, so that all operations\nare accounted for in the wrapping operations.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_div(10), 10);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_unstable ( feature = "const_wrapping_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_div ( self , rhs : Self )-> Self { self / rhs }} doc_comment ! { concat ! ( "Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.\nWrapped division on unsigned types is just normal division.\nThere's no way wrapping could ever happen.\nThis function exists, so that all operations\nare accounted for in the wrapping operations.\nSince, for the positive integers, all common\ndefinitions of division are equal, this\nis exactly equal to `self.wrapping_div(rhs)`.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(100" , stringify ! ($SelfT ), ".wrapping_div_euclid(10), 10);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_div_euclid ( self , rhs : Self )-> Self { self / rhs }} doc_comment ! { concat ! ( "Wrapping (modular) remainder. Computes `self % rhs`.\nWrapped remainder calculation on unsigned types is\njust the regular remainder calculation.\nThere's no way wrapping could ever happen.\nThis function exists, so that all operations\nare accounted for in the wrapping operations.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(100" , stringify ! ($SelfT ), ".wrapping_rem(10), 0);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_unstable ( feature = "const_wrapping_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_rem ( self , rhs : Self )-> Self { self % rhs }} doc_comment ! { concat ! ( "Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.\nWrapped modulo calculation on unsigned types is\njust the regular remainder calculation.\nThere's no way wrapping could ever happen.\nThis function exists, so that all operations\nare accounted for in the wrapping operations.\nSince, for the positive integers, all common\ndefinitions of division are equal, this\nis exactly equal to `self.wrapping_rem(rhs)`.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(100" , stringify ! ($SelfT ), ".wrapping_rem_euclid(10), 0);\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_rem_euclid ( self , rhs : Self )-> Self { self % rhs }}# [ doc = " Wrapping (modular) negation. Computes `-self`," ]# [ doc = " wrapping around at the boundary of the type." ]# [ doc = "" ]# [ doc = " Since unsigned types do not have negative equivalents" ]# [ doc = " all applications of this function will wrap (except for `-0`)." ]# [ doc = " For values smaller than the corresponding signed type\\\'s maximum" ]# [ doc = " the result is the same as casting the corresponding signed value." ]# [ doc = " Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where" ]# [ doc = " `MAX` is the corresponding signed type\\\'s maximum." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " Please note that this example is shared between integer types." ]# [ doc = " Which explains why `i8` is used here." ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " assert_eq!(100i8.wrapping_neg(), -100);" ]# [ doc = " assert_eq!((-128i8).wrapping_neg(), -128);" ]# [ doc = " ```" ]# [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ inline ] pub const fn wrapping_neg ( self )-> Self { self . overflowing_neg (). 0 } doc_comment ! { concat ! ( "Panic-free bitwise shift-left; yields `self << mask(rhs)`,\nwhere `mask` removes any high-order bits of `rhs` that\nwould cause the shift to exceed the bitwidth of the type.\n\nNote that this is *not* the same as a rotate-left; the\nRHS of a wrapping shift-left is restricted to the range\nof the type, rather than the bits shifted out of the LHS\nbeing returned to the other end. The primitive integer\ntypes all implement a [`rotate_left`](#method.rotate_left) function,\nwhich may be what you want instead.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(1" , stringify ! ($SelfT ), ".wrapping_shl(7), 128);\nassert_eq!(1" , stringify ! ($SelfT ), ".wrapping_shl(128), 1);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_shl ( self , rhs : u32 )-> Self { unsafe { intrinsics :: unchecked_shl ( self , ( rhs & ($BITS - 1 )) as $SelfT )}}} doc_comment ! { concat ! ( "Panic-free bitwise shift-right; yields `self >> mask(rhs)`,\nwhere `mask` removes any high-order bits of `rhs` that\nwould cause the shift to exceed the bitwidth of the type.\n\nNote that this is *not* the same as a rotate-right; the\nRHS of a wrapping shift-right is restricted to the range\nof the type, rather than the bits shifted out of the LHS\nbeing returned to the other end. The primitive integer\ntypes all implement a [`rotate_right`](#method.rotate_right) function,\nwhich may be what you want instead.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(128" , stringify ! ($SelfT ), ".wrapping_shr(7), 1);\nassert_eq!(128" , stringify ! ($SelfT ), ".wrapping_shr(128), 128);" , $EndFeature , "\n```" ), # [ stable ( feature = "num_wrapping" , since = "1.2.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_shr ( self , rhs : u32 )-> Self { unsafe { intrinsics :: unchecked_shr ( self , ( rhs & ($BITS - 1 )) as $SelfT )}}} doc_comment ! { concat ! ( "Wrapping (modular) exponentiation. Computes `self.pow(exp)`,\nwrapping around at the boundary of the type.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(3" , stringify ! ($SelfT ), ".wrapping_pow(5), 243);\nassert_eq!(3u8.wrapping_pow(6), 217);" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn wrapping_pow ( self , mut exp : u32 )-> Self { if exp == 0 { return 1 ; } let mut base = self ; let mut acc : Self = 1 ; while exp > 1 { if ( exp & 1 )== 1 { acc = acc . wrapping_mul ( base ); } exp /= 2 ; base = base . wrapping_mul ( base ); } acc . wrapping_mul ( base )}} doc_comment ! { concat ! ( "Calculates `self` + `rhs`\n\nReturns a tuple of the addition along with a boolean indicating\nwhether an arithmetic overflow would occur. If an overflow would\nhave occurred then the wrapped value is returned.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_add(2), (7, false));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.overflowing_add(1), (0, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_add ( self , rhs : Self )-> ( Self , bool ){ let ( a , b )= intrinsics :: add_with_overflow ( self as $ActualT , rhs as $ActualT ); ( a as Self , b )}} doc_comment ! { concat ! ( "Calculates `self` - `rhs`\n\nReturns a tuple of the subtraction along with a boolean indicating\nwhether an arithmetic overflow would occur. If an overflow would\nhave occurred then the wrapped value is returned.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_sub(2), (3, false));\nassert_eq!(0" , stringify ! ($SelfT ), ".overflowing_sub(1), (" , stringify ! ($SelfT ), "::MAX, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_sub ( self , rhs : Self )-> ( Self , bool ){ let ( a , b )= intrinsics :: sub_with_overflow ( self as $ActualT , rhs as $ActualT ); ( a as Self , b )}}# [ doc = " Calculates the multiplication of `self` and `rhs`." ]# [ doc = "" ]# [ doc = " Returns a tuple of the multiplication along with a boolean" ]# [ doc = " indicating whether an arithmetic overflow would occur. If an" ]# [ doc = " overflow would have occurred then the wrapped value is returned." ]# [ doc = "" ]# [ doc = " # Examples" ]# [ doc = "" ]# [ doc = " Basic usage:" ]# [ doc = "" ]# [ doc = " Please note that this example is shared between integer types." ]# [ doc = " Which explains why `u32` is used here." ]# [ doc = "" ]# [ doc = " ```" ]# [ doc = " assert_eq!(5u32.overflowing_mul(2), (10, false));" ]# [ doc = " assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));" ]# [ doc = " ```" ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_mul ( self , rhs : Self )-> ( Self , bool ){ let ( a , b )= intrinsics :: mul_with_overflow ( self as $ActualT , rhs as $ActualT ); ( a as Self , b )} doc_comment ! { concat ! ( "Calculates the divisor when `self` is divided by `rhs`.\n\nReturns a tuple of the divisor along with a boolean indicating\nwhether an arithmetic overflow would occur. Note that for unsigned\nintegers overflow never occurs, so the second value is always\n`false`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "assert_eq!(5" , stringify ! ($SelfT ), ".overflowing_div(2), (2, false));" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_unstable ( feature = "const_overflowing_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_div ( self , rhs : Self )-> ( Self , bool ){( self / rhs , false )}} doc_comment ! { concat ! ( "Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.\n\nReturns a tuple of the divisor along with a boolean indicating\nwhether an arithmetic overflow would occur. Note that for unsigned\nintegers overflow never occurs, so the second value is always\n`false`.\nSince, for the positive integers, all common\ndefinitions of division are equal, this\nis exactly equal to `self.overflowing_div(rhs)`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage\n\n```\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_div_euclid(2), (2, false));\n```" ), # [ inline ]# [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_div_euclid ( self , rhs : Self )-> ( Self , bool ){( self / rhs , false )}} doc_comment ! { concat ! ( "Calculates the remainder when `self` is divided by `rhs`.\n\nReturns a tuple of the remainder after dividing along with a boolean\nindicating whether an arithmetic overflow would occur. Note that for\nunsigned integers overflow never occurs, so the second value is\nalways `false`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "assert_eq!(5" , stringify ! ($SelfT ), ".overflowing_rem(2), (1, false));" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_unstable ( feature = "const_overflowing_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_rem ( self , rhs : Self )-> ( Self , bool ){( self % rhs , false )}} doc_comment ! { concat ! ( "Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.\n\nReturns a tuple of the modulo after dividing along with a boolean\nindicating whether an arithmetic overflow would occur. Note that for\nunsigned integers overflow never occurs, so the second value is\nalways `false`.\nSince, for the positive integers, all common\ndefinitions of division are equal, this operation\nis exactly equal to `self.overflowing_rem(rhs)`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage\n\n```\nassert_eq!(5" , stringify ! ($SelfT ), ".overflowing_rem_euclid(2), (1, false));\n```" ), # [ inline ]# [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ] pub const fn overflowing_rem_euclid ( self , rhs : Self )-> ( Self , bool ){( self % rhs , false )}} doc_comment ! { concat ! ( "Negates self in an overflowing fashion.\n\nReturns `!self + 1` using wrapping operations to return the value\nthat represents the negation of this unsigned value. Note that for\npositive unsigned values overflow always occurs, but negating 0 does\nnot overflow.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "assert_eq!(0" , stringify ! ($SelfT ), ".overflowing_neg(), (0, false));\nassert_eq!(2" , stringify ! ($SelfT ), ".overflowing_neg(), (-2i32 as " , stringify ! ($SelfT ), ", true));" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )] pub const fn overflowing_neg ( self )-> ( Self , bool ){((! self ). wrapping_add ( 1 ), self != 0 )}} doc_comment ! { concat ! ( "Shifts self left by `rhs` bits.\n\nReturns a tuple of the shifted version of self along with a boolean\nindicating whether the shift value was larger than or equal to the\nnumber of bits. If the shift value is too large, then value is\nmasked (N-1) where N is the number of bits, and this value is then\nused to perform the shift.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "assert_eq!(0x1" , stringify ! ($SelfT ), ".overflowing_shl(4), (0x10, false));\nassert_eq!(0x1" , stringify ! ($SelfT ), ".overflowing_shl(132), (0x10, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_shl ( self , rhs : u32 )-> ( Self , bool ){( self . wrapping_shl ( rhs ), ( rhs > ($BITS - 1 )))}} doc_comment ! { concat ! ( "Shifts self right by `rhs` bits.\n\nReturns a tuple of the shifted version of self along with a boolean\nindicating whether the shift value was larger than or equal to the\nnumber of bits. If the shift value is too large, then value is\nmasked (N-1) where N is the number of bits, and this value is then\nused to perform the shift.\n\n# Examples\n\nBasic usage\n\n```\n" , $Feature , "assert_eq!(0x10" , stringify ! ($SelfT ), ".overflowing_shr(4), (0x1, false));\nassert_eq!(0x10" , stringify ! ($SelfT ), ".overflowing_shr(132), (0x1, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "wrapping" , since = "1.7.0" )]# [ rustc_const_stable ( feature = "const_wrapping_math" , since = "1.32.0" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_shr ( self , rhs : u32 )-> ( Self , bool ){( self . wrapping_shr ( rhs ), ( rhs > ($BITS - 1 )))}} doc_comment ! { concat ! ( "Raises self to the power of `exp`, using exponentiation by squaring.\n\nReturns a tuple of the exponentiation along with a bool indicating\nwhether an overflow happened.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(3" , stringify ! ($SelfT ), ".overflowing_pow(5), (243, false));\nassert_eq!(3u8.overflowing_pow(6), (217, true));" , $EndFeature , "\n```" ), # [ stable ( feature = "no_panic_pow" , since = "1.34.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ] pub const fn overflowing_pow ( self , mut exp : u32 )-> ( Self , bool ){ if exp == 0 { return ( 1 , false ); } let mut base = self ; let mut acc : Self = 1 ; let mut overflown = false ; let mut r ; while exp > 1 { if ( exp & 1 )== 1 { r = acc . overflowing_mul ( base ); acc = r . 0 ; overflown |= r . 1 ; } exp /= 2 ; r = base . overflowing_mul ( base ); base = r . 0 ; overflown |= r . 1 ; } r = acc . overflowing_mul ( base ); r . 1 |= overflown ; r }} doc_comment ! { concat ! ( "Raises self to the power of `exp`, using exponentiation by squaring.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(2" , stringify ! ($SelfT ), ".pow(5), 32);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn pow ( self , mut exp : u32 )-> Self { if exp == 0 { return 1 ; } let mut base = self ; let mut acc = 1 ; while exp > 1 { if ( exp & 1 )== 1 { acc = acc * base ; } exp /= 2 ; base = base * base ; } acc * base }} doc_comment ! { concat ! ( "Performs Euclidean division.\n\nSince, for the positive integers, all common\ndefinitions of division are equal, this\nis exactly equal to `self / rhs`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(7" , stringify ! ($SelfT ), ".div_euclid(4), 1); // or any other integer type\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn div_euclid ( self , rhs : Self )-> Self { self / rhs }} doc_comment ! { concat ! ( "Calculates the least remainder of `self (mod rhs)`.\n\nSince, for the positive integers, all common\ndefinitions of division are equal, this\nis exactly equal to `self % rhs`.\n\n# Panics\n\nThis function will panic if `rhs` is 0.\n\n# Examples\n\nBasic usage:\n\n```\nassert_eq!(7" , stringify ! ($SelfT ), ".rem_euclid(4), 3); // or any other integer type\n```" ), # [ stable ( feature = "euclidean_division" , since = "1.38.0" )]# [ rustc_const_unstable ( feature = "const_euclidean_int_methods" , issue = "53718" )]# [ must_use = "this returns the result of the operation, \\n without modifying the original" ]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn rem_euclid ( self , rhs : Self )-> Self { self % rhs }} doc_comment ! { concat ! ( "Returns `true` if and only if `self == 2^k` for some `k`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert!(16" , stringify ! ($SelfT ), ".is_power_of_two());\nassert!(!10" , stringify ! ($SelfT ), ".is_power_of_two());" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_stable ( feature = "const_is_power_of_two" , since = "1.32.0" )]# [ inline ] pub const fn is_power_of_two ( self )-> bool { self . count_ones ()== 1 }}# [ inline ]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )] const fn one_less_than_next_power_of_two ( self )-> Self { if self <= 1 { return 0 ; } let p = self - 1 ; let z = unsafe { intrinsics :: ctlz_nonzero ( p )}; <$SelfT >:: MAX >> z } doc_comment ! { concat ! ( "Returns the smallest power of two greater than or equal to `self`.\n\nWhen return value overflows (i.e., `self > (1 << (N-1))` for type\n`uN`), it panics in debug mode and return value is wrapped to 0 in\nrelease mode (the only situation in which method can return 0).\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(2" , stringify ! ($SelfT ), ".next_power_of_two(), 2);\nassert_eq!(3" , stringify ! ($SelfT ), ".next_power_of_two(), 4);" , $EndFeature , "\n```" ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )]# [ inline ]# [ rustc_inherit_overflow_checks ] pub const fn next_power_of_two ( self )-> Self { self . one_less_than_next_power_of_two ()+ 1 }} doc_comment ! { concat ! ( "Returns the smallest power of two greater than or equal to `n`. If\nthe next power of two is greater than the type's maximum value,\n`None` is returned, otherwise the power of two is wrapped in `Some`.\n\n# Examples\n\nBasic usage:\n\n```\n" , $Feature , "assert_eq!(2" , stringify ! ($SelfT ), ".checked_next_power_of_two(), Some(2));\nassert_eq!(3" , stringify ! ($SelfT ), ".checked_next_power_of_two(), Some(4));\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.checked_next_power_of_two(), None);" , $EndFeature , "\n```" ), # [ inline ]# [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )] pub const fn checked_next_power_of_two ( self )-> Option < Self > { self . one_less_than_next_power_of_two (). checked_add ( 1 )}} doc_comment ! { concat ! ( "Returns the smallest power of two greater than or equal to `n`. If\nthe next power of two is greater than the type's maximum value,\nthe return value is wrapped to `0`.\n\n# Examples\n\nBasic usage:\n\n```\n#![feature(wrapping_next_power_of_two)]\n" , $Feature , "\nassert_eq!(2" , stringify ! ($SelfT ), ".wrapping_next_power_of_two(), 2);\nassert_eq!(3" , stringify ! ($SelfT ), ".wrapping_next_power_of_two(), 4);\nassert_eq!(" , stringify ! ($SelfT ), "::MAX.wrapping_next_power_of_two(), 0);" , $EndFeature , "\n```" ), # [ unstable ( feature = "wrapping_next_power_of_two" , issue = "32463" , reason = "needs decision on wrapping behaviour" )]# [ rustc_const_unstable ( feature = "const_int_pow" , issue = "53718" )] pub const fn wrapping_next_power_of_two ( self )-> Self { self . one_less_than_next_power_of_two (). wrapping_add ( 1 )}} doc_comment ! { concat ! ( "Return the memory representation of this integer as a byte array in\nbig-endian (network) byte order.\n" , $to_xe_bytes_doc , "\n# Examples\n\n```\nlet bytes = " , $swap_op , stringify ! ($SelfT ), ".to_be_bytes();\nassert_eq!(bytes, " , $be_bytes , ");\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn to_be_bytes ( self )-> [ u8 ; mem :: size_of ::< Self > ()]{ self . to_be (). to_ne_bytes ()}} doc_comment ! { concat ! ( "Return the memory representation of this integer as a byte array in\nlittle-endian byte order.\n" , $to_xe_bytes_doc , "\n# Examples\n\n```\nlet bytes = " , $swap_op , stringify ! ($SelfT ), ".to_le_bytes();\nassert_eq!(bytes, " , $le_bytes , ");\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn to_le_bytes ( self )-> [ u8 ; mem :: size_of ::< Self > ()]{ self . to_le (). to_ne_bytes ()}} doc_comment ! { concat ! ( "\nReturn the memory representation of this integer as a byte array in\nnative byte order.\n\nAs the target platform's native endianness is used, portable code\nshould use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,\ninstead.\n" , $to_xe_bytes_doc , "\n[`to_be_bytes`]: #method.to_be_bytes\n[`to_le_bytes`]: #method.to_le_bytes\n\n# Examples\n\n```\nlet bytes = " , $swap_op , stringify ! ($SelfT ), ".to_ne_bytes();\nassert_eq!(\n bytes,\n if cfg!(target_endian = \"big\") {\n " , $be_bytes , "\n } else {\n " , $le_bytes , "\n }\n);\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ cfg_attr ( not ( bootstrap ), rustc_allow_const_fn_unstable ( const_fn_transmute ))]# [ cfg_attr ( bootstrap , allow_internal_unstable ( const_fn_transmute ))]# [ inline ] pub const fn to_ne_bytes ( self )-> [ u8 ; mem :: size_of ::< Self > ()]{ unsafe { mem :: transmute ( self )}}} doc_comment ! { concat ! ( "\nReturn the memory representation of this integer as a byte array in\nnative byte order.\n\n[`to_ne_bytes`] should be preferred over this whenever possible.\n\n[`to_ne_bytes`]: #method.to_ne_bytes\n" , "\n# Examples\n\n```\n#![feature(num_as_ne_bytes)]\nlet num = " , $swap_op , stringify ! ($SelfT ), ";\nlet bytes = num.as_ne_bytes();\nassert_eq!(\n bytes,\n if cfg!(target_endian = \"big\") {\n &" , $be_bytes , "\n } else {\n &" , $le_bytes , "\n }\n);\n```" ), # [ unstable ( feature = "num_as_ne_bytes" , issue = "76976" )]# [ inline ] pub fn as_ne_bytes (& self )-> & [ u8 ; mem :: size_of ::< Self > ()]{ unsafe {&* ( self as * const Self as * const _)}}} doc_comment ! { concat ! ( "Create a native endian integer value from its representation\nas a byte array in big endian.\n" , $from_xe_bytes_doc , "\n# Examples\n\n```\nlet value = " , stringify ! ($SelfT ), "::from_be_bytes(" , $be_bytes , ");\nassert_eq!(value, " , $swap_op , ");\n```\n\nWhen starting from a slice rather than an array, fallible conversion APIs can be used:\n\n```\nuse std::convert::TryInto;\n\nfn read_be_" , stringify ! ($SelfT ), "(input: &mut &[u8]) -> " , stringify ! ($SelfT ), " {\n let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify ! ($SelfT ), ">());\n *input = rest;\n " , stringify ! ($SelfT ), "::from_be_bytes(int_bytes.try_into().unwrap())\n}\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn from_be_bytes ( bytes : [ u8 ; mem :: size_of ::< Self > ()])-> Self { Self :: from_be ( Self :: from_ne_bytes ( bytes ))}} doc_comment ! { concat ! ( "\nCreate a native endian integer value from its representation\nas a byte array in little endian.\n" , $from_xe_bytes_doc , "\n# Examples\n\n```\nlet value = " , stringify ! ($SelfT ), "::from_le_bytes(" , $le_bytes , ");\nassert_eq!(value, " , $swap_op , ");\n```\n\nWhen starting from a slice rather than an array, fallible conversion APIs can be used:\n\n```\nuse std::convert::TryInto;\n\nfn read_le_" , stringify ! ($SelfT ), "(input: &mut &[u8]) -> " , stringify ! ($SelfT ), " {\n let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify ! ($SelfT ), ">());\n *input = rest;\n " , stringify ! ($SelfT ), "::from_le_bytes(int_bytes.try_into().unwrap())\n}\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ inline ] pub const fn from_le_bytes ( bytes : [ u8 ; mem :: size_of ::< Self > ()])-> Self { Self :: from_le ( Self :: from_ne_bytes ( bytes ))}} doc_comment ! { concat ! ( "Create a native endian integer value from its memory representation\nas a byte array in native endianness.\n\nAs the target platform's native endianness is used, portable code\nlikely wants to use [`from_be_bytes`] or [`from_le_bytes`], as\nappropriate instead.\n\n[`from_be_bytes`]: #method.from_be_bytes\n[`from_le_bytes`]: #method.from_le_bytes\n" , $from_xe_bytes_doc , "\n# Examples\n\n```\nlet value = " , stringify ! ($SelfT ), "::from_ne_bytes(if cfg!(target_endian = \"big\") {\n " , $be_bytes , "\n} else {\n " , $le_bytes , "\n});\nassert_eq!(value, " , $swap_op , ");\n```\n\nWhen starting from a slice rather than an array, fallible conversion APIs can be used:\n\n```\nuse std::convert::TryInto;\n\nfn read_ne_" , stringify ! ($SelfT ), "(input: &mut &[u8]) -> " , stringify ! ($SelfT ), " {\n let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify ! ($SelfT ), ">());\n *input = rest;\n " , stringify ! ($SelfT ), "::from_ne_bytes(int_bytes.try_into().unwrap())\n}\n```" ), # [ stable ( feature = "int_to_from_bytes" , since = "1.32.0" )]# [ rustc_const_stable ( feature = "const_int_conversion" , since = "1.44.0" )]# [ cfg_attr ( not ( bootstrap ), rustc_allow_const_fn_unstable ( const_fn_transmute ))]# [ cfg_attr ( bootstrap , allow_internal_unstable ( const_fn_transmute ))]# [ inline ] pub const fn from_ne_bytes ( bytes : [ u8 ; mem :: size_of ::< Self > ()])-> Self { unsafe { mem :: transmute ( bytes )}}} doc_comment ! { concat ! ( "**This method is soft-deprecated.**\n\nAlthough using it won’t cause compilation warning,\nnew code should use [`" , stringify ! ($SelfT ), "::MIN" , "`](#associatedconstant.MIN) instead.\n\nReturns the smallest value that can be represented by this integer type." ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_promotable ]# [ inline ( always )]# [ rustc_const_stable ( feature = "const_max_value" , since = "1.32.0" )] pub const fn min_value ()-> Self { Self :: MIN }} doc_comment ! { concat ! ( "**This method is soft-deprecated.**\n\nAlthough using it won’t cause compilation warning,\nnew code should use [`" , stringify ! ($SelfT ), "::MAX" , "`](#associatedconstant.MAX) instead.\n\nReturns the largest value that can be represented by this integer type." ), # [ stable ( feature = "rust1" , since = "1.0.0" )]# [ rustc_promotable ]# [ inline ( always )]# [ rustc_const_stable ( feature = "const_max_value" , since = "1.32.0" )] pub const fn max_value ()-> Self { Self :: MAX }}}} +macro_rules! __ra_macro_fixture433 {($type : ident )=>{ const EXPLICIT_SIG_BITS : u8 = Self :: SIG_BITS - 1 ; const MAX_EXP : i16 = ( 1 << ( Self :: EXP_BITS - 1 ))- 1 ; const MIN_EXP : i16 = -< Self as RawFloat >:: MAX_EXP + 1 ; const MAX_EXP_INT : i16 = < Self as RawFloat >:: MAX_EXP - ( Self :: SIG_BITS as i16 - 1 ); const MAX_ENCODED_EXP : i16 = ( 1 << Self :: EXP_BITS )- 1 ; const MIN_EXP_INT : i16 = < Self as RawFloat >:: MIN_EXP - ( Self :: SIG_BITS as i16 - 1 ); const MAX_SIG : u64 = ( 1 << Self :: SIG_BITS )- 1 ; const MIN_SIG : u64 = 1 << ( Self :: SIG_BITS - 1 ); const INFINITY : Self = $type :: INFINITY ; const NAN : Self = $type :: NAN ; const ZERO : Self = 0.0 ; }; } +macro_rules! __ra_macro_fixture434 {()=>{# [ inline ] unsafe fn forward_unchecked ( start : Self , n : usize )-> Self { unsafe { start . unchecked_add ( n as Self )}}# [ inline ] unsafe fn backward_unchecked ( start : Self , n : usize )-> Self { unsafe { start . unchecked_sub ( n as Self )}}# [ inline ] fn forward ( start : Self , n : usize )-> Self { if Self :: forward_checked ( start , n ). is_none (){ let _ = Add :: add ( Self :: MAX , 1 ); } start . wrapping_add ( n as Self )}# [ inline ] fn backward ( start : Self , n : usize )-> Self { if Self :: backward_checked ( start , n ). is_none (){ let _ = Sub :: sub ( Self :: MIN , 1 ); } start . wrapping_sub ( n as Self )}}; } +macro_rules! __ra_macro_fixture435 {( u8 , $($tt : tt )*)=>{ "" }; ( i8 , $($tt : tt )*)=>{ "" }; ($_: ident , $($tt : tt )*)=>{$($tt )* }; } +macro_rules! __ra_macro_fixture436 {( forward )=>{# [ inline ] fn haystack (& self )-> & 'a str { self . 0 . haystack ()}# [ inline ] fn next (& mut self )-> SearchStep { self . 0 . next ()}# [ inline ] fn next_match (& mut self )-> Option < ( usize , usize )> { self . 0 . next_match ()}# [ inline ] fn next_reject (& mut self )-> Option < ( usize , usize )> { self . 0 . next_reject ()}}; ( reverse )=>{# [ inline ] fn next_back (& mut self )-> SearchStep { self . 0 . next_back ()}# [ inline ] fn next_match_back (& mut self )-> Option < ( usize , usize )> { self . 0 . next_match_back ()}# [ inline ] fn next_reject_back (& mut self )-> Option < ( usize , usize )> { self . 0 . next_reject_back ()}}; } +macro_rules! __ra_macro_fixture437 {($t : ty , $pmap : expr , $smap : expr )=>{ type Searcher = $t ; # [ inline ] fn into_searcher ( self , haystack : & 'a str )-> $t {($smap )(($pmap )( self ). into_searcher ( haystack ))}# [ inline ] fn is_contained_in ( self , haystack : & 'a str )-> bool {($pmap )( self ). is_contained_in ( haystack )}# [ inline ] fn is_prefix_of ( self , haystack : & 'a str )-> bool {($pmap )( self ). is_prefix_of ( haystack )}# [ inline ] fn strip_prefix_of ( self , haystack : & 'a str )-> Option <& 'a str > {($pmap )( self ). strip_prefix_of ( haystack )}# [ inline ] fn is_suffix_of ( self , haystack : & 'a str )-> bool where $t : ReverseSearcher < 'a >, {($pmap )( self ). is_suffix_of ( haystack )}# [ inline ] fn strip_suffix_of ( self , haystack : & 'a str )-> Option <& 'a str > where $t : ReverseSearcher < 'a >, {($pmap )( self ). strip_suffix_of ( haystack )}}; } +macro_rules! __ra_macro_fixture438 {()=>{# [ inline ] fn is_ascii (& self )-> bool { self . is_ascii ()}# [ inline ] fn to_ascii_uppercase (& self )-> Self :: Owned { self . to_ascii_uppercase ()}# [ inline ] fn to_ascii_lowercase (& self )-> Self :: Owned { self . to_ascii_lowercase ()}# [ inline ] fn eq_ignore_ascii_case (& self , o : & Self )-> bool { self . eq_ignore_ascii_case ( o )}# [ inline ] fn make_ascii_uppercase (& mut self ){ self . make_ascii_uppercase (); }# [ inline ] fn make_ascii_lowercase (& mut self ){ self . make_ascii_lowercase (); }}; } +macro_rules! __ra_macro_fixture439 {()=>($crate :: vec :: Vec :: new ()); ($elem : expr ; $n : expr )=>($crate :: vec :: from_elem ($elem , $n )); ($($x : expr ),+ $(,)?)=>(< [_]>:: into_vec ( box [$($x ),+])); } +macro_rules! __ra_macro_fixture440 {($left : expr , $right : expr $(,)?)=>({ match (&$left , &$right ){( left_val , right_val )=>{ if ! (* left_val == * right_val ){ panic ! ( r#"assertion failed: `(left == right)`\n left: `{:?}`,\n right: `{:?}`"# , &* left_val , &* right_val )}}}}); ($left : expr , $right : expr , $($arg : tt )+)=>({ match (& ($left ), & ($right )){( left_val , right_val )=>{ if ! (* left_val == * right_val ){ panic ! ( r#"assertion failed: `(left == right)`\n left: `{:?}`,\n right: `{:?}`: {}"# , &* left_val , &* right_val , $crate :: format_args ! ($($arg )+))}}}}); } +macro_rules! __ra_macro_fixture441 {()=>({$crate :: panic ! ( "explicit panic" )}); ($msg : expr $(,)?)=>({$crate :: rt :: begin_panic ($msg )}); ($fmt : expr , $($arg : tt )+)=>({$crate :: rt :: begin_panic_fmt (&$crate :: format_args ! ($fmt , $($arg )+))}); } +macro_rules! __ra_macro_fixture442 {($expression : expr , $($pattern : pat )|+ $(if $guard : expr )? $(,)?)=>{ match $expression {$($pattern )|+ $(if $guard )? => true , _ => false }}} +macro_rules! __ra_macro_fixture443 {()=>{# [ inline ] fn load_consume (& self )-> Self :: Val { self . load ( Ordering :: Acquire )}}; } +macro_rules! __ra_macro_fixture444 {($($tt : tt )*)=>{$($tt )* }} +macro_rules! __ra_macro_fixture445 {($tyname : ident , $($($field : ident ).+),*)=>{ fn fmt (& self , f : & mut :: std :: fmt :: Formatter )-> :: std :: fmt :: Result { f . debug_struct ( stringify ! ($tyname ))$(. field ( stringify ! ($($field ).+), & self .$($field ).+))* . finish ()}}} +macro_rules! __ra_macro_fixture446 {($($field : ident ),*)=>{ fn clone (& self )-> Self { Self {$($field : self .$field . clone (),)* }}}} +macro_rules! __ra_macro_fixture447 {($method : ident )=>{ fn $method < V > ( self , visitor : V )-> Result < V :: Value > where V : de :: Visitor < 'de >, { self . deserialize_number ( visitor )}}; } +macro_rules! __ra_macro_fixture448 {($method : ident =>$visit : ident )=>{ fn $method < V > ( self , visitor : V )-> Result < V :: Value > where V : de :: Visitor < 'de >, { self . de . eat_char (); self . de . scratch . clear (); let string = tri ! ( self . de . read . parse_str (& mut self . de . scratch )); match ( string . parse (), string ){( Ok ( integer ), _)=> visitor .$visit ( integer ), ( Err (_), Reference :: Borrowed ( s ))=> visitor . visit_borrowed_str ( s ), ( Err (_), Reference :: Copied ( s ))=> visitor . visit_str ( s ), }}}; } +macro_rules! __ra_macro_fixture449 {($method : ident )=>{# [ cfg ( not ( feature = "arbitrary_precision" ))] fn $method < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { match self { Value :: Number ( n )=> n . deserialize_any ( visitor ), _ => Err ( self . invalid_type (& visitor )), }}# [ cfg ( feature = "arbitrary_precision" )] fn $method < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { match self { Value :: Number ( n )=> n .$method ( visitor ), _ => self . deserialize_any ( visitor ), }}}; } +macro_rules! __ra_macro_fixture450 {($method : ident )=>{# [ cfg ( not ( feature = "arbitrary_precision" ))] fn $method < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { match * self { Value :: Number ( ref n )=> n . deserialize_any ( visitor ), _ => Err ( self . invalid_type (& visitor )), }}# [ cfg ( feature = "arbitrary_precision" )] fn $method < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { match * self { Value :: Number ( ref n )=> n .$method ( visitor ), _ => self . deserialize_any ( visitor ), }}}; } +macro_rules! __ra_macro_fixture451 {($method : ident =>$visit : ident )=>{ fn $method < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { match ( self . key . parse (), self . key ){( Ok ( integer ), _)=> visitor .$visit ( integer ), ( Err (_), Cow :: Borrowed ( s ))=> visitor . visit_borrowed_str ( s ), # [ cfg ( any ( feature = "std" , feature = "alloc" ))]( Err (_), Cow :: Owned ( s ))=> visitor . visit_string ( s ), }}}; } +macro_rules! __ra_macro_fixture452 {(@ expand [$($num_string : tt )*])=>{# [ cfg ( not ( feature = "arbitrary_precision" ))]# [ inline ] fn deserialize_any < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { match self . n { N :: PosInt ( u )=> visitor . visit_u64 ( u ), N :: NegInt ( i )=> visitor . visit_i64 ( i ), N :: Float ( f )=> visitor . visit_f64 ( f ), }}# [ cfg ( feature = "arbitrary_precision" )]# [ inline ] fn deserialize_any < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de > { if let Some ( u )= self . as_u64 (){ return visitor . visit_u64 ( u ); } else if let Some ( i )= self . as_i64 (){ return visitor . visit_i64 ( i ); } else if let Some ( f )= self . as_f64 (){ if ryu :: Buffer :: new (). format_finite ( f )== self . n || f . to_string ()== self . n { return visitor . visit_f64 ( f ); }} visitor . visit_map ( NumberDeserializer { number : Some ( self .$($num_string )*), })}}; ( owned )=>{ deserialize_any ! (@ expand [ n ]); }; ( ref )=>{ deserialize_any ! (@ expand [ n . clone ()]); }; } +macro_rules! __ra_macro_fixture453 {($deserialize : ident =>$visit : ident )=>{# [ cfg ( not ( feature = "arbitrary_precision" ))] fn $deserialize < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : Visitor < 'de >, { self . deserialize_any ( visitor )}# [ cfg ( feature = "arbitrary_precision" )] fn $deserialize < V > ( self , visitor : V )-> Result < V :: Value , Error > where V : de :: Visitor < 'de >, { visitor .$visit ( self . n . parse (). map_err (|_| invalid_number ())?)}}; } +macro_rules! __ra_macro_fixture454 {()=>{ fn __rayon_private__ (& self )-> crate :: private :: PrivateMarker { crate :: private :: PrivateMarker }}; } +macro_rules! __ra_macro_fixture455 {()=>{ fn __rayon_private__ (& self )-> crate :: private :: PrivateMarker { crate :: private :: PrivateMarker }}; } +macro_rules! __ra_macro_fixture456 {($map_elt : expr )=>{ fn next (& mut self )-> Option < Self :: Item > { self . iter . next (). map ($map_elt )} fn size_hint (& self )-> ( usize , Option < usize >){ self . iter . size_hint ()} fn count ( self )-> usize { self . iter . len ()} fn nth (& mut self , n : usize )-> Option < Self :: Item > { self . iter . nth ( n ). map ($map_elt )} fn last ( mut self )-> Option < Self :: Item > { self . next_back ()} fn collect < C > ( self )-> C where C : FromIterator < Self :: Item >, { self . iter . map ($map_elt ). collect ()}}; } +macro_rules! __ra_macro_fixture457 {($map_elt : expr )=>{ fn next_back (& mut self )-> Option < Self :: Item > { self . iter . next_back (). map ($map_elt )}}; } +macro_rules! __ra_macro_fixture458 {()=>{# [ doc = " This trait is private; this method exists to make it" ]# [ doc = " impossible to implement outside the crate." ]# [ doc ( hidden )] fn __rayon_private__ (& self )-> crate :: private :: PrivateMarker ; }; } +macro_rules! __ra_macro_fixture459 {($ident : ident )=>{{# [ cfg ( test )]{ extern "C" {# [ no_mangle ] static $ident : std :: sync :: atomic :: AtomicUsize ; } unsafe {$ident . fetch_add ( 1 , std :: sync :: atomic :: Ordering :: SeqCst ); }}}}; } +macro_rules! __ra_macro_fixture460 {($ident : ident )=>{# [ no_mangle ] static $ident : std :: sync :: atomic :: AtomicUsize = std :: sync :: atomic :: AtomicUsize :: new ( 0 ); let _checker = $crate :: mark :: MarkChecker :: new (&$ident ); }; } +macro_rules! __ra_macro_fixture461 {( target : $target : expr , $($arg : tt )+)=>( log ! ( target : $target , $crate :: Level :: Debug , $($arg )+)); ($($arg : tt )+)=>( log ! ($crate :: Level :: Debug , $($arg )+))} +macro_rules! __ra_macro_fixture462 {()=>($crate :: eprint ! ( "\n" )); ($($arg : tt )*)=>({$crate :: io :: _eprint ($crate :: format_args_nl ! ($($arg )*)); })} +macro_rules! __ra_macro_fixture463 {( target : $target : expr , $($arg : tt )+)=>( log ! ( target : $target , $crate :: Level :: Warn , $($arg )+)); ($($arg : tt )+)=>( log ! ($crate :: Level :: Warn , $($arg )+))} +macro_rules! __ra_macro_fixture464 {( target : $target : expr , $lvl : expr , $($arg : tt )+)=>({ let lvl = $lvl ; if lvl <= $crate :: STATIC_MAX_LEVEL && lvl <= $crate :: max_level (){$crate :: __private_api_log ( __log_format_args ! ($($arg )+), lvl , & ($target , __log_module_path ! (), __log_file ! (), __log_line ! ()), ); }}); ($lvl : expr , $($arg : tt )+)=>( log ! ( target : __log_module_path ! (), $lvl , $($arg )+))} +macro_rules! __ra_macro_fixture465 {($($args : tt )*)=>{ format_args ! ($($args )*)}; } +macro_rules! __ra_macro_fixture466 {()=>{ module_path ! ()}; } +macro_rules! __ra_macro_fixture467 {()=>{ file ! ()}; } +macro_rules! __ra_macro_fixture468 {()=>{ line ! ()}; } +macro_rules! __ra_macro_fixture469 {($left : expr , $right : expr )=>{ assert_eq_text ! ($left , $right ,)}; ($left : expr , $right : expr , $($tt : tt )*)=>{{ let left = $left ; let right = $right ; if left != right { if left . trim ()== right . trim (){ std :: eprintln ! ( "Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n" , left , right ); } else { let diff = $crate :: __diff ( left , right ); std :: eprintln ! ( "Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n" , left , right , $crate :: format_diff ( diff )); } std :: eprintln ! ($($tt )*); panic ! ( "text differs" ); }}}; } +macro_rules! __ra_macro_fixture470 {($($arg : tt )*)=>($crate :: io :: _eprint ($crate :: format_args ! ($($arg )*))); } +macro_rules! __ra_macro_fixture471 {($left : expr , $right : expr $(,)?)=>({ match (&$left , &$right ){( left_val , right_val )=>{ if * left_val == * right_val { panic ! ( r#"assertion failed: `(left != right)`\n left: `{:?}`,\n right: `{:?}`"# , &* left_val , &* right_val )}}}}); ($left : expr , $right : expr , $($arg : tt )+)=>({ match (& ($left ), & ($right )){( left_val , right_val )=>{ if * left_val == * right_val { panic ! ( r#"assertion failed: `(left != right)`\n left: `{:?}`,\n right: `{:?}`: {}"# , &* left_val , &* right_val , $crate :: format_args ! ($($arg )+))}}}}); } +macro_rules! __ra_macro_fixture472 {[[$data : literal ]]=>{$crate :: Expect { position : $crate :: Position { file : file ! (), line : line ! (), column : column ! (), }, data : $data , }}; [[]]=>{$crate :: expect ! [[ "" ]]}; } +macro_rules! __ra_macro_fixture473 {( self )=>{$crate :: name :: known :: SELF_PARAM }; ( Self )=>{$crate :: name :: known :: SELF_TYPE }; ('static )=>{$crate :: name :: known :: STATIC_LIFETIME }; ($ident : ident )=>{$crate :: name :: known ::$ident }; } +macro_rules! __ra_macro_fixture474 {()=>({ panic ! ( "internal error: entered unreachable code" )}); ($msg : expr $(,)?)=>({$crate :: unreachable ! ( "{}" , $msg )}); ($fmt : expr , $($arg : tt )*)=>({ panic ! ($crate :: concat ! ( "internal error: entered unreachable code: " , $fmt ), $($arg )*)}); } +macro_rules! __ra_macro_fixture475 {( target : $target : expr , $($arg : tt )+)=>( log ! ( target : $target , $crate :: Level :: Error , $($arg )+)); ($($arg : tt )+)=>( log ! ($crate :: Level :: Error , $($arg )+))} +macro_rules! __ra_macro_fixture476 {( target : $target : expr , $($arg : tt )+)=>( log ! ( target : $target , $crate :: Level :: Trace , $($arg )+)); ($($arg : tt )+)=>( log ! ($crate :: Level :: Trace , $($arg )+))} +macro_rules! __ra_macro_fixture477 {($buf : expr )=>(); ($buf : expr , $lit : literal $($arg : tt )*)=>{{ use :: std :: fmt :: Write as _; let _ = :: std :: write ! ($buf , $lit $($arg )*); }}; } +macro_rules! __ra_macro_fixture478 {( match $node : ident {$($tt : tt )* })=>{ match_ast ! ( match ($node ){$($tt )* })}; ( match ($node : expr ){$(ast ::$ast : ident ($it : ident )=>$res : expr , )* _ =>$catch_all : expr $(,)? })=>{{$(if let Some ($it )= ast ::$ast :: cast ($node . clone ()){$res } else )* {$catch_all }}}; } +macro_rules! __ra_macro_fixture479 {($start : ident $(:: $seg : ident )*)=>({$crate :: __known_path ! ($start $(:: $seg )*); $crate :: path :: ModPath :: from_segments ($crate :: path :: PathKind :: Abs , vec ! [$crate :: path :: __name ! [$start ], $($crate :: path :: __name ! [$seg ],)* ])}); } +macro_rules! __ra_macro_fixture480 {( core :: iter :: IntoIterator )=>{}; ( core :: iter :: Iterator )=>{}; ( core :: result :: Result )=>{}; ( core :: option :: Option )=>{}; ( core :: ops :: Range )=>{}; ( core :: ops :: RangeFrom )=>{}; ( core :: ops :: RangeFull )=>{}; ( core :: ops :: RangeTo )=>{}; ( core :: ops :: RangeToInclusive )=>{}; ( core :: ops :: RangeInclusive )=>{}; ( core :: future :: Future )=>{}; ( core :: ops :: Try )=>{}; ($path : path )=>{ compile_error ! ( "Please register your known path in the path module" )}; } +macro_rules! __ra_macro_fixture481 {($changed : ident , ($this : ident / $def : ident ). $field : ident , $glob_imports : ident [$lookup : ident ], $def_import_type : ident )=>{{ let existing = $this .$field . entry ($lookup . 1 . clone ()); match ( existing , $def .$field ){( Entry :: Vacant ( entry ), Some (_))=>{ match $def_import_type { ImportType :: Glob =>{$glob_imports .$field . insert ($lookup . clone ()); } ImportType :: Named =>{$glob_imports .$field . remove (&$lookup ); }} if let Some ( fld )= $def .$field { entry . insert ( fld ); }$changed = true ; }( Entry :: Occupied ( mut entry ), Some (_)) if $glob_imports .$field . contains (&$lookup )&& matches ! ($def_import_type , ImportType :: Named )=>{ mark :: hit ! ( import_shadowed ); $glob_imports .$field . remove (&$lookup ); if let Some ( fld )= $def .$field { entry . insert ( fld ); }$changed = true ; }_ =>{}}}}; } +macro_rules! __ra_macro_fixture482 {($(# $attr_args : tt )* const fn $($item : tt )* )=>{$(# $attr_args )* fn $($item )* }; ($(# $attr_args : tt )* pub const fn $($item : tt )* )=>{$(# $attr_args )* pub fn $($item )* }; ($(# $attr_args : tt )* pub const unsafe fn $($item : tt )* )=>{$(# $attr_args )* pub unsafe fn $($item )* }; } +macro_rules! __ra_macro_fixture483 {{ type Mirror = $tinyname : ident ; $($(# [$attr : meta ])* $v : vis fn $fname : ident ($seif : ident : $seifty : ty $(,$argname : ident : $argtype : ty )*)$(-> $ret : ty )? ; )* }=>{$($(# [$attr ])* # [ inline ( always )]$v fn $fname ($seif : $seifty , $($argname : $argtype ),*)$(-> $ret )? { match $seif {$tinyname :: Inline ( i )=> i .$fname ($($argname ),*), $tinyname :: Heap ( h )=> h .$fname ($($argname ),*), }})* }; } +macro_rules! __ra_macro_fixture484 {([$($stack : tt )*])=>{$($stack )* }; ([$($stack : tt )*]@ escape $_x : tt $($t : tt )*)=>{ remove_sections_inner ! ([$($stack )*]$($t )*); }; ([$($stack : tt )*]@ section $x : ident $($t : tt )*)=>{ remove_sections_inner ! ([$($stack )*]$($t )*); }; ([$($stack : tt )*]$t : tt $($tail : tt )*)=>{ remove_sections_inner ! ([$($stack )* $t ]$($tail )*); }; } +macro_rules! __ra_macro_fixture485 {($name : ident , $($field : ident ),+ $(,)*)=>( fn clone (& self )-> Self {$name {$($field : self . $field . clone ()),* }}); } +macro_rules! __ra_macro_fixture486 {( type FreeFunctions )=>( type FreeFunctions : 'static ;); ( type TokenStream )=>( type TokenStream : 'static + Clone ;); ( type TokenStreamBuilder )=>( type TokenStreamBuilder : 'static ;); ( type TokenStreamIter )=>( type TokenStreamIter : 'static + Clone ;); ( type Group )=>( type Group : 'static + Clone ;); ( type Punct )=>( type Punct : 'static + Copy + Eq + Hash ;); ( type Ident )=>( type Ident : 'static + Copy + Eq + Hash ;); ( type Literal )=>( type Literal : 'static + Clone ;); ( type SourceFile )=>( type SourceFile : 'static + Clone ;); ( type MultiSpan )=>( type MultiSpan : 'static ;); ( type Diagnostic )=>( type Diagnostic : 'static ;); ( type Span )=>( type Span : 'static + Copy + Eq + Hash ;); ( fn drop (& mut self , $arg : ident : $arg_ty : ty ))=>( fn drop (& mut self , $arg : $arg_ty ){ mem :: drop ($arg )}); ( fn clone (& mut self , $arg : ident : $arg_ty : ty )-> $ret_ty : ty )=>( fn clone (& mut self , $arg : $arg_ty )-> $ret_ty {$arg . clone ()}); ($($item : tt )*)=>($($item )*;)} +macro_rules! __ra_macro_fixture487 {($bit : expr , $is_fn_name : ident , $set_fn_name : ident )=>{ fn $is_fn_name (& self )-> bool { self . bools & ( 0b1 << $bit )> 0 } fn $set_fn_name (& mut self , yes : bool ){ if yes { self . bools |= 1 << $bit ; } else { self . bools &= ! ( 1 << $bit ); }}}; } +macro_rules! __ra_macro_fixture488 {($($(# [$cfg : meta ])* fn $method : ident -> $i : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$i > {( self . 0 ).$method ()})*}} +macro_rules! __ra_macro_fixture489 {($($(# [$cfg : meta ])* fn $method : ident ($i : ident ); )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method ( n : $i )-> Option < Self > { T ::$method ( n ). map ( Wrapping )})*}} +macro_rules! __ra_macro_fixture490 {($SrcT : ident : $($(# [$cfg : meta ])* fn $method : ident -> $DstT : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$DstT > { let min = $DstT :: MIN as $SrcT ; let max = $DstT :: MAX as $SrcT ; if size_of ::<$SrcT > ()<= size_of ::<$DstT > ()|| ( min <= * self && * self <= max ){ Some (* self as $DstT )} else { None }})*}} +macro_rules! __ra_macro_fixture491 {($SrcT : ident : $($(# [$cfg : meta ])* fn $method : ident -> $DstT : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$DstT > { let max = $DstT :: MAX as $SrcT ; if 0 <= * self && ( size_of ::<$SrcT > ()<= size_of ::<$DstT > ()|| * self <= max ){ Some (* self as $DstT )} else { None }})*}} +macro_rules! __ra_macro_fixture492 {($SrcT : ident : $($(# [$cfg : meta ])* fn $method : ident -> $DstT : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$DstT > { let max = $DstT :: MAX as $SrcT ; if size_of ::<$SrcT > ()< size_of ::<$DstT > ()|| * self <= max { Some (* self as $DstT )} else { None }})*}} +macro_rules! __ra_macro_fixture493 {($SrcT : ident : $($(# [$cfg : meta ])* fn $method : ident -> $DstT : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$DstT > { let max = $DstT :: MAX as $SrcT ; if size_of ::<$SrcT > ()<= size_of ::<$DstT > ()|| * self <= max { Some (* self as $DstT )} else { None }})*}} +macro_rules! __ra_macro_fixture494 {($f : ident : $($(# [$cfg : meta ])* fn $method : ident -> $i : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$i > { if size_of ::<$f > ()> size_of ::<$i > (){ const MIN_M1 : $f = $i :: MIN as $f - 1.0 ; const MAX_P1 : $f = $i :: MAX as $f + 1.0 ; if * self > MIN_M1 && * self < MAX_P1 { return Some ( float_to_int_unchecked ! (* self =>$i )); }} else { const MIN : $f = $i :: MIN as $f ; const MAX_P1 : $f = $i :: MAX as $f ; if * self >= MIN && * self < MAX_P1 { return Some ( float_to_int_unchecked ! (* self =>$i )); }} None })*}} +macro_rules! __ra_macro_fixture495 {($f : ident : $($(# [$cfg : meta ])* fn $method : ident -> $u : ident ; )*)=>{$(# [ inline ]$(# [$cfg ])* fn $method (& self )-> Option <$u > { if size_of ::<$f > ()> size_of ::<$u > (){ const MAX_P1 : $f = $u :: MAX as $f + 1.0 ; if * self > - 1.0 && * self < MAX_P1 { return Some ( float_to_int_unchecked ! (* self =>$u )); }} else { const MAX_P1 : $f = $u :: MAX as $f ; if * self > - 1.0 && * self < MAX_P1 { return Some ( float_to_int_unchecked ! (* self =>$u )); }} None })*}} +macro_rules! __ra_macro_fixture496 {($SrcT : ident : $(fn $method : ident -> $DstT : ident ; )*)=>{$(# [ inline ] fn $method (& self )-> Option <$DstT > { Some (* self as $DstT )})*}} +macro_rules! __ra_macro_fixture497 {($($method : ident ()-> $ret : expr ; )*)=>{$(# [ inline ] fn $method ()-> Self {$ret })*}; } +macro_rules! __ra_macro_fixture498 {($(Self :: $method : ident ( self $(, $arg : ident : $ty : ty )* )-> $ret : ty ; )*)=>{$(# [ inline ] fn $method ( self $(, $arg : $ty )* )-> $ret { Self ::$method ( self $(, $arg )* )})*}; ($($base : ident :: $method : ident ( self $(, $arg : ident : $ty : ty )* )-> $ret : ty ; )*)=>{$(# [ inline ] fn $method ( self $(, $arg : $ty )* )-> $ret {< Self as $base >::$method ( self $(, $arg )* )})*}; ($($base : ident :: $method : ident ($($arg : ident : $ty : ty ),* )-> $ret : ty ; )*)=>{$(# [ inline ] fn $method ($($arg : $ty ),* )-> $ret {< Self as $base >::$method ($($arg ),* )})*}} +macro_rules! __ra_macro_fixture499 {($tyname : ident , $($($field : ident ).+),*)=>{ fn fmt (& self , f : & mut :: std :: fmt :: Formatter )-> :: std :: fmt :: Result { f . debug_struct ( stringify ! ($tyname ))$(. field ( stringify ! ($($field ).+), & self .$($field ).+))* . finish ()}}} +macro_rules! __ra_macro_fixture500 {($($field : ident ),*)=>{ fn clone (& self )-> Self { Self {$($field : self .$field . clone (),)* }}}} +macro_rules! __ra_macro_fixture501 {($($json : tt )+)=>{ json_internal ! ($($json )+)}; } +macro_rules! __ra_macro_fixture502 {(@ array [$($elems : expr ,)*])=>{ json_internal_vec ! [$($elems ,)*]}; (@ array [$($elems : expr ),*])=>{ json_internal_vec ! [$($elems ),*]}; (@ array [$($elems : expr ,)*] null $($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ( null )]$($rest )*)}; (@ array [$($elems : expr ,)*] true $($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ( true )]$($rest )*)}; (@ array [$($elems : expr ,)*] false $($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ( false )]$($rest )*)}; (@ array [$($elems : expr ,)*][$($array : tt )*]$($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ([$($array )*])]$($rest )*)}; (@ array [$($elems : expr ,)*]{$($map : tt )*}$($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ({$($map )*})]$($rest )*)}; (@ array [$($elems : expr ,)*]$next : expr , $($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ($next ),]$($rest )*)}; (@ array [$($elems : expr ,)*]$last : expr )=>{ json_internal ! (@ array [$($elems ,)* json_internal ! ($last )])}; (@ array [$($elems : expr ),*], $($rest : tt )*)=>{ json_internal ! (@ array [$($elems ,)*]$($rest )*)}; (@ array [$($elems : expr ),*]$unexpected : tt $($rest : tt )*)=>{ json_unexpected ! ($unexpected )}; (@ object $object : ident ()()())=>{}; (@ object $object : ident [$($key : tt )+]($value : expr ), $($rest : tt )*)=>{ let _ = $object . insert (($($key )+). into (), $value ); json_internal ! (@ object $object ()($($rest )*)($($rest )*)); }; (@ object $object : ident [$($key : tt )+]($value : expr )$unexpected : tt $($rest : tt )*)=>{ json_unexpected ! ($unexpected ); }; (@ object $object : ident [$($key : tt )+]($value : expr ))=>{ let _ = $object . insert (($($key )+). into (), $value ); }; (@ object $object : ident ($($key : tt )+)(: null $($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ( null ))$($rest )*); }; (@ object $object : ident ($($key : tt )+)(: true $($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ( true ))$($rest )*); }; (@ object $object : ident ($($key : tt )+)(: false $($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ( false ))$($rest )*); }; (@ object $object : ident ($($key : tt )+)(: [$($array : tt )*]$($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ([$($array )*]))$($rest )*); }; (@ object $object : ident ($($key : tt )+)(: {$($map : tt )*}$($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ({$($map )*}))$($rest )*); }; (@ object $object : ident ($($key : tt )+)(: $value : expr , $($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ($value )), $($rest )*); }; (@ object $object : ident ($($key : tt )+)(: $value : expr )$copy : tt )=>{ json_internal ! (@ object $object [$($key )+]( json_internal ! ($value ))); }; (@ object $object : ident ($($key : tt )+)(:)$copy : tt )=>{ json_internal ! (); }; (@ object $object : ident ($($key : tt )+)()$copy : tt )=>{ json_internal ! (); }; (@ object $object : ident ()(: $($rest : tt )*)($colon : tt $($copy : tt )*))=>{ json_unexpected ! ($colon ); }; (@ object $object : ident ($($key : tt )*)(, $($rest : tt )*)($comma : tt $($copy : tt )*))=>{ json_unexpected ! ($comma ); }; (@ object $object : ident ()(($key : expr ): $($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object ($key )(: $($rest )*)(: $($rest )*)); }; (@ object $object : ident ($($key : tt )*)(: $($unexpected : tt )+)$copy : tt )=>{ json_expect_expr_comma ! ($($unexpected )+); }; (@ object $object : ident ($($key : tt )*)($tt : tt $($rest : tt )*)$copy : tt )=>{ json_internal ! (@ object $object ($($key )* $tt )($($rest )*)($($rest )*)); }; ( null )=>{$crate :: Value :: Null }; ( true )=>{$crate :: Value :: Bool ( true )}; ( false )=>{$crate :: Value :: Bool ( false )}; ([])=>{$crate :: Value :: Array ( json_internal_vec ! [])}; ([$($tt : tt )+ ])=>{$crate :: Value :: Array ( json_internal ! (@ array []$($tt )+))}; ({})=>{$crate :: Value :: Object ($crate :: Map :: new ())}; ({$($tt : tt )+ })=>{$crate :: Value :: Object ({ let mut object = $crate :: Map :: new (); json_internal ! (@ object object ()($($tt )+)($($tt )+)); object })}; ($other : expr )=>{$crate :: to_value (&$other ). unwrap ()}; } +macro_rules! __ra_macro_fixture503 {($($content : tt )*)=>{ vec ! [$($content )*]}; } +macro_rules! __ra_macro_fixture504 {($($cfg : tt )*)=>{}; } +macro_rules! __ra_macro_fixture505 {($($tokens : tt )*)=>{$crate :: crossbeam_channel_internal ! ($($tokens )* )}; } +macro_rules! __ra_macro_fixture506 {(@ list ()($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ case ($($head )*)()())}; (@ list ( default =>$($tail : tt )*)($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ list ( default ()=>$($tail )*)($($head )*))}; (@ list ( default -> $($tail : tt )*)($($head : tt )*))=>{ compile_error ! ( "expected `=>` after `default` case, found `->`" )}; (@ list ( default $args : tt -> $($tail : tt )*)($($head : tt )*))=>{ compile_error ! ( "expected `=>` after `default` case, found `->`" )}; (@ list ( recv ($($args : tt )*)=>$($tail : tt )*)($($head : tt )*))=>{ compile_error ! ( "expected `->` after `recv` case, found `=>`" )}; (@ list ( send ($($args : tt )*)=>$($tail : tt )*)($($head : tt )*))=>{ compile_error ! ( "expected `->` after `send` operation, found `=>`" )}; (@ list ($case : ident $args : tt -> $res : tt -> $($tail : tt )*)($($head : tt )*))=>{ compile_error ! ( "expected `=>`, found `->`" )}; (@ list ($case : ident $args : tt $(-> $res : pat )* =>$body : block ; $($tail : tt )*)($($head : tt )*))=>{ compile_error ! ( "did you mean to put a comma instead of the semicolon after `}`?" )}; (@ list ($case : ident ($($args : tt )*)$(-> $res : pat )* =>$body : expr , $($tail : tt )*)($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ list ($($tail )*)($($head )* $case ($($args )*)$(-> $res )* =>{$body },))}; (@ list ($case : ident ($($args : tt )*)$(-> $res : pat )* =>$body : block $($tail : tt )*)($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ list ($($tail )*)($($head )* $case ($($args )*)$(-> $res )* =>{$body },))}; (@ list ($case : ident ($($args : tt )*)$(-> $res : pat )* =>$body : expr )($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ list ()($($head )* $case ($($args )*)$(-> $res )* =>{$body },))}; (@ list ($case : ident ($($args : tt )*)$(-> $res : pat )* =>$body : expr ,)($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ list ()($($head )* $case ($($args )*)$(-> $res )* =>{$body },))}; (@ list ($($tail : tt )*)($($head : tt )*))=>{$crate :: crossbeam_channel_internal ! (@ list_error1 $($tail )*)}; (@ list_error1 recv $($tail : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list_error2 recv $($tail )*)}; (@ list_error1 send $($tail : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list_error2 send $($tail )*)}; (@ list_error1 default $($tail : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list_error2 default $($tail )*)}; (@ list_error1 $t : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected one of `recv`, `send`, or `default`, found `" , stringify ! ($t ), "`" , ))}; (@ list_error1 $($tail : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list_error2 $($tail )*); }; (@ list_error2 $case : ident )=>{ compile_error ! ( concat ! ( "missing argument list after `" , stringify ! ($case ), "`" , ))}; (@ list_error2 $case : ident =>$($tail : tt )*)=>{ compile_error ! ( concat ! ( "missing argument list after `" , stringify ! ($case ), "`" , ))}; (@ list_error2 $($tail : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list_error3 $($tail )*)}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )*)=>{ compile_error ! ( concat ! ( "missing `=>` after `" , stringify ! ($case ), "` case" , ))}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>)=>{ compile_error ! ( "expected expression after `=>`" )}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>$body : expr ; $($tail : tt )*)=>{ compile_error ! ( concat ! ( "did you mean to put a comma instead of the semicolon after `" , stringify ! ($body ), "`?" , ))}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* => recv ($($a : tt )*)$($tail : tt )*)=>{ compile_error ! ( "expected an expression after `=>`" )}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* => send ($($a : tt )*)$($tail : tt )*)=>{ compile_error ! ( "expected an expression after `=>`" )}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* => default ($($a : tt )*)$($tail : tt )*)=>{ compile_error ! ( "expected an expression after `=>`" )}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>$f : ident ($($a : tt )*)$($tail : tt )*)=>{ compile_error ! ( concat ! ( "did you mean to put a comma after `" , stringify ! ($f ), "(" , stringify ! ($($a )*), ")`?" , ))}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>$f : ident ! ($($a : tt )*)$($tail : tt )*)=>{ compile_error ! ( concat ! ( "did you mean to put a comma after `" , stringify ! ($f ), "!(" , stringify ! ($($a )*), ")`?" , ))}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>$f : ident ! [$($a : tt )*]$($tail : tt )*)=>{ compile_error ! ( concat ! ( "did you mean to put a comma after `" , stringify ! ($f ), "![" , stringify ! ($($a )*), "]`?" , ))}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>$f : ident ! {$($a : tt )*}$($tail : tt )*)=>{ compile_error ! ( concat ! ( "did you mean to put a comma after `" , stringify ! ($f ), "!{" , stringify ! ($($a )*), "}`?" , ))}; (@ list_error3 $case : ident ($($args : tt )*)$(-> $r : pat )* =>$body : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "did you mean to put a comma after `" , stringify ! ($body ), "`?" , ))}; (@ list_error3 $case : ident ($($args : tt )*)-> =>$($tail : tt )*)=>{ compile_error ! ( "missing pattern after `->`" )}; (@ list_error3 $case : ident ($($args : tt )*)$t : tt $(-> $r : pat )* =>$($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected `->`, found `" , stringify ! ($t ), "`" , ))}; (@ list_error3 $case : ident ($($args : tt )*)-> $t : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected a pattern, found `" , stringify ! ($t ), "`" , ))}; (@ list_error3 recv ($($args : tt )*)$t : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected `->`, found `" , stringify ! ($t ), "`" , ))}; (@ list_error3 send ($($args : tt )*)$t : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected `->`, found `" , stringify ! ($t ), "`" , ))}; (@ list_error3 recv $args : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected an argument list after `recv`, found `" , stringify ! ($args ), "`" , ))}; (@ list_error3 send $args : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected an argument list after `send`, found `" , stringify ! ($args ), "`" , ))}; (@ list_error3 default $args : tt $($tail : tt )*)=>{ compile_error ! ( concat ! ( "expected an argument list or `=>` after `default`, found `" , stringify ! ($args ), "`" , ))}; (@ list_error3 $($tail : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list_error4 $($tail )*)}; (@ list_error4 $($tail : tt )*)=>{ compile_error ! ( "invalid syntax" )}; (@ case ()$cases : tt $default : tt )=>{$crate :: crossbeam_channel_internal ! (@ init $cases $default )}; (@ case ( recv ($r : expr )-> $res : pat =>$body : tt , $($tail : tt )*)($($cases : tt )*)$default : tt )=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)($($cases )* recv ($r )-> $res =>$body ,)$default )}; (@ case ( recv ($r : expr ,)-> $res : pat =>$body : tt , $($tail : tt )*)($($cases : tt )*)$default : tt )=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)($($cases )* recv ($r )-> $res =>$body ,)$default )}; (@ case ( recv ($($args : tt )*)-> $res : pat =>$body : tt , $($tail : tt )*)($($cases : tt )*)$default : tt )=>{ compile_error ! ( concat ! ( "invalid argument list in `recv(" , stringify ! ($($args )*), ")`" , ))}; (@ case ( recv $t : tt $($tail : tt )*)($($cases : tt )*)$default : tt )=>{ compile_error ! ( concat ! ( "expected an argument list after `recv`, found `" , stringify ! ($t ), "`" , ))}; (@ case ( send ($s : expr , $m : expr )-> $res : pat =>$body : tt , $($tail : tt )*)($($cases : tt )*)$default : tt )=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)($($cases )* send ($s , $m )-> $res =>$body ,)$default )}; (@ case ( send ($s : expr , $m : expr ,)-> $res : pat =>$body : tt , $($tail : tt )*)($($cases : tt )*)$default : tt )=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)($($cases )* send ($s , $m )-> $res =>$body ,)$default )}; (@ case ( send ($($args : tt )*)-> $res : pat =>$body : tt , $($tail : tt )*)($($cases : tt )*)$default : tt )=>{ compile_error ! ( concat ! ( "invalid argument list in `send(" , stringify ! ($($args )*), ")`" , ))}; (@ case ( send $t : tt $($tail : tt )*)($($cases : tt )*)$default : tt )=>{ compile_error ! ( concat ! ( "expected an argument list after `send`, found `" , stringify ! ($t ), "`" , ))}; (@ case ( default ()=>$body : tt , $($tail : tt )*)$cases : tt ())=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)$cases ( default ()=>$body ,))}; (@ case ( default ($timeout : expr )=>$body : tt , $($tail : tt )*)$cases : tt ())=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)$cases ( default ($timeout )=>$body ,))}; (@ case ( default ($timeout : expr ,)=>$body : tt , $($tail : tt )*)$cases : tt ())=>{$crate :: crossbeam_channel_internal ! (@ case ($($tail )*)$cases ( default ($timeout )=>$body ,))}; (@ case ( default $($tail : tt )*)$cases : tt ($($def : tt )+))=>{ compile_error ! ( "there can be only one `default` case in a `select!` block" )}; (@ case ( default ($($args : tt )*)=>$body : tt , $($tail : tt )*)$cases : tt $default : tt )=>{ compile_error ! ( concat ! ( "invalid argument list in `default(" , stringify ! ($($args )*), ")`" , ))}; (@ case ( default $t : tt $($tail : tt )*)$cases : tt $default : tt )=>{ compile_error ! ( concat ! ( "expected an argument list or `=>` after `default`, found `" , stringify ! ($t ), "`" , ))}; (@ case ($case : ident $($tail : tt )*)$cases : tt $default : tt )=>{ compile_error ! ( concat ! ( "expected one of `recv`, `send`, or `default`, found `" , stringify ! ($case ), "`" , ))}; (@ init ( recv ($r : expr )-> $res : pat =>$recv_body : tt ,)( default ()=>$default_body : tt ,))=>{{ match $r { ref _r =>{ let _r : &$crate :: Receiver <_> = _r ; match _r . try_recv (){:: std :: result :: Result :: Err ($crate :: TryRecvError :: Empty )=>{$default_body } _res =>{ let _res = _res . map_err (|_| $crate :: RecvError ); let $res = _res ; $recv_body }}}}}}; (@ init ( recv ($r : expr )-> $res : pat =>$body : tt ,)())=>{{ match $r { ref _r =>{ let _r : &$crate :: Receiver <_> = _r ; let _res = _r . recv (); let $res = _res ; $body }}}}; (@ init ( recv ($r : expr )-> $res : pat =>$recv_body : tt ,)( default ($timeout : expr )=>$default_body : tt ,))=>{{ match $r { ref _r =>{ let _r : &$crate :: Receiver <_> = _r ; match _r . recv_timeout ($timeout ){:: std :: result :: Result :: Err ($crate :: RecvTimeoutError :: Timeout )=>{$default_body } _res =>{ let _res = _res . map_err (|_| $crate :: RecvError ); let $res = _res ; $recv_body }}}}}}; (@ init ($($cases : tt )*)$default : tt )=>{{ const _LEN : usize = $crate :: crossbeam_channel_internal ! (@ count ($($cases )*)); let _handle : &$crate :: internal :: SelectHandle = &$crate :: never ::< ()> (); # [ allow ( unused_mut )] let mut _sel = [( _handle , 0 , :: std :: ptr :: null ()); _LEN ]; $crate :: crossbeam_channel_internal ! (@ add _sel ($($cases )*)$default (( 0usize _oper0 )( 1usize _oper1 )( 2usize _oper2 )( 3usize _oper3 )( 4usize _oper4 )( 5usize _oper5 )( 6usize _oper6 )( 7usize _oper7 )( 8usize _oper8 )( 9usize _oper9 )( 10usize _oper10 )( 11usize _oper11 )( 12usize _oper12 )( 13usize _oper13 )( 14usize _oper14 )( 15usize _oper15 )( 16usize _oper16 )( 17usize _oper17 )( 18usize _oper18 )( 19usize _oper19 )( 20usize _oper20 )( 21usize _oper21 )( 22usize _oper22 )( 23usize _oper23 )( 24usize _oper24 )( 25usize _oper25 )( 26usize _oper26 )( 27usize _oper27 )( 28usize _oper28 )( 29usize _oper29 )( 30usize _oper30 )( 31usize _oper31 ))())}}; (@ count ())=>{ 0 }; (@ count ($oper : ident $args : tt -> $res : pat =>$body : tt , $($cases : tt )*))=>{ 1 + $crate :: crossbeam_channel_internal ! (@ count ($($cases )*))}; (@ add $sel : ident ()()$labels : tt $cases : tt )=>{{ let _oper : $crate :: SelectedOperation < '_ > = { let _oper = $crate :: internal :: select (& mut $sel ); unsafe {:: std :: mem :: transmute ( _oper )}}; $crate :: crossbeam_channel_internal ! {@ complete $sel _oper $cases }}}; (@ add $sel : ident ()( default ()=>$body : tt ,)$labels : tt $cases : tt )=>{{ let _oper : :: std :: option :: Option <$crate :: SelectedOperation < '_ >> = { let _oper = $crate :: internal :: try_select (& mut $sel ); unsafe {:: std :: mem :: transmute ( _oper )}}; match _oper { None =>{{$sel }; $body } Some ( _oper )=>{$crate :: crossbeam_channel_internal ! {@ complete $sel _oper $cases }}}}}; (@ add $sel : ident ()( default ($timeout : expr )=>$body : tt ,)$labels : tt $cases : tt )=>{{ let _oper : :: std :: option :: Option <$crate :: SelectedOperation < '_ >> = { let _oper = $crate :: internal :: select_timeout (& mut $sel , $timeout ); unsafe {:: std :: mem :: transmute ( _oper )}}; match _oper {:: std :: option :: Option :: None =>{{$sel }; $body }:: std :: option :: Option :: Some ( _oper )=>{$crate :: crossbeam_channel_internal ! {@ complete $sel _oper $cases }}}}}; (@ add $sel : ident $input : tt $default : tt ()$cases : tt )=>{ compile_error ! ( "too many operations in a `select!` block" )}; (@ add $sel : ident ( recv ($r : expr )-> $res : pat =>$body : tt , $($tail : tt )*)$default : tt (($i : tt $var : ident )$($labels : tt )*)($($cases : tt )*))=>{{ match $r { ref _r =>{ let $var : &$crate :: Receiver <_> = unsafe { let _r : &$crate :: Receiver <_> = _r ; unsafe fn unbind < 'a , T > ( x : & T )-> & 'a T {:: std :: mem :: transmute ( x )} unbind ( _r )}; $sel [$i ]= ($var , $i , $var as * const $crate :: Receiver <_> as * const u8 ); $crate :: crossbeam_channel_internal ! (@ add $sel ($($tail )*)$default ($($labels )*)($($cases )* [$i ] recv ($var )-> $res =>$body ,))}}}}; (@ add $sel : ident ( send ($s : expr , $m : expr )-> $res : pat =>$body : tt , $($tail : tt )*)$default : tt (($i : tt $var : ident )$($labels : tt )*)($($cases : tt )*))=>{{ match $s { ref _s =>{ let $var : &$crate :: Sender <_> = unsafe { let _s : &$crate :: Sender <_> = _s ; unsafe fn unbind < 'a , T > ( x : & T )-> & 'a T {:: std :: mem :: transmute ( x )} unbind ( _s )}; $sel [$i ]= ($var , $i , $var as * const $crate :: Sender <_> as * const u8 ); $crate :: crossbeam_channel_internal ! (@ add $sel ($($tail )*)$default ($($labels )*)($($cases )* [$i ] send ($var , $m )-> $res =>$body ,))}}}}; (@ complete $sel : ident $oper : ident ([$i : tt ] recv ($r : ident )-> $res : pat =>$body : tt , $($tail : tt )*))=>{{ if $oper . index ()== $i { let _res = $oper . recv ($r ); {$sel }; let $res = _res ; $body } else {$crate :: crossbeam_channel_internal ! {@ complete $sel $oper ($($tail )*)}}}}; (@ complete $sel : ident $oper : ident ([$i : tt ] send ($s : ident , $m : expr )-> $res : pat =>$body : tt , $($tail : tt )*))=>{{ if $oper . index ()== $i { let _res = $oper . send ($s , $m ); {$sel }; let $res = _res ; $body } else {$crate :: crossbeam_channel_internal ! {@ complete $sel $oper ($($tail )*)}}}}; (@ complete $sel : ident $oper : ident ())=>{{ unreachable ! ( "internal error in crossbeam-channel: invalid case" )}}; (@$($tokens : tt )*)=>{ compile_error ! ( concat ! ( "internal error in crossbeam-channel: " , stringify ! (@$($tokens )*), ))}; ()=>{ compile_error ! ( "empty `select!` block" )}; ($($case : ident $(($($args : tt )*))* =>$body : expr $(,)*)*)=>{$crate :: crossbeam_channel_internal ! (@ list ($($case $(($($args )*))* =>{$body },)*)())}; ($($tokens : tt )*)=>{$crate :: crossbeam_channel_internal ! (@ list ($($tokens )*)())}; } +macro_rules! __ra_macro_fixture507 {($($tokens : tt )*)=>{ return Err ( crate :: errors :: error ! ($($tokens )*))}} +macro_rules! __ra_macro_fixture508 {($fmt : expr )=>{$crate :: SsrError :: new ( format ! ($fmt ))}; ($fmt : expr , $($arg : tt )+)=>{$crate :: SsrError :: new ( format ! ($fmt , $($arg )+))}} +macro_rules! __ra_macro_fixture509 {[;]=>{$crate :: SyntaxKind :: SEMICOLON }; [,]=>{$crate :: SyntaxKind :: COMMA }; [ '(' ]=>{$crate :: SyntaxKind :: L_PAREN }; [ ')' ]=>{$crate :: SyntaxKind :: R_PAREN }; [ '{' ]=>{$crate :: SyntaxKind :: L_CURLY }; [ '}' ]=>{$crate :: SyntaxKind :: R_CURLY }; [ '[' ]=>{$crate :: SyntaxKind :: L_BRACK }; [ ']' ]=>{$crate :: SyntaxKind :: R_BRACK }; [<]=>{$crate :: SyntaxKind :: L_ANGLE }; [>]=>{$crate :: SyntaxKind :: R_ANGLE }; [@]=>{$crate :: SyntaxKind :: AT }; [#]=>{$crate :: SyntaxKind :: POUND }; [~]=>{$crate :: SyntaxKind :: TILDE }; [?]=>{$crate :: SyntaxKind :: QUESTION }; [$]=>{$crate :: SyntaxKind :: DOLLAR }; [&]=>{$crate :: SyntaxKind :: AMP }; [|]=>{$crate :: SyntaxKind :: PIPE }; [+]=>{$crate :: SyntaxKind :: PLUS }; [*]=>{$crate :: SyntaxKind :: STAR }; [/]=>{$crate :: SyntaxKind :: SLASH }; [^]=>{$crate :: SyntaxKind :: CARET }; [%]=>{$crate :: SyntaxKind :: PERCENT }; [_]=>{$crate :: SyntaxKind :: UNDERSCORE }; [.]=>{$crate :: SyntaxKind :: DOT }; [..]=>{$crate :: SyntaxKind :: DOT2 }; [...]=>{$crate :: SyntaxKind :: DOT3 }; [..=]=>{$crate :: SyntaxKind :: DOT2EQ }; [:]=>{$crate :: SyntaxKind :: COLON }; [::]=>{$crate :: SyntaxKind :: COLON2 }; [=]=>{$crate :: SyntaxKind :: EQ }; [==]=>{$crate :: SyntaxKind :: EQ2 }; [=>]=>{$crate :: SyntaxKind :: FAT_ARROW }; [!]=>{$crate :: SyntaxKind :: BANG }; [!=]=>{$crate :: SyntaxKind :: NEQ }; [-]=>{$crate :: SyntaxKind :: MINUS }; [->]=>{$crate :: SyntaxKind :: THIN_ARROW }; [<=]=>{$crate :: SyntaxKind :: LTEQ }; [>=]=>{$crate :: SyntaxKind :: GTEQ }; [+=]=>{$crate :: SyntaxKind :: PLUSEQ }; [-=]=>{$crate :: SyntaxKind :: MINUSEQ }; [|=]=>{$crate :: SyntaxKind :: PIPEEQ }; [&=]=>{$crate :: SyntaxKind :: AMPEQ }; [^=]=>{$crate :: SyntaxKind :: CARETEQ }; [/=]=>{$crate :: SyntaxKind :: SLASHEQ }; [*=]=>{$crate :: SyntaxKind :: STAREQ }; [%=]=>{$crate :: SyntaxKind :: PERCENTEQ }; [&&]=>{$crate :: SyntaxKind :: AMP2 }; [||]=>{$crate :: SyntaxKind :: PIPE2 }; [<<]=>{$crate :: SyntaxKind :: SHL }; [>>]=>{$crate :: SyntaxKind :: SHR }; [<<=]=>{$crate :: SyntaxKind :: SHLEQ }; [>>=]=>{$crate :: SyntaxKind :: SHREQ }; [ as ]=>{$crate :: SyntaxKind :: AS_KW }; [ async ]=>{$crate :: SyntaxKind :: ASYNC_KW }; [ await ]=>{$crate :: SyntaxKind :: AWAIT_KW }; [ box ]=>{$crate :: SyntaxKind :: BOX_KW }; [ break ]=>{$crate :: SyntaxKind :: BREAK_KW }; [ const ]=>{$crate :: SyntaxKind :: CONST_KW }; [ continue ]=>{$crate :: SyntaxKind :: CONTINUE_KW }; [ crate ]=>{$crate :: SyntaxKind :: CRATE_KW }; [ dyn ]=>{$crate :: SyntaxKind :: DYN_KW }; [ else ]=>{$crate :: SyntaxKind :: ELSE_KW }; [ enum ]=>{$crate :: SyntaxKind :: ENUM_KW }; [ extern ]=>{$crate :: SyntaxKind :: EXTERN_KW }; [ false ]=>{$crate :: SyntaxKind :: FALSE_KW }; [ fn ]=>{$crate :: SyntaxKind :: FN_KW }; [ for ]=>{$crate :: SyntaxKind :: FOR_KW }; [ if ]=>{$crate :: SyntaxKind :: IF_KW }; [ impl ]=>{$crate :: SyntaxKind :: IMPL_KW }; [ in ]=>{$crate :: SyntaxKind :: IN_KW }; [ let ]=>{$crate :: SyntaxKind :: LET_KW }; [ loop ]=>{$crate :: SyntaxKind :: LOOP_KW }; [ macro ]=>{$crate :: SyntaxKind :: MACRO_KW }; [ match ]=>{$crate :: SyntaxKind :: MATCH_KW }; [ mod ]=>{$crate :: SyntaxKind :: MOD_KW }; [ move ]=>{$crate :: SyntaxKind :: MOVE_KW }; [ mut ]=>{$crate :: SyntaxKind :: MUT_KW }; [ pub ]=>{$crate :: SyntaxKind :: PUB_KW }; [ ref ]=>{$crate :: SyntaxKind :: REF_KW }; [ return ]=>{$crate :: SyntaxKind :: RETURN_KW }; [ self ]=>{$crate :: SyntaxKind :: SELF_KW }; [ static ]=>{$crate :: SyntaxKind :: STATIC_KW }; [ struct ]=>{$crate :: SyntaxKind :: STRUCT_KW }; [ super ]=>{$crate :: SyntaxKind :: SUPER_KW }; [ trait ]=>{$crate :: SyntaxKind :: TRAIT_KW }; [ true ]=>{$crate :: SyntaxKind :: TRUE_KW }; [ try ]=>{$crate :: SyntaxKind :: TRY_KW }; [ type ]=>{$crate :: SyntaxKind :: TYPE_KW }; [ unsafe ]=>{$crate :: SyntaxKind :: UNSAFE_KW }; [ use ]=>{$crate :: SyntaxKind :: USE_KW }; [ where ]=>{$crate :: SyntaxKind :: WHERE_KW }; [ while ]=>{$crate :: SyntaxKind :: WHILE_KW }; [ yield ]=>{$crate :: SyntaxKind :: YIELD_KW }; [ auto ]=>{$crate :: SyntaxKind :: AUTO_KW }; [ default ]=>{$crate :: SyntaxKind :: DEFAULT_KW }; [ existential ]=>{$crate :: SyntaxKind :: EXISTENTIAL_KW }; [ union ]=>{$crate :: SyntaxKind :: UNION_KW }; [ raw ]=>{$crate :: SyntaxKind :: RAW_KW }; [ macro_rules ]=>{$crate :: SyntaxKind :: MACRO_RULES_KW }; [ lifetime_ident ]=>{$crate :: SyntaxKind :: LIFETIME_IDENT }; [ ident ]=>{$crate :: SyntaxKind :: IDENT }; [ shebang ]=>{$crate :: SyntaxKind :: SHEBANG }; } +macro_rules! __ra_macro_fixture510 {($($args : tt )*)=>{ return Err ( match_error ! ($($args )*))}; } +macro_rules! __ra_macro_fixture511 {($e : expr )=>{{ MatchFailed { reason : if recording_match_fail_reasons (){ Some ( format ! ( "{}" , $e ))} else { None }}}}; ($fmt : expr , $($arg : tt )+)=>{{ MatchFailed { reason : if recording_match_fail_reasons (){ Some ( format ! ($fmt , $($arg )+))} else { None }}}}; } +macro_rules! __ra_macro_fixture512 {()=>($crate :: print ! ( "\n" )); ($($arg : tt )*)=>({$crate :: io :: _print ($crate :: format_args_nl ! ($($arg )*)); })} +macro_rules! __ra_macro_fixture513 {($cmd : tt )=>{{# [ cfg ( trick_rust_analyzer_into_highlighting_interpolated_bits )] format_args ! ($cmd ); use $crate :: Cmd as __CMD ; let cmd : $crate :: Cmd = $crate :: __cmd ! ( __CMD $cmd ); cmd }}; } +macro_rules! __ra_macro_fixture514 {($reader : ident , $s : ident ;)=>{}; ($reader : ident , $s : ident ; $first : ident : $first_ty : ty $(, $rest : ident : $rest_ty : ty )*)=>{ reverse_decode ! ($reader , $s ; $($rest : $rest_ty ),*); let $first = <$first_ty >:: decode (& mut $reader , $s ); }} +macro_rules! __ra_macro_fixture515 {($kind : ident , $($ty : ty ),*)=>{ match $kind {$(stringify ! ($ty )=>{ let n : $ty = n . parse (). unwrap (); format ! ( concat ! ( "{}" , stringify ! ($ty )), n )})* _ => unimplemented ! ( "unknown args for typed_integer: n {}, kind {}" , n , $kind ), }}} +macro_rules! __ra_macro_fixture516 {()=>( panic ! ( "not implemented" )); ($($arg : tt )+)=>( panic ! ( "not implemented: {}" , $crate :: format_args ! ($($arg )+))); } +macro_rules! __ra_macro_fixture517 {($cond : expr )=>{{ let cond = !$crate :: always ! (!$cond ); cond }}; ($cond : expr , $fmt : literal $($arg : tt )*)=>{{ let cond = !$crate :: always ! (!$cond , $fmt $($arg )*); cond }}; } +macro_rules! __ra_macro_fixture518 {($cond : expr )=>{$crate :: always ! ($cond , "assertion failed: {}" , stringify ! ($cond ))}; ($cond : expr , $fmt : literal $($arg : tt )*)=>{{ let cond = $cond ; if cfg ! ( debug_assertions )|| $crate :: __FORCE { assert ! ( cond , $fmt $($arg )*); } if ! cond {$crate :: __log_error ! ($fmt $($arg )*); } cond }}; } +macro_rules! __ra_macro_fixture519 {($msg : literal $(,)?)=>{ return $crate :: private :: Err ($crate :: anyhow ! ($msg ))}; ($err : expr $(,)?)=>{ return $crate :: private :: Err ($crate :: anyhow ! ($err ))}; ($fmt : expr , $($arg : tt )*)=>{ return $crate :: private :: Err ($crate :: anyhow ! ($fmt , $($arg )*))}; } +macro_rules! __ra_macro_fixture520 {($msg : literal $(,)?)=>{$crate :: private :: new_adhoc ($msg )}; ($err : expr $(,)?)=>({ use $crate :: private :: kind ::*; match $err { error =>(& error ). anyhow_kind (). new ( error ), }}); ($fmt : expr , $($arg : tt )*)=>{$crate :: private :: new_adhoc ( format ! ($fmt , $($arg )*))}; } +macro_rules! __ra_macro_fixture521 {( target : $target : expr , $($arg : tt )+)=>( log ! ( target : $target , $crate :: Level :: Info , $($arg )+)); ($($arg : tt )+)=>( log ! ($crate :: Level :: Info , $($arg )+))} +macro_rules! __ra_macro_fixture522 {[$($sl : expr , $sc : expr ; $el : expr , $ec : expr =>$text : expr ),+]=>{ vec ! [$(TextDocumentContentChangeEvent { range : Some ( Range { start : Position { line : $sl , character : $sc }, end : Position { line : $el , character : $ec }, }), range_length : None , text : String :: from ($text ), }),+]}; } +macro_rules! __ra_macro_fixture523 {[$path : expr ]=>{$crate :: ExpectFile { path : std :: path :: PathBuf :: from ($path ), position : file ! (), }}; } +macro_rules! __ra_macro_fixture524 {($($key : literal : $value : tt ),*$(,)?)=>{{$(map . insert ($key . into (), serde_json :: json ! ($value )); )*}}; } +macro_rules! __ra_macro_fixture525 {($expr : expr , $or : expr )=>{ try_ ! ($expr ). unwrap_or ($or )}; } +macro_rules! __ra_macro_fixture526 {($expr : expr )=>{|| -> _ { Some ($expr )}()}; } +macro_rules! __ra_macro_fixture527 {($($arg : tt )*)=>($crate :: io :: _print ($crate :: format_args ! ($($arg )*))); } +macro_rules! __ra_macro_fixture528 {($fmt : literal , $($tt : tt ),*)=>{ mbe :: ExpandError :: ProcMacroError ( tt :: ExpansionError :: Unknown ( format ! ($fmt , $($tt ),*)))}; ($fmt : literal )=>{ mbe :: ExpandError :: ProcMacroError ( tt :: ExpansionError :: Unknown ($fmt . to_string ()))}} +macro_rules! __ra_macro_fixture529 {($($tt : tt )* )=>{$crate :: quote :: IntoTt :: to_subtree ($crate :: __quote ! ($($tt )*))}} +macro_rules! __ra_macro_fixture530 {()=>{ Vec ::< tt :: TokenTree >:: new ()}; (@ SUBTREE $delim : ident $($tt : tt )* )=>{{ let children = $crate :: __quote ! ($($tt )*); tt :: Subtree { delimiter : Some ( tt :: Delimiter { kind : tt :: DelimiterKind ::$delim , id : tt :: TokenId :: unspecified (), }), token_trees : $crate :: quote :: IntoTt :: to_tokens ( children ), }}}; (@ PUNCT $first : literal )=>{{ vec ! [ tt :: Leaf :: Punct ( tt :: Punct { char : $first , spacing : tt :: Spacing :: Alone , id : tt :: TokenId :: unspecified (), }). into ()]}}; (@ PUNCT $first : literal , $sec : literal )=>{{ vec ! [ tt :: Leaf :: Punct ( tt :: Punct { char : $first , spacing : tt :: Spacing :: Joint , id : tt :: TokenId :: unspecified (), }). into (), tt :: Leaf :: Punct ( tt :: Punct { char : $sec , spacing : tt :: Spacing :: Alone , id : tt :: TokenId :: unspecified (), }). into ()]}}; (# $first : ident $($tail : tt )* )=>{{ let token = $crate :: quote :: ToTokenTree :: to_token ($first ); let mut tokens = vec ! [ token . into ()]; let mut tail_tokens = $crate :: quote :: IntoTt :: to_tokens ($crate :: __quote ! ($($tail )*)); tokens . append (& mut tail_tokens ); tokens }}; (## $first : ident $($tail : tt )* )=>{{ let mut tokens = $first . into_iter (). map ($crate :: quote :: ToTokenTree :: to_token ). collect ::< Vec < tt :: TokenTree >> (); let mut tail_tokens = $crate :: quote :: IntoTt :: to_tokens ($crate :: __quote ! ($($tail )*)); tokens . append (& mut tail_tokens ); tokens }}; ({$($tt : tt )* })=>{$crate :: __quote ! (@ SUBTREE Brace $($tt )*)}; ([$($tt : tt )* ])=>{$crate :: __quote ! (@ SUBTREE Bracket $($tt )*)}; (($($tt : tt )* ))=>{$crate :: __quote ! (@ SUBTREE Parenthesis $($tt )*)}; ($tt : literal )=>{ vec ! [$crate :: quote :: ToTokenTree :: to_token ($tt ). into ()]}; ($tt : ident )=>{ vec ! [{ tt :: Leaf :: Ident ( tt :: Ident { text : stringify ! ($tt ). into (), id : tt :: TokenId :: unspecified (), }). into ()}]}; (-> )=>{$crate :: __quote ! (@ PUNCT '-' , '>' )}; (& )=>{$crate :: __quote ! (@ PUNCT '&' )}; (, )=>{$crate :: __quote ! (@ PUNCT ',' )}; (: )=>{$crate :: __quote ! (@ PUNCT ':' )}; (; )=>{$crate :: __quote ! (@ PUNCT ';' )}; (:: )=>{$crate :: __quote ! (@ PUNCT ':' , ':' )}; (. )=>{$crate :: __quote ! (@ PUNCT '.' )}; (< )=>{$crate :: __quote ! (@ PUNCT '<' )}; (> )=>{$crate :: __quote ! (@ PUNCT '>' )}; ($first : tt $($tail : tt )+ )=>{{ let mut tokens = $crate :: quote :: IntoTt :: to_tokens ($crate :: __quote ! ($first )); let mut tail_tokens = $crate :: quote :: IntoTt :: to_tokens ($crate :: __quote ! ($($tail )*)); tokens . append (& mut tail_tokens ); tokens }}; } +macro_rules! __ra_macro_fixture531 {($($name : ident )*)=>{$(if let Some ( it )= & self .$name { f . field ( stringify ! ($name ), it ); })*}} +macro_rules! __ra_macro_fixture532 {($fmt : expr )=>{ RenameError ( format ! ($fmt ))}; ($fmt : expr , $($arg : tt )+)=>{ RenameError ( format ! ($fmt , $($arg )+))}} +macro_rules! __ra_macro_fixture533 {($($tokens : tt )*)=>{ return Err ( format_err ! ($($tokens )*))}} +macro_rules! __ra_macro_fixture534 {()=>{$crate :: __private :: TokenStream :: new ()}; ($($tt : tt )*)=>{{ let mut _s = $crate :: __private :: TokenStream :: new (); $crate :: quote_each_token ! ( _s $($tt )*); _s }}; } +macro_rules! __ra_macro_fixture535 {($tokens : ident $($tts : tt )*)=>{$crate :: quote_tokens_with_context ! ($tokens (@ @ @ @ @ @ $($tts )*)(@ @ @ @ @ $($tts )* @)(@ @ @ @ $($tts )* @ @)(@ @ @ $(($tts ))* @ @ @)(@ @ $($tts )* @ @ @ @)(@ $($tts )* @ @ @ @ @)($($tts )* @ @ @ @ @ @)); }; } +macro_rules! __ra_macro_fixture536 {($tokens : ident ($($b3 : tt )*)($($b2 : tt )*)($($b1 : tt )*)($($curr : tt )*)($($a1 : tt )*)($($a2 : tt )*)($($a3 : tt )*))=>{$($crate :: quote_token_with_context ! ($tokens $b3 $b2 $b1 $curr $a1 $a2 $a3 ); )* }; } +macro_rules! __ra_macro_fixture537 {($tokens : ident $b3 : tt $b2 : tt $b1 : tt @ $a1 : tt $a2 : tt $a3 : tt )=>{}; ($tokens : ident $b3 : tt $b2 : tt $b1 : tt (#)($($inner : tt )* )* $a3 : tt )=>{{ use $crate :: __private :: ext ::*; let has_iter = $crate :: __private :: ThereIsNoIteratorInRepetition ; $crate :: pounded_var_names ! ( quote_bind_into_iter ! ( has_iter )()$($inner )*); let _: $crate :: __private :: HasIterator = has_iter ; while true {$crate :: pounded_var_names ! ( quote_bind_next_or_break ! ()()$($inner )*); $crate :: quote_each_token ! ($tokens $($inner )*); }}}; ($tokens : ident $b3 : tt $b2 : tt # (($($inner : tt )* ))* $a2 : tt $a3 : tt )=>{}; ($tokens : ident $b3 : tt # ($($inner : tt )* )(*)$a1 : tt $a2 : tt $a3 : tt )=>{}; ($tokens : ident $b3 : tt $b2 : tt $b1 : tt (#)($($inner : tt )* )$sep : tt *)=>{{ use $crate :: __private :: ext ::*; let mut _i = 0usize ; let has_iter = $crate :: __private :: ThereIsNoIteratorInRepetition ; $crate :: pounded_var_names ! ( quote_bind_into_iter ! ( has_iter )()$($inner )*); let _: $crate :: __private :: HasIterator = has_iter ; while true {$crate :: pounded_var_names ! ( quote_bind_next_or_break ! ()()$($inner )*); if _i > 0 {$crate :: quote_token ! ($tokens $sep ); } _i += 1 ; $crate :: quote_each_token ! ($tokens $($inner )*); }}}; ($tokens : ident $b3 : tt $b2 : tt # (($($inner : tt )* ))$sep : tt * $a3 : tt )=>{}; ($tokens : ident $b3 : tt # ($($inner : tt )* )($sep : tt )* $a2 : tt $a3 : tt )=>{}; ($tokens : ident # ($($inner : tt )* )* (*)$a1 : tt $a2 : tt $a3 : tt )=>{$crate :: quote_token ! ($tokens *); }; ($tokens : ident # ($($inner : tt )* )$sep : tt (*)$a1 : tt $a2 : tt $a3 : tt )=>{}; ($tokens : ident $b3 : tt $b2 : tt $b1 : tt (#)$var : ident $a2 : tt $a3 : tt )=>{$crate :: ToTokens :: to_tokens (&$var , & mut $tokens ); }; ($tokens : ident $b3 : tt $b2 : tt # ($var : ident )$a1 : tt $a2 : tt $a3 : tt )=>{}; ($tokens : ident $b3 : tt $b2 : tt $b1 : tt ($curr : tt )$a1 : tt $a2 : tt $a3 : tt )=>{$crate :: quote_token ! ($tokens $curr ); }; } +macro_rules! __ra_macro_fixture538 {($tokens : ident ($($inner : tt )* ))=>{$crate :: __private :: push_group (& mut $tokens , $crate :: __private :: Delimiter :: Parenthesis , $crate :: quote ! ($($inner )*), ); }; ($tokens : ident [$($inner : tt )* ])=>{$crate :: __private :: push_group (& mut $tokens , $crate :: __private :: Delimiter :: Bracket , $crate :: quote ! ($($inner )*), ); }; ($tokens : ident {$($inner : tt )* })=>{$crate :: __private :: push_group (& mut $tokens , $crate :: __private :: Delimiter :: Brace , $crate :: quote ! ($($inner )*), ); }; ($tokens : ident +)=>{$crate :: __private :: push_add (& mut $tokens ); }; ($tokens : ident +=)=>{$crate :: __private :: push_add_eq (& mut $tokens ); }; ($tokens : ident &)=>{$crate :: __private :: push_and (& mut $tokens ); }; ($tokens : ident &&)=>{$crate :: __private :: push_and_and (& mut $tokens ); }; ($tokens : ident &=)=>{$crate :: __private :: push_and_eq (& mut $tokens ); }; ($tokens : ident @)=>{$crate :: __private :: push_at (& mut $tokens ); }; ($tokens : ident !)=>{$crate :: __private :: push_bang (& mut $tokens ); }; ($tokens : ident ^)=>{$crate :: __private :: push_caret (& mut $tokens ); }; ($tokens : ident ^=)=>{$crate :: __private :: push_caret_eq (& mut $tokens ); }; ($tokens : ident :)=>{$crate :: __private :: push_colon (& mut $tokens ); }; ($tokens : ident ::)=>{$crate :: __private :: push_colon2 (& mut $tokens ); }; ($tokens : ident ,)=>{$crate :: __private :: push_comma (& mut $tokens ); }; ($tokens : ident /)=>{$crate :: __private :: push_div (& mut $tokens ); }; ($tokens : ident /=)=>{$crate :: __private :: push_div_eq (& mut $tokens ); }; ($tokens : ident .)=>{$crate :: __private :: push_dot (& mut $tokens ); }; ($tokens : ident ..)=>{$crate :: __private :: push_dot2 (& mut $tokens ); }; ($tokens : ident ...)=>{$crate :: __private :: push_dot3 (& mut $tokens ); }; ($tokens : ident ..=)=>{$crate :: __private :: push_dot_dot_eq (& mut $tokens ); }; ($tokens : ident =)=>{$crate :: __private :: push_eq (& mut $tokens ); }; ($tokens : ident ==)=>{$crate :: __private :: push_eq_eq (& mut $tokens ); }; ($tokens : ident >=)=>{$crate :: __private :: push_ge (& mut $tokens ); }; ($tokens : ident >)=>{$crate :: __private :: push_gt (& mut $tokens ); }; ($tokens : ident <=)=>{$crate :: __private :: push_le (& mut $tokens ); }; ($tokens : ident <)=>{$crate :: __private :: push_lt (& mut $tokens ); }; ($tokens : ident *=)=>{$crate :: __private :: push_mul_eq (& mut $tokens ); }; ($tokens : ident !=)=>{$crate :: __private :: push_ne (& mut $tokens ); }; ($tokens : ident |)=>{$crate :: __private :: push_or (& mut $tokens ); }; ($tokens : ident |=)=>{$crate :: __private :: push_or_eq (& mut $tokens ); }; ($tokens : ident ||)=>{$crate :: __private :: push_or_or (& mut $tokens ); }; ($tokens : ident #)=>{$crate :: __private :: push_pound (& mut $tokens ); }; ($tokens : ident ?)=>{$crate :: __private :: push_question (& mut $tokens ); }; ($tokens : ident ->)=>{$crate :: __private :: push_rarrow (& mut $tokens ); }; ($tokens : ident <-)=>{$crate :: __private :: push_larrow (& mut $tokens ); }; ($tokens : ident %)=>{$crate :: __private :: push_rem (& mut $tokens ); }; ($tokens : ident %=)=>{$crate :: __private :: push_rem_eq (& mut $tokens ); }; ($tokens : ident =>)=>{$crate :: __private :: push_fat_arrow (& mut $tokens ); }; ($tokens : ident ;)=>{$crate :: __private :: push_semi (& mut $tokens ); }; ($tokens : ident <<)=>{$crate :: __private :: push_shl (& mut $tokens ); }; ($tokens : ident <<=)=>{$crate :: __private :: push_shl_eq (& mut $tokens ); }; ($tokens : ident >>)=>{$crate :: __private :: push_shr (& mut $tokens ); }; ($tokens : ident >>=)=>{$crate :: __private :: push_shr_eq (& mut $tokens ); }; ($tokens : ident *)=>{$crate :: __private :: push_star (& mut $tokens ); }; ($tokens : ident -)=>{$crate :: __private :: push_sub (& mut $tokens ); }; ($tokens : ident -=)=>{$crate :: __private :: push_sub_eq (& mut $tokens ); }; ($tokens : ident $ident : ident )=>{$crate :: __private :: push_ident (& mut $tokens , stringify ! ($ident )); }; ($tokens : ident $other : tt )=>{$crate :: __private :: parse (& mut $tokens , stringify ! ($other )); }; } +macro_rules! __ra_macro_fixture539 {($call : ident ! $extra : tt $($tts : tt )*)=>{$crate :: pounded_var_names_with_context ! ($call ! $extra (@ $($tts )*)($($tts )* @))}; } +macro_rules! __ra_macro_fixture540 {($call : ident ! $extra : tt ($($b1 : tt )*)($($curr : tt )*))=>{$($crate :: pounded_var_with_context ! ($call ! $extra $b1 $curr ); )* }; } +macro_rules! __ra_macro_fixture541 {($call : ident ! $extra : tt $b1 : tt ($($inner : tt )* ))=>{$crate :: pounded_var_names ! ($call ! $extra $($inner )*); }; ($call : ident ! $extra : tt $b1 : tt [$($inner : tt )* ])=>{$crate :: pounded_var_names ! ($call ! $extra $($inner )*); }; ($call : ident ! $extra : tt $b1 : tt {$($inner : tt )* })=>{$crate :: pounded_var_names ! ($call ! $extra $($inner )*); }; ($call : ident ! ($($extra : tt )*)# $var : ident )=>{$crate ::$call ! ($($extra )* $var ); }; ($call : ident ! $extra : tt $b1 : tt $curr : tt )=>{}; } +macro_rules! __ra_macro_fixture542 {($has_iter : ident $var : ident )=>{# [ allow ( unused_mut )] let ( mut $var , i )= $var . quote_into_iter (); let $has_iter = $has_iter | i ; }; } +macro_rules! __ra_macro_fixture543 {($var : ident )=>{ let $var = match $var . next (){ Some ( _x )=>$crate :: __private :: RepInterp ( _x ), None => break , }; }; } +macro_rules! __ra_macro_fixture544 {($fmt : expr )=>{$crate :: format_ident_impl ! ([:: std :: option :: Option :: None , $fmt ])}; ($fmt : expr , $($rest : tt )*)=>{$crate :: format_ident_impl ! ([:: std :: option :: Option :: None , $fmt ]$($rest )*)}; } +macro_rules! __ra_macro_fixture545 {([$span : expr , $($fmt : tt )*])=>{$crate :: __private :: mk_ident (& format ! ($($fmt )*), $span )}; ([$old : expr , $($fmt : tt )*] span = $span : expr )=>{$crate :: format_ident_impl ! ([$old , $($fmt )*] span = $span ,)}; ([$old : expr , $($fmt : tt )*] span = $span : expr , $($rest : tt )*)=>{$crate :: format_ident_impl ! ([:: std :: option :: Option :: Some ::<$crate :: __private :: Span > ($span ), $($fmt )* ]$($rest )*)}; ([$span : expr , $($fmt : tt )*]$name : ident = $arg : expr )=>{$crate :: format_ident_impl ! ([$span , $($fmt )*]$name = $arg ,)}; ([$span : expr , $($fmt : tt )*]$name : ident = $arg : expr , $($rest : tt )*)=>{ match $crate :: __private :: IdentFragmentAdapter (&$arg ){ arg =>$crate :: format_ident_impl ! ([$span . or ( arg . span ()), $($fmt )*, $name = arg ]$($rest )*), }}; ([$span : expr , $($fmt : tt )*]$arg : expr )=>{$crate :: format_ident_impl ! ([$span , $($fmt )*]$arg ,)}; ([$span : expr , $($fmt : tt )*]$arg : expr , $($rest : tt )*)=>{ match $crate :: __private :: IdentFragmentAdapter (&$arg ){ arg =>$crate :: format_ident_impl ! ([$span . or ( arg . span ()), $($fmt )*, arg ]$($rest )*), }}; } +macro_rules! __ra_macro_fixture546 {()=>( panic ! ( "not yet implemented" )); ($($arg : tt )+)=>( panic ! ( "not yet implemented: {}" , $crate :: format_args ! ($($arg )+))); } +macro_rules! __ra_macro_fixture547 {($($name : expr ),+ $(,)?)=>{{ let mut v = ArrayVec ::< [ LangItemTarget ; 2 ]>:: new (); $(v . extend ( db . lang_item ( cur_crate , $name . into ())); )+ v }}; } +macro_rules! __ra_macro_fixture548 {($ctor : pat , $param : pat )=>{ crate :: Ty :: Apply ( crate :: ApplicationTy { ctor : $ctor , parameters : $param })}; ($ctor : pat )=>{ ty_app ! ($ctor , _)}; } +macro_rules! __ra_macro_fixture549 {(@ one $x : expr )=>( 1usize ); ($elem : expr ; $n : expr )=>({$crate :: SmallVec :: from_elem ($elem , $n )}); ($($x : expr ),*$(,)*)=>({ let count = 0usize $(+ $crate :: smallvec ! (@ one $x ))*; # [ allow ( unused_mut )] let mut vec = $crate :: SmallVec :: new (); if count <= vec . inline_size (){$(vec . push ($x );)* vec } else {$crate :: SmallVec :: from_vec ($crate :: alloc :: vec ! [$($x ,)*])}}); } +macro_rules! __ra_macro_fixture550 {($($q : path )*)=>{$(let before = memory_usage (). allocated ; $q . in_db ( self ). sweep ( sweep ); let after = memory_usage (). allocated ; let q : $q = Default :: default (); let name = format ! ( "{:?}" , q ); acc . push (( name , before - after )); let before = memory_usage (). allocated ; $q . in_db ( self ). sweep ( sweep . discard_everything ()); let after = memory_usage (). allocated ; let q : $q = Default :: default (); let name = format ! ( "{:?} (deps)" , q ); acc . push (( name , before - after )); let before = memory_usage (). allocated ; $q . in_db ( self ). purge (); let after = memory_usage (). allocated ; let q : $q = Default :: default (); let name = format ! ( "{:?} (purge)" , q ); acc . push (( name , before - after )); )*}} +macro_rules! __ra_macro_fixture551 {($($arg : tt )*)=>( if $crate :: cfg ! ( debug_assertions ){$crate :: assert ! ($($arg )*); })} +macro_rules! __ra_macro_fixture552 {()=>{{ let anchor = match self . l_curly_token (){ Some ( it )=> it . into (), None => return self . clone (), }; InsertPosition :: After ( anchor )}}; } +macro_rules! __ra_macro_fixture553 {($anchor : expr )=>{ if let Some ( comma )= $anchor . syntax (). siblings_with_tokens ( Direction :: Next ). find (| it | it . kind ()== T ! [,]){ InsertPosition :: After ( comma )} else { to_insert . insert ( 0 , make :: token ( T ! [,]). into ()); InsertPosition :: After ($anchor . syntax (). clone (). into ())}}; } +macro_rules! __ra_macro_fixture554 {($anchor : expr )=>{ if let Some ( comma )= $anchor . syntax (). siblings_with_tokens ( Direction :: Next ). find (| it | it . kind ()== T ! [,]){ InsertPosition :: After ( comma )} else { to_insert . insert ( 0 , make :: token ( T ! [,]). into ()); InsertPosition :: After ($anchor . syntax (). clone (). into ())}}; } +macro_rules! __ra_macro_fixture555 {()=>{{ let anchor = match self . l_angle_token (){ Some ( it )=> it . into (), None => return self . clone (), }; InsertPosition :: After ( anchor )}}; } +macro_rules! __ra_macro_fixture556 {()=>{ for _ in 0 .. level { buf . push_str ( " " ); }}; } +macro_rules! __ra_macro_fixture557 {()=>{ ExpandError :: BindingError ( format ! ( "" ))}; ($($tt : tt )*)=>{ ExpandError :: BindingError ( format ! ($($tt )*))}; } +macro_rules! __ra_macro_fixture558 {($($tt : tt )*)=>{ return Err ( err ! ($($tt )*))}; } +macro_rules! __ra_macro_fixture559 {($($tt : tt )*)=>{ ParseError :: UnexpectedToken (($($tt )*). to_string ())}; } |