hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
d9029ecfeb3902f3407a484f1e14b6f2305151ac | 6,626 | // Copyright 2018 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate grin_api as api;
extern crate grin_chain as chain;
extern crate grin_core as core;
extern crate grin_p2p as p2p;
extern crate grin_servers as servers;
extern crate grin_util as util;
extern crate grin_wallet as wallet;
extern crate bufstream;
extern crate serde_json;
#[macro_use]
extern crate slog;
mod framework;
use bufstream::BufStream;
use serde_json::Value;
use std::io::prelude::{BufRead, Write};
use std::net::TcpStream;
use std::process;
use std::{thread, time};
use core::global::{self, ChainTypes};
use util::LOGGER;
use framework::{config, stratum_config};
// Create a grin server, and a stratum server.
// Simulate a few JSONRpc requests and verify the results.
// Validate disconnected workers
// Validate broadcasting new jobs
#[test]
fn basic_stratum_server() {
util::init_test_logger();
global::set_mining_mode(ChainTypes::AutomatedTesting);
let test_name_dir = "stratum_server";
framework::clean_all_output(test_name_dir);
// Create a server
let s = servers::Server::new(config(4000, test_name_dir, 0)).unwrap();
// Get mining config with stratumserver enabled
let mut stratum_cfg = stratum_config();
stratum_cfg.burn_reward = true;
stratum_cfg.attempt_time_per_block = 999;
stratum_cfg.enable_stratum_server = Some(true);
stratum_cfg.stratum_server_addr = Some(String::from("127.0.0.1:11101"));
// Start stratum server
s.start_stratum_server(stratum_cfg);
// Wait for stratum server to start and
// Verify stratum server accepts connections
loop {
if let Ok(_stream) = TcpStream::connect("127.0.0.1:11101") {
break;
} else {
thread::sleep(time::Duration::from_millis(500));
}
// As this stream falls out of scope it will be disconnected
}
info!(LOGGER, "stratum server connected");
// Create a few new worker connections
let mut workers = vec![];
for _n in 0..5 {
let w = TcpStream::connect("127.0.0.1:11101").unwrap();
w.set_nonblocking(true)
.expect("Failed to set TcpStream to non-blocking");
let stream = BufStream::new(w);
workers.push(stream);
}
assert!(workers.len() == 5);
info!(LOGGER, "workers length verification ok");
// Simulate a worker lost connection
workers.remove(4);
// Swallow the genesis block
thread::sleep(time::Duration::from_secs(5)); // Wait for the server to broadcast
let mut response = String::new();
for n in 0..workers.len() {
let _result = workers[n].read_line(&mut response);
}
// Verify a few stratum JSONRpc commands
// getjobtemplate - expected block template result
let mut response = String::new();
let job_req = "{\"id\": \"Stratum\", \"jsonrpc\": \"2.0\", \"method\": \"getjobtemplate\"}\n";
workers[2].write(job_req.as_bytes()).unwrap();
workers[2].flush().unwrap();
thread::sleep(time::Duration::from_secs(1)); // Wait for the server to reply
match workers[2].read_line(&mut response) {
Ok(_) => {
let r: Value = serde_json::from_str(&response).unwrap();
assert_eq!(r["error"], serde_json::Value::Null);
assert_ne!(r["result"], serde_json::Value::Null);
}
Err(_e) => {
assert!(false);
}
}
info!(LOGGER, "a few stratum JSONRpc commands verification ok");
// keepalive - expected "ok" result
let mut response = String::new();
let job_req = "{\"id\":\"3\",\"jsonrpc\":\"2.0\",\"method\":\"keepalive\"}\n";
let ok_resp = "{\"id\":\"3\",\"jsonrpc\":\"2.0\",\"method\":\"keepalive\",\"result\":\"ok\",\"error\":null}\n";
workers[2].write(job_req.as_bytes()).unwrap();
workers[2].flush().unwrap();
thread::sleep(time::Duration::from_secs(1)); // Wait for the server to reply
let _st = workers[2].read_line(&mut response);
assert_eq!(response.as_str(), ok_resp);
info!(LOGGER, "keepalive test ok");
// "doesnotexist" - error expected
let mut response = String::new();
let job_req = "{\"id\":\"4\",\"jsonrpc\":\"2.0\",\"method\":\"doesnotexist\"}\n";
let ok_resp = "{\"id\":\"4\",\"jsonrpc\":\"2.0\",\"method\":\"doesnotexist\",\"result\":null,\"error\":{\"code\":-32601,\"message\":\"Method not found\"}}\n";
workers[3].write(job_req.as_bytes()).unwrap();
workers[3].flush().unwrap();
thread::sleep(time::Duration::from_secs(1)); // Wait for the server to reply
let _st = workers[3].read_line(&mut response);
assert_eq!(response.as_str(), ok_resp);
info!(LOGGER, "worker doesnotexist test ok");
// Verify stratum server and worker stats
let stats = s.get_server_stats().unwrap();
assert_eq!(stats.stratum_stats.block_height, 1); // just 1 genesis block
assert_eq!(stats.stratum_stats.num_workers, 4); // 5 - 1 = 4
assert_eq!(stats.stratum_stats.worker_stats[5].is_connected, false); // worker was removed
assert_eq!(stats.stratum_stats.worker_stats[1].is_connected, true);
info!(LOGGER, "stratum server and worker stats verification ok");
// Start mining blocks
s.start_test_miner(None);
info!(LOGGER, "test miner started");
// This test is supposed to complete in 3 seconds,
// so let's set a timeout on 10s to avoid infinite waiting happened in Travis-CI.
let handler = thread::spawn(|| {
thread::sleep(time::Duration::from_secs(10));
error!(LOGGER, "basic_stratum_server test fail on timeout!");
thread::sleep(time::Duration::from_millis(100));
process::exit(1);
});
// Simulate a worker lost connection
workers.remove(1);
// Verify blocks are being broadcast to workers
let expected = String::from("job");
thread::sleep(time::Duration::from_secs(3)); // Wait for a few mined blocks
let mut jobtemplate = String::new();
let _st = workers[2].read_line(&mut jobtemplate);
let job_template: Value = serde_json::from_str(&jobtemplate).unwrap();
assert_eq!(job_template["method"], expected);
info!(LOGGER, "blocks broadcasting to workers test ok");
// Verify stratum server and worker stats
let stats = s.get_server_stats().unwrap();
assert_eq!(stats.stratum_stats.num_workers, 3); // 5 - 2 = 3
assert_eq!(stats.stratum_stats.worker_stats[2].is_connected, false); // worker was removed
assert_ne!(stats.stratum_stats.block_height, 1);
info!(LOGGER, "basic_stratum_server test done and ok.");
}
| 36.20765 | 159 | 0.706459 |
d9354efb8fdc4594e4b57509f024178bbbe6ead1 | 130 | // run-rustfix
fn main () {
#[allow(non_upper_case_globals)]
let foo: usize = 42;
let _: [u8; foo]; //~ ERROR E0435
}
| 18.571429 | 37 | 0.576923 |
8ff97453c14149700455c677c7c815c03fb4c141 | 49,016 | pub mod attr;
mod diagnostics;
mod expr;
mod generics;
mod item;
mod nonterminal;
mod pat;
mod path;
mod stmt;
mod ty;
use crate::lexer::UnmatchedBrace;
pub use diagnostics::AttemptLocalParseRecovery;
use diagnostics::Error;
pub use path::PathStyle;
use rustc_ast::ptr::P;
use rustc_ast::token::{self, DelimToken, Token, TokenKind};
use rustc_ast::tokenstream::{self, DelimSpan, LazyTokenStream, LazyTokenStreamInner, Spacing};
use rustc_ast::tokenstream::{TokenStream, TokenTree};
use rustc_ast::DUMMY_NODE_ID;
use rustc_ast::{self as ast, AnonConst, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe};
use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit};
use rustc_ast::{Visibility, VisibilityKind};
use rustc_ast_pretty::pprust;
use rustc_errors::PResult;
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError};
use rustc_session::parse::ParseSess;
use rustc_span::source_map::{Span, DUMMY_SP};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use tracing::debug;
use std::{cmp, mem, slice};
bitflags::bitflags! {
struct Restrictions: u8 {
const STMT_EXPR = 1 << 0;
const NO_STRUCT_LITERAL = 1 << 1;
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum SemiColonMode {
Break,
Ignore,
Comma,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum BlockMode {
Break,
Ignore,
}
/// Like `maybe_whole_expr`, but for things other than expressions.
#[macro_export]
macro_rules! maybe_whole {
($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
if let token::Interpolated(nt) = &$p.token.kind {
if let token::$constructor(x) = &**nt {
let $x = x.clone();
$p.bump();
return Ok($e);
}
}
};
}
/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
#[macro_export]
macro_rules! maybe_recover_from_interpolated_ty_qpath {
($self: expr, $allow_qpath_recovery: expr) => {
if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
if let token::Interpolated(nt) = &$self.token.kind {
if let token::NtTy(ty) = &**nt {
let ty = ty.clone();
$self.bump();
return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
}
}
}
};
}
#[derive(Clone)]
pub struct Parser<'a> {
pub sess: &'a ParseSess,
/// The current token.
pub token: Token,
/// The spacing for the current token
pub token_spacing: Spacing,
/// The previous token.
pub prev_token: Token,
restrictions: Restrictions,
expected_tokens: Vec<TokenType>,
// Important: This must only be advanced from `next_tok`
// to ensure that `token_cursor.num_next_calls` is updated properly
token_cursor: TokenCursor,
desugar_doc_comments: 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.
unmatched_angle_bracket_count: u32,
max_angle_bracket_count: u32,
/// A 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.
pub(super) unclosed_delims: Vec<UnmatchedBrace>,
last_unexpected_token_span: Option<Span>,
/// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
/// looked like it could have been a mistyped path or literal `Option:Some(42)`).
pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
/// If present, this `Parser` is not parsing Rust code but rather a macro call.
subparser_name: Option<&'static str>,
}
impl<'a> Drop for Parser<'a> {
fn drop(&mut self) {
emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
}
}
#[derive(Clone)]
struct TokenCursor {
frame: TokenCursorFrame,
stack: Vec<TokenCursorFrame>,
desugar_doc_comments: bool,
// Counts the number of calls to `next` or `next_desugared`,
// depending on whether `desugar_doc_comments` is set.
num_next_calls: usize,
}
#[derive(Clone)]
struct TokenCursorFrame {
delim: token::DelimToken,
span: DelimSpan,
open_delim: bool,
tree_cursor: tokenstream::Cursor,
close_delim: bool,
}
impl TokenCursorFrame {
fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self {
TokenCursorFrame {
delim,
span,
open_delim: delim == token::NoDelim,
tree_cursor: tts.into_trees(),
close_delim: delim == token::NoDelim,
}
}
}
impl TokenCursor {
fn next(&mut self) -> (Token, Spacing) {
loop {
let (tree, spacing) = if !self.frame.open_delim {
self.frame.open_delim = true;
TokenTree::open_tt(self.frame.span, self.frame.delim).into()
} else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() {
tree
} else if !self.frame.close_delim {
self.frame.close_delim = true;
TokenTree::close_tt(self.frame.span, self.frame.delim).into()
} else if let Some(frame) = self.stack.pop() {
self.frame = frame;
continue;
} else {
(TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone)
};
match tree {
TokenTree::Token(token) => {
return (token, spacing);
}
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) -> (Token, Spacing) {
let (data, attr_style, sp) = match self.next() {
(Token { kind: token::DocComment(_, attr_style, data), span }, _) => {
(data, attr_style, span)
}
tok => return tok,
};
// 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 data.as_str().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(token::Ident(sym::doc, false), sp),
TokenTree::token(token::Eq, sp),
TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
]
.iter()
.cloned()
.collect::<TokenStream>(),
);
self.stack.push(mem::replace(
&mut self.frame,
TokenCursorFrame::new(
delim_span,
token::NoDelim,
if attr_style == AttrStyle::Inner {
[TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
.iter()
.cloned()
.collect::<TokenStream>()
} else {
[TokenTree::token(token::Pound, sp), body]
.iter()
.cloned()
.collect::<TokenStream>()
},
),
));
self.next()
}
}
#[derive(Clone, PartialEq)]
enum TokenType {
Token(TokenKind),
Keyword(Symbol),
Operator,
Lifetime,
Ident,
Path,
Type,
Const,
}
impl TokenType {
fn to_string(&self) -> String {
match *self {
TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
TokenType::Keyword(kw) => format!("`{}`", kw),
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(),
}
}
}
#[derive(Copy, Clone, Debug)]
enum TokenExpectType {
Expect,
NoExpect,
}
/// A sequence separator.
struct SeqSep {
/// The separator token.
sep: Option<TokenKind>,
/// `true` if a trailing separator is allowed.
trailing_sep_allowed: bool,
}
impl SeqSep {
fn trailing_allowed(t: TokenKind) -> SeqSep {
SeqSep { sep: Some(t), trailing_sep_allowed: true }
}
fn none() -> SeqSep {
SeqSep { sep: None, trailing_sep_allowed: false }
}
}
pub enum FollowedByType {
Yes,
No,
}
fn token_descr_opt(token: &Token) -> Option<&'static str> {
Some(match token.kind {
_ if token.is_special_ident() => "reserved identifier",
_ if token.is_used_keyword() => "keyword",
_ if token.is_unused_keyword() => "reserved keyword",
token::DocComment(..) => "doc comment",
_ => return None,
})
}
pub(super) fn token_descr(token: &Token) -> String {
let token_str = pprust::token_to_string(token);
match token_descr_opt(token) {
Some(prefix) => format!("{} `{}`", prefix, token_str),
_ => format!("`{}`", token_str),
}
}
impl<'a> Parser<'a> {
pub fn new(
sess: &'a ParseSess,
tokens: TokenStream,
desugar_doc_comments: bool,
subparser_name: Option<&'static str>,
) -> Self {
let mut parser = Parser {
sess,
token: Token::dummy(),
token_spacing: Spacing::Alone,
prev_token: Token::dummy(),
restrictions: Restrictions::empty(),
expected_tokens: Vec::new(),
token_cursor: TokenCursor {
frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens),
stack: Vec::new(),
num_next_calls: 0,
desugar_doc_comments,
},
desugar_doc_comments,
unmatched_angle_bracket_count: 0,
max_angle_bracket_count: 0,
unclosed_delims: Vec::new(),
last_unexpected_token_span: None,
last_type_ascription: None,
subparser_name,
};
// Make parser point to the first token.
parser.bump();
parser
}
fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) {
let (mut next, spacing) = if self.desugar_doc_comments {
self.token_cursor.next_desugared()
} else {
self.token_cursor.next()
};
self.token_cursor.num_next_calls += 1;
if next.span.is_dummy() {
// Tweak the location for better diagnostics, but keep syntactic context intact.
next.span = fallback_span.with_ctxt(next.span.ctxt());
}
(next, spacing)
}
pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
match self.expect_one_of(&[], &[]) {
Err(e) => Err(e),
// We can get `Ok(true)` from `recover_closing_delimiter`
// which is called in `expected_one_of_not_found`.
Ok(_) => FatalError.raise(),
}
}
/// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
if self.expected_tokens.is_empty() {
if self.token == *t {
self.bump();
Ok(false)
} else {
self.unexpected_try_recover(t)
}
} else {
self.expect_one_of(slice::from_ref(t), &[])
}
}
/// 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: &[TokenKind],
inedible: &[TokenKind],
) -> PResult<'a, bool /* recovered */> {
if edible.contains(&self.token.kind) {
self.bump();
Ok(false)
} else if inedible.contains(&self.token.kind) {
// leave it in the input
Ok(false)
} else if self.last_unexpected_token_span == Some(self.token.span) {
FatalError.raise();
} else {
self.expected_one_of_not_found(edible, inedible)
}
}
// Public for rustfmt usage.
pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
self.parse_ident_common(true)
}
fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
match self.token.ident() {
Some((ident, is_raw)) => {
if !is_raw && ident.is_reserved() {
let mut err = self.expected_ident_found();
if recover {
err.emit();
} else {
return Err(err);
}
}
self.bump();
Ok(ident)
}
_ => Err(match self.prev_token.kind {
TokenKind::DocComment(..) => {
self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
}
_ => 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.
fn check(&mut self, tok: &TokenKind) -> 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: &TokenKind) -> bool {
let is_present = self.check(tok);
if is_present {
self.bump()
}
is_present
}
/// If the next token is the given keyword, returns `true` without eating it.
/// An expectation is also added for diagnostics purposes.
fn check_keyword(&mut self, kw: Symbol) -> 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`. An expectation is also added for diagnostics purposes.
// Public for rustfmt usage.
pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
if self.check_keyword(kw) {
self.bump();
true
} else {
false
}
}
fn eat_keyword_noexpect(&mut self, kw: Symbol) -> 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: Symbol) -> PResult<'a, ()> {
if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
}
/// Is the given keyword `kw` followed by a non-reserved identifier?
fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
}
fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
if ok {
true
} else {
self.expected_tokens.push(typ);
false
}
}
fn check_ident(&mut self) -> bool {
self.check_or_expected(self.token.is_ident(), TokenType::Ident)
}
fn check_path(&mut self) -> bool {
self.check_or_expected(self.token.is_path_start(), TokenType::Path)
}
fn check_type(&mut self) -> bool {
self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
}
fn check_const_arg(&mut self) -> bool {
self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
}
fn check_inline_const(&self, dist: usize) -> bool {
self.is_keyword_ahead(dist, &[kw::Const])
&& self.look_ahead(dist + 1, |t| match t.kind {
token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
token::OpenDelim(DelimToken::Brace) => true,
_ => false,
})
}
/// Checks to see if the next token is either `+` or `+=`.
/// Otherwise returns `false`.
fn check_plus(&mut self) -> bool {
self.check_or_expected(
self.token.is_like_plus(),
TokenType::Token(token::BinOp(token::Plus)),
)
}
/// Eats the expected token if it's present possibly breaking
/// compound tokens like multi-character operators in process.
/// Returns `true` if the token was eaten.
fn break_and_eat(&mut self, expected: TokenKind) -> bool {
if self.token.kind == expected {
self.bump();
return true;
}
match self.token.kind.break_two_token_op() {
Some((first, second)) if first == expected => {
let first_span = self.sess.source_map().start_point(self.token.span);
let second_span = self.token.span.with_lo(first_span.hi());
self.token = Token::new(first, first_span);
// Use the spacing of the glued token as the spacing
// of the unglued second token.
self.bump_with((Token::new(second, second_span), self.token_spacing));
true
}
_ => {
self.expected_tokens.push(TokenType::Token(expected));
false
}
}
}
/// Eats `+` possibly breaking tokens like `+=` in process.
fn eat_plus(&mut self) -> bool {
self.break_and_eat(token::BinOp(token::Plus))
}
/// Eats `&` possibly breaking tokens like `&&` in process.
/// Signals an error if `&` is not eaten.
fn expect_and(&mut self) -> PResult<'a, ()> {
if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
}
/// Eats `|` possibly breaking tokens like `||` in process.
/// Signals an error if `|` was not eaten.
fn expect_or(&mut self) -> PResult<'a, ()> {
if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
}
/// Eats `<` possibly breaking tokens like `<<` in process.
fn eat_lt(&mut self) -> bool {
let ate = self.break_and_eat(token::Lt);
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
}
/// Eats `<` possibly breaking tokens like `<<` in process.
/// Signals an error if `<` was not eaten.
fn expect_lt(&mut self) -> PResult<'a, ()> {
if self.eat_lt() { Ok(()) } else { self.unexpected() }
}
/// Eats `>` possibly breaking tokens like `>>` in process.
/// Signals an error if `>` was not eaten.
fn expect_gt(&mut self) -> PResult<'a, ()> {
if self.break_and_eat(token::Gt) {
// 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(())
} else {
self.unexpected()
}
}
fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
kets.iter().any(|k| match expect {
TokenExpectType::Expect => self.check(k),
TokenExpectType::NoExpect => self.token == **k,
})
}
fn parse_seq_to_before_tokens<T>(
&mut self,
kets: &[&TokenKind],
sep: SeqSep,
expect: TokenExpectType,
mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
let mut first = true;
let mut recovered = false;
let mut trailing = false;
let mut v = vec![];
while !self.expect_any_with_type(kets, expect) {
if let token::CloseDelim(..) | token::Eof = self.token.kind {
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 expect_err) => {
let sp = self.prev_token.span.shrink_to_hi();
let token_str = pprust::token_kind_to_string(t);
// Attempt to keep parsing if it was a similar separator.
if let Some(ref tokens) = t.similar_tokens() {
if tokens.contains(&self.token.kind) {
self.bump();
}
}
// If this was a missing `@` in a binding pattern
// bail with a suggestion
// https://github.com/rust-lang/rust/issues/72373
if self.prev_token.is_ident() && self.token.kind == token::DotDot {
let msg = format!(
"if you meant to bind the contents of \
the rest of the array pattern into `{}`, use `@`",
pprust::token_to_string(&self.prev_token)
);
expect_err
.span_suggestion_verbose(
self.prev_token.span.shrink_to_hi().until(self.token.span),
&msg,
" @ ".to_string(),
Applicability::MaybeIncorrect,
)
.emit();
break;
}
// Attempt to keep parsing if it was an omitted separator.
match f(self) {
Ok(t) => {
// Parsed successfully, therefore most probably the code only
// misses a separator.
let mut exp_span = self.sess.source_map().next_point(sp);
if self.sess.source_map().is_multiline(exp_span) {
exp_span = sp;
}
expect_err
.span_suggestion_short(
exp_span,
&format!("missing `{}`", token_str),
token_str,
Applicability::MaybeIncorrect,
)
.emit();
v.push(t);
continue;
}
Err(mut e) => {
// Parsing failed, therefore it must be something more serious
// than just a missing separator.
expect_err.emit();
e.cancel();
break;
}
}
}
}
}
}
if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
trailing = true;
break;
}
let t = f(self)?;
v.push(t);
}
Ok((v, trailing, recovered))
}
/// Parses a sequence, not including the closing delimiter. The function
/// `f` must consume tokens until reaching the next separator or
/// closing bracket.
fn parse_seq_to_before_end<T>(
&mut self,
ket: &TokenKind,
sep: SeqSep,
f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
) -> PResult<'a, (Vec<T>, bool, bool)> {
self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
}
/// Parses a sequence, including the closing delimiter. The function
/// `f` must consume tokens until reaching the next separator or
/// closing bracket.
fn parse_seq_to_end<T>(
&mut self,
ket: &TokenKind,
sep: SeqSep,
f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
if !recovered {
self.eat(ket);
}
Ok((val, trailing))
}
/// 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>(
&mut self,
bra: &TokenKind,
ket: &TokenKind,
sep: SeqSep,
f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
) -> PResult<'a, (Vec<T>, bool)> {
self.expect(bra)?;
self.parse_seq_to_end(ket, sep, f)
}
fn parse_delim_comma_seq<T>(
&mut self,
delim: DelimToken,
f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
) -> PResult<'a, (Vec<T>, bool)> {
self.parse_unspanned_seq(
&token::OpenDelim(delim),
&token::CloseDelim(delim),
SeqSep::trailing_allowed(token::Comma),
f,
)
}
fn parse_paren_comma_seq<T>(
&mut self,
f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
) -> PResult<'a, (Vec<T>, bool)> {
self.parse_delim_comma_seq(token::Paren, f)
}
/// Advance the parser by one token using provided token as the next one.
fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
// Bumping after EOF is a bad sign, usually an infinite loop.
if self.prev_token.kind == TokenKind::Eof {
let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
self.span_bug(self.token.span, msg);
}
// Update the current and previous tokens.
self.prev_token = mem::replace(&mut self.token, next_token);
self.token_spacing = next_spacing;
// Diagnostics.
self.expected_tokens.clear();
}
/// Advance the parser by one token.
pub fn bump(&mut self) {
let next_token = self.next_tok(self.token.span);
self.bump_with(next_token);
}
/// Look-ahead `dist` tokens of `self.token` and get access to that token there.
/// When `dist == 0` then the current token is looked at.
pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
if dist == 0 {
return looker(&self.token);
}
let frame = &self.token_cursor.frame;
match frame.tree_cursor.look_ahead(dist - 1) {
Some(tree) => match tree {
TokenTree::Token(token) => looker(token),
TokenTree::Delimited(dspan, delim, _) => {
looker(&Token::new(token::OpenDelim(*delim), dspan.open))
}
},
None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)),
}
}
/// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
}
/// Parses asyncness: `async` or nothing.
fn parse_asyncness(&mut self) -> Async {
if self.eat_keyword(kw::Async) {
let span = self.prev_token.uninterpolated_span();
Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
} else {
Async::No
}
}
/// Parses unsafety: `unsafe` or nothing.
fn parse_unsafety(&mut self) -> Unsafe {
if self.eat_keyword(kw::Unsafe) {
Unsafe::Yes(self.prev_token.uninterpolated_span())
} else {
Unsafe::No
}
}
/// Parses constness: `const` or nothing.
fn parse_constness(&mut self) -> Const {
// Avoid const blocks to be parsed as const items
if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace))
&& self.eat_keyword(kw::Const)
{
Const::Yes(self.prev_token.uninterpolated_span())
} else {
Const::No
}
}
/// Parses inline const expressions.
fn parse_const_block(&mut self, span: Span) -> PResult<'a, P<Expr>> {
self.sess.gated_spans.gate(sym::inline_const, span);
self.eat_keyword(kw::Const);
let blk = self.parse_block()?;
let anon_const = AnonConst {
id: DUMMY_NODE_ID,
value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
};
Ok(self.mk_expr(span, ExprKind::ConstBlock(anon_const), AttrVec::new()))
}
/// Parses mutability (`mut` or nothing).
fn parse_mutability(&mut self) -> Mutability {
if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
}
/// Possibly parses mutability (`const` or `mut`).
fn parse_const_or_mut(&mut self) -> Option<Mutability> {
if self.eat_keyword(kw::Mut) {
Some(Mutability::Mut)
} else if self.eat_keyword(kw::Const) {
Some(Mutability::Not)
} else {
None
}
}
fn parse_field_name(&mut self) -> PResult<'a, Ident> {
if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
{
self.expect_no_suffix(self.token.span, "a tuple index", suffix);
self.bump();
Ok(Ident::new(symbol, self.prev_token.span))
} else {
self.parse_ident_common(false)
}
}
fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
self.parse_mac_args_common(true).map(P)
}
fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
self.parse_mac_args_common(false)
}
fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
Ok(
if self.check(&token::OpenDelim(DelimToken::Paren))
|| self.check(&token::OpenDelim(DelimToken::Bracket))
|| self.check(&token::OpenDelim(DelimToken::Brace))
{
match self.parse_token_tree() {
TokenTree::Delimited(dspan, delim, tokens) =>
// We've confirmed above that there is a delimiter so unwrapping is OK.
{
MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
}
_ => unreachable!(),
}
} else if !delimited_only {
if self.eat(&token::Eq) {
let eq_span = self.prev_token.span;
let mut is_interpolated_expr = false;
if let token::Interpolated(nt) = &self.token.kind {
if let token::NtExpr(..) = **nt {
is_interpolated_expr = true;
}
}
let token_tree = if is_interpolated_expr {
// We need to accept arbitrary interpolated expressions to continue
// supporting things like `doc = $expr` that work on stable.
// Non-literal interpolated expressions are rejected after expansion.
self.parse_token_tree()
} else {
self.parse_unsuffixed_lit()?.token_tree()
};
MacArgs::Eq(eq_span, token_tree.into())
} else {
MacArgs::Empty
}
} else {
return self.unexpected();
},
)
}
fn parse_or_use_outer_attributes(
&mut self,
already_parsed_attrs: Option<AttrVec>,
) -> PResult<'a, AttrVec> {
if let Some(attrs) = already_parsed_attrs {
Ok(attrs)
} else {
self.parse_outer_attributes().map(|a| a.into())
}
}
/// Parses a single token tree from the input.
pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
match self.token.kind {
token::OpenDelim(..) => {
let depth = self.token_cursor.stack.len();
// We keep advancing the token cursor until we hit
// the matching `CloseDelim` token.
while !(depth == self.token_cursor.stack.len()
&& matches!(self.token.kind, token::CloseDelim(_)))
{
// Advance one token at a time, so `TokenCursor::next()`
// can capture these tokens if necessary.
self.bump();
}
// We are still inside the frame corresponding
// to the delimited stream we captured, so grab
// the tokens from this frame.
let frame = &self.token_cursor.frame;
let stream = frame.tree_cursor.stream.clone();
let span = frame.span;
let delim = frame.delim;
// Consume close delimiter
self.bump();
TokenTree::Delimited(span, delim, stream)
}
token::CloseDelim(_) | token::Eof => unreachable!(),
_ => {
self.bump();
TokenTree::Token(self.prev_token.clone())
}
}
}
/// Parses 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.kind {
token::Eof | token::CloseDelim(..) => break,
_ => result.push(self.parse_token_tree().into()),
}
}
TokenStream::new(result)
}
/// Evaluates the closure with restrictions in place.
///
/// Afters the closure is evaluated, restrictions are reset.
fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
let old = self.restrictions;
self.restrictions = res;
let res = f(self);
self.restrictions = old;
res
}
fn is_crate_vis(&self) -> bool {
self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
}
/// 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.
// Public for rustfmt usage.
pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
maybe_whole!(self, NtVis, |x| x);
self.expected_tokens.push(TokenType::Keyword(kw::Crate));
if self.is_crate_vis() {
self.bump(); // `crate`
self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
return Ok(Visibility {
span: self.prev_token.span,
kind: VisibilityKind::Crate(CrateSugar::JustCrate),
tokens: None,
});
}
if !self.eat_keyword(kw::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(Visibility {
span: self.token.span.shrink_to_lo(),
kind: VisibilityKind::Inherited,
tokens: None,
});
}
let lo = self.prev_token.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.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
// account for `pub(crate::foo)`
{
// Parse `pub(crate)`.
self.bump(); // `(`
self.bump(); // `crate`
self.expect(&token::CloseDelim(token::Paren))?; // `)`
let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
return Ok(Visibility {
span: lo.to(self.prev_token.span),
kind: vis,
tokens: None,
});
} else if self.is_keyword_ahead(1, &[kw::In]) {
// Parse `pub(in path)`.
self.bump(); // `(`
self.bump(); // `in`
let path = self.parse_path(PathStyle::Mod)?; // `path`
self.expect(&token::CloseDelim(token::Paren))?; // `)`
let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
return Ok(Visibility {
span: lo.to(self.prev_token.span),
kind: vis,
tokens: None,
});
} else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
&& self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
{
// Parse `pub(self)` or `pub(super)`.
self.bump(); // `(`
let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
self.expect(&token::CloseDelim(token::Paren))?; // `)`
let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
return Ok(Visibility {
span: lo.to(self.prev_token.span),
kind: vis,
tokens: None,
});
} else if let FollowedByType::No = fbt {
// Provide this diagnostic if a type cannot follow;
// in particular, if this is not a tuple struct.
self.recover_incorrect_vis_restriction()?;
// Emit diagnostic, but continue with public visibility.
}
}
Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
}
/// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
self.bump(); // `(`
let path = self.parse_path(PathStyle::Mod)?;
self.expect(&token::CloseDelim(token::Paren))?; // `)`
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_str = pprust::path_to_string(&path);
struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
.help(suggestion)
.span_suggestion(
path.span,
&format!("make this visible only to module `{}` with `in`", path_str),
format!("in {}", path_str),
Applicability::MachineApplicable,
)
.emit();
Ok(())
}
/// Parses `extern string_literal?`.
fn parse_extern(&mut self) -> PResult<'a, Extern> {
Ok(if self.eat_keyword(kw::Extern) {
Extern::from_abi(self.parse_abi())
} else {
Extern::None
})
}
/// Parses a string literal as an ABI spec.
fn parse_abi(&mut self) -> Option<StrLit> {
match self.parse_str_lit() {
Ok(str_lit) => Some(str_lit),
Err(Some(lit)) => match lit.kind {
ast::LitKind::Err(_) => None,
_ => {
self.struct_span_err(lit.span, "non-string ABI literal")
.span_suggestion(
lit.span,
"specify the ABI with a string literal",
"\"C\"".to_string(),
Applicability::MaybeIncorrect,
)
.emit();
None
}
},
Err(None) => None,
}
}
/// Records all tokens consumed by the provided callback,
/// including the current token. These tokens are collected
/// into a `TokenStream`, and returned along with the result
/// of the callback.
///
/// Note: If your callback consumes an opening delimiter
/// (including the case where you call `collect_tokens`
/// when the current token is an opening delimeter),
/// you must also consume the corresponding closing delimiter.
///
/// That is, you can consume
/// `something ([{ }])` or `([{}])`, but not `([{}]`
///
/// This restriction shouldn't be an issue in practice,
/// since this function is used to record the tokens for
/// a parsed AST item, which always has matching delimiters.
pub fn collect_tokens<R>(
&mut self,
f: impl FnOnce(&mut Self) -> PResult<'a, R>,
) -> PResult<'a, (R, LazyTokenStream)> {
let start_token = (self.token.clone(), self.token_spacing);
let mut cursor_snapshot = self.token_cursor.clone();
let ret = f(self)?;
let new_calls = self.token_cursor.num_next_calls;
let num_calls = new_calls - cursor_snapshot.num_next_calls;
let desugar_doc_comments = self.desugar_doc_comments;
// Produces a `TokenStream` on-demand. Using `cursor_snapshot`
// and `num_calls`, we can reconstruct the `TokenStream` seen
// by the callback. This allows us to avoid producing a `TokenStream`
// if it is never needed - for example, a captured `macro_rules!`
// argument that is never passed to a proc macro.
//
// This also makes `Parser` very cheap to clone, since
// there is no intermediate collection buffer to clone.
let lazy_cb = move || {
// The token produced by the final call to `next` or `next_desugared`
// was not actually consumed by the callback. The combination
// of chaining the initial token and using `take` produces the desired
// result - we produce an empty `TokenStream` if no calls were made,
// and omit the final token otherwise.
let tokens = std::iter::once(start_token)
.chain((0..num_calls).map(|_| {
if desugar_doc_comments {
cursor_snapshot.next_desugared()
} else {
cursor_snapshot.next()
}
}))
.take(num_calls);
make_token_stream(tokens)
};
let stream = LazyTokenStream::new(LazyTokenStreamInner::Lazy(Box::new(lazy_cb)));
Ok((ret, stream))
}
/// `::{` 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)
})
}
pub fn clear_expected_tokens(&mut self) {
self.expected_tokens.clear();
}
}
crate fn make_unclosed_delims_error(
unmatched: UnmatchedBrace,
sess: &ParseSess,
) -> Option<DiagnosticBuilder<'_>> {
// `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
// `unmatched_braces` only for error recovery in the `Parser`.
let found_delim = unmatched.found_delim?;
let mut err = sess.span_diagnostic.struct_span_err(
unmatched.found_span,
&format!(
"mismatched closing delimiter: `{}`",
pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
),
);
err.span_label(unmatched.found_span, "mismatched closing delimiter");
if let Some(sp) = unmatched.candidate_span {
err.span_label(sp, "closing delimiter possibly meant for this");
}
if let Some(sp) = unmatched.unclosed_span {
err.span_label(sp, "unclosed delimiter");
}
Some(err)
}
pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
*sess.reached_eof.borrow_mut() |=
unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
for unmatched in unclosed_delims.drain(..) {
if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
e.emit();
}
}
}
/// Converts a flattened iterator of tokens (including open and close delimiter tokens)
/// into a `TokenStream`, creating a `TokenTree::Delimited` for each matching pair
/// of open and close delims.
fn make_token_stream(tokens: impl Iterator<Item = (Token, Spacing)>) -> TokenStream {
#[derive(Debug)]
struct FrameData {
open: Span,
inner: Vec<(TokenTree, Spacing)>,
}
let mut stack = vec![FrameData { open: DUMMY_SP, inner: vec![] }];
for (token, spacing) in tokens {
match token {
Token { kind: TokenKind::OpenDelim(_), span } => {
stack.push(FrameData { open: span, inner: vec![] });
}
Token { kind: TokenKind::CloseDelim(delim), span } => {
let frame_data = stack.pop().expect("Token stack was empty!");
let dspan = DelimSpan::from_pair(frame_data.open, span);
let stream = TokenStream::new(frame_data.inner);
let delimited = TokenTree::Delimited(dspan, delim, stream);
stack
.last_mut()
.unwrap_or_else(|| panic!("Bottom token frame is missing for tokens!"))
.inner
.push((delimited, Spacing::Alone));
}
token => stack
.last_mut()
.expect("Bottom token frame is missing!")
.inner
.push((TokenTree::Token(token), spacing)),
}
}
let final_buf = stack.pop().expect("Missing final buf!");
assert!(stack.is_empty(), "Stack should be empty: final_buf={:?} stack={:?}", final_buf, stack);
TokenStream::new(final_buf.inner)
}
| 37.049131 | 100 | 0.531133 |
fec2602efbd70e8598c0d86e7b95b0bbf88d0629 | 328 | use graph::NodeT;
use numpy::{PyArray1, PyArray2};
use pyo3::prelude::*;
pub type PyContexts = Py<PyArray2<NodeT>>;
pub type PyWords = Py<PyArray1<NodeT>>;
pub type PyFrequencies = Py<PyArray1<f64>>;
pub struct ThreadDataRaceAware<'a, T> {
pub(crate) t: &'a T,
}
unsafe impl<'a, T> Sync for ThreadDataRaceAware<'a, T> {}
| 23.428571 | 57 | 0.689024 |
fffeca0f517b41a4e0e5bdd1708d6cbe7c483a9e | 285 | extern crate crossbeam_epoch_0_4_0 ; extern crate lolbench_support ; use
lolbench_support :: { criterion_from_env , init_logging } ; fn main ( ) {
init_logging ( ) ; let mut crit = criterion_from_env ( ) ;
crossbeam_epoch_0_4_0 :: defer :: single_alloc_defer_free ( & mut crit ) ; } | 71.25 | 76 | 0.736842 |
16d528733ce8a28b72d9fa453d24d523d7585758 | 1,072 | // Copyright 2014-2016 Johannes Köster, Martin Larralde.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! GC counter over an `IntoTextIterator` object.
//! Complexity: o(n)
use utils::IntoTextIterator;
/// Base gc content counter
fn gcn_content<'a, I: IntoTextIterator<'a>>(sequence: I, step: usize) -> f32 {
let mut l = 0f32;
let mut count = 0.0;
for (i, &n) in sequence.into_iter().enumerate() {
if i % step == 0 {
count += match n {
b'c' | b'g' | b'G' | b'C' => 1f32, // G or C
_ => 0f32,
};
}
l = i as f32;
}
count / (l + 1f32)
}
/// gc content counter for every nucleotide
pub fn gc_content<'a, I: IntoTextIterator<'a>>(sequence: I) -> f32 {
gcn_content(sequence, 1usize)
}
/// gc content counter for the nucleotide in 3rd position
pub fn gc3_content<'a, I: IntoTextIterator<'a>>(sequence: I) -> f32 {
gcn_content(sequence, 3usize)
}
| 28.972973 | 78 | 0.607276 |
76bd57a3aff9891551f7e1aa2d08e950e18b5ada | 41,364 | // Copyright (c) 2019 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
use anyhow::{anyhow, bail, Context, Result};
use libc::uid_t;
use nix::errno::Errno;
use nix::fcntl::{self, OFlag};
#[cfg(not(test))]
use nix::mount;
use nix::mount::{MntFlags, MsFlags};
use nix::sys::stat::{self, Mode, SFlag};
use nix::unistd::{self, Gid, Uid};
use nix::NixPath;
use oci::{LinuxDevice, Mount, Spec};
use std::collections::{HashMap, HashSet};
use std::fs::{self, OpenOptions};
use std::mem::MaybeUninit;
use std::os::unix;
use std::os::unix::io::RawFd;
use std::path::{Path, PathBuf};
use path_absolutize::*;
use std::fs::File;
use std::io::{BufRead, BufReader};
use crate::container::DEFAULT_DEVICES;
use crate::sync::write_count;
use std::string::ToString;
use crate::log_child;
// Info reveals information about a particular mounted filesystem. This
// struct is populated from the content in the /proc/<pid>/mountinfo file.
#[derive(std::fmt::Debug)]
pub struct Info {
id: i32,
parent: i32,
major: i32,
minor: i32,
root: String,
mount_point: String,
opts: String,
optional: String,
fstype: String,
source: String,
vfs_opts: String,
}
const MOUNTINFOFORMAT: &str = "{d} {d} {d}:{d} {} {} {} {}";
const PROC_PATH: &str = "/proc";
// since libc didn't defined this const for musl, thus redefined it here.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
const PROC_SUPER_MAGIC: libc::c_long = 0x00009fa0;
#[cfg(all(target_os = "linux", target_env = "musl"))]
const PROC_SUPER_MAGIC: libc::c_ulong = 0x00009fa0;
lazy_static! {
static ref PROPAGATION: HashMap<&'static str, MsFlags> = {
let mut m = HashMap::new();
m.insert("shared", MsFlags::MS_SHARED);
m.insert("rshared", MsFlags::MS_SHARED | MsFlags::MS_REC);
m.insert("private", MsFlags::MS_PRIVATE);
m.insert("rprivate", MsFlags::MS_PRIVATE | MsFlags::MS_REC);
m.insert("slave", MsFlags::MS_SLAVE);
m.insert("rslave", MsFlags::MS_SLAVE | MsFlags::MS_REC);
m
};
static ref OPTIONS: HashMap<&'static str, (bool, MsFlags)> = {
let mut m = HashMap::new();
m.insert("defaults", (false, MsFlags::empty()));
m.insert("ro", (false, MsFlags::MS_RDONLY));
m.insert("rw", (true, MsFlags::MS_RDONLY));
m.insert("suid", (true, MsFlags::MS_NOSUID));
m.insert("nosuid", (false, MsFlags::MS_NOSUID));
m.insert("dev", (true, MsFlags::MS_NODEV));
m.insert("nodev", (false, MsFlags::MS_NODEV));
m.insert("exec", (true, MsFlags::MS_NOEXEC));
m.insert("noexec", (false, MsFlags::MS_NOEXEC));
m.insert("sync", (false, MsFlags::MS_SYNCHRONOUS));
m.insert("async", (true, MsFlags::MS_SYNCHRONOUS));
m.insert("dirsync", (false, MsFlags::MS_DIRSYNC));
m.insert("remount", (false, MsFlags::MS_REMOUNT));
m.insert("mand", (false, MsFlags::MS_MANDLOCK));
m.insert("nomand", (true, MsFlags::MS_MANDLOCK));
m.insert("atime", (true, MsFlags::MS_NOATIME));
m.insert("noatime", (false, MsFlags::MS_NOATIME));
m.insert("diratime", (true, MsFlags::MS_NODIRATIME));
m.insert("nodiratime", (false, MsFlags::MS_NODIRATIME));
m.insert("bind", (false, MsFlags::MS_BIND));
m.insert("rbind", (false, MsFlags::MS_BIND | MsFlags::MS_REC));
m.insert("unbindable", (false, MsFlags::MS_UNBINDABLE));
m.insert(
"runbindable",
(false, MsFlags::MS_UNBINDABLE | MsFlags::MS_REC),
);
m.insert("private", (false, MsFlags::MS_PRIVATE));
m.insert("rprivate", (false, MsFlags::MS_PRIVATE | MsFlags::MS_REC));
m.insert("shared", (false, MsFlags::MS_SHARED));
m.insert("rshared", (false, MsFlags::MS_SHARED | MsFlags::MS_REC));
m.insert("slave", (false, MsFlags::MS_SLAVE));
m.insert("rslave", (false, MsFlags::MS_SLAVE | MsFlags::MS_REC));
m.insert("relatime", (false, MsFlags::MS_RELATIME));
m.insert("norelatime", (true, MsFlags::MS_RELATIME));
m.insert("strictatime", (false, MsFlags::MS_STRICTATIME));
m.insert("nostrictatime", (true, MsFlags::MS_STRICTATIME));
m
};
}
#[inline(always)]
#[allow(unused_variables)]
pub fn mount<
P1: ?Sized + NixPath,
P2: ?Sized + NixPath,
P3: ?Sized + NixPath,
P4: ?Sized + NixPath,
>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>,
) -> std::result::Result<(), nix::Error> {
#[cfg(not(test))]
return mount::mount(source, target, fstype, flags, data);
#[cfg(test)]
return Ok(());
}
#[inline(always)]
#[allow(unused_variables)]
pub fn umount2<P: ?Sized + NixPath>(
target: &P,
flags: MntFlags,
) -> std::result::Result<(), nix::Error> {
#[cfg(not(test))]
return mount::umount2(target, flags);
#[cfg(test)]
return Ok(());
}
pub fn init_rootfs(
cfd_log: RawFd,
spec: &Spec,
cpath: &HashMap<String, String>,
mounts: &HashMap<String, String>,
bind_device: bool,
) -> Result<()> {
lazy_static::initialize(&OPTIONS);
lazy_static::initialize(&PROPAGATION);
lazy_static::initialize(&LINUXDEVICETYPE);
let linux = &spec
.linux
.as_ref()
.ok_or_else(|| anyhow!("Could not get linux configuration from spec"))?;
let mut flags = MsFlags::MS_REC;
match PROPAGATION.get(&linux.rootfs_propagation.as_str()) {
Some(fl) => flags |= *fl,
None => flags |= MsFlags::MS_SLAVE,
}
let root = spec
.root
.as_ref()
.ok_or_else(|| anyhow!("Could not get rootfs path from spec"))
.and_then(|r| {
fs::canonicalize(r.path.as_str()).context("Could not canonicalize rootfs path")
})?;
let rootfs = (*root)
.to_str()
.ok_or_else(|| anyhow!("Could not convert rootfs path to string"))?;
mount(None::<&str>, "/", None::<&str>, flags, None::<&str>)?;
rootfs_parent_mount_private(rootfs)?;
mount(
Some(rootfs),
rootfs,
None::<&str>,
MsFlags::MS_BIND | MsFlags::MS_REC,
None::<&str>,
)?;
let mut bind_mount_dev = false;
for m in &spec.mounts {
let (mut flags, data) = parse_mount(&m);
if !m.destination.starts_with('/') || m.destination.contains("..") {
return Err(anyhow!(
"the mount destination {} is invalid",
m.destination
));
}
if m.r#type == "cgroup" {
mount_cgroups(cfd_log, &m, rootfs, flags, &data, cpath, mounts)?;
} else {
if m.destination == "/dev" {
if m.r#type == "bind" {
bind_mount_dev = true;
}
flags &= !MsFlags::MS_RDONLY;
}
if m.r#type == "bind" {
check_proc_mount(m)?;
}
// If the destination already exists and is not a directory, we bail
// out This is to avoid mounting through a symlink or similar -- which
// has been a "fun" attack scenario in the past.
if m.r#type == "proc" || m.r#type == "sysfs" {
if let Ok(meta) = fs::symlink_metadata(&m.destination) {
if !meta.is_dir() {
return Err(anyhow!(
"Mount point {} must be ordinary directory: got {:?}",
m.destination,
meta.file_type()
));
}
}
}
mount_from(cfd_log, &m, &rootfs, flags, &data, "")?;
// bind mount won't change mount options, we need remount to make mount options
// effective.
// first check that we have non-default options required before attempting a
// remount
if m.r#type == "bind" {
for o in &m.options {
if let Some(fl) = PROPAGATION.get(o.as_str()) {
let dest = secure_join(rootfs, &m.destination);
mount(None::<&str>, dest.as_str(), None::<&str>, *fl, None::<&str>)?;
}
}
}
}
}
let olddir = unistd::getcwd()?;
unistd::chdir(rootfs)?;
// in case the /dev directory was binded mount from guest,
// then there's no need to create devices nodes and symlinks
// in /dev.
if !bind_mount_dev {
default_symlinks()?;
create_devices(&linux.devices, bind_device)?;
ensure_ptmx()?;
}
unistd::chdir(&olddir)?;
Ok(())
}
fn check_proc_mount(m: &Mount) -> Result<()> {
// White list, it should be sub directories of invalid destinations
// These entries can be bind mounted by files emulated by fuse,
// so commands like top, free displays stats in container.
let valid_destinations = [
"/proc/cpuinfo",
"/proc/diskstats",
"/proc/meminfo",
"/proc/stat",
"/proc/swaps",
"/proc/uptime",
"/proc/loadavg",
"/proc/net/dev",
];
for i in valid_destinations.iter() {
if m.destination.as_str() == *i {
return Ok(());
}
}
if m.destination == PROC_PATH {
// only allow a mount on-top of proc if it's source is "proc"
unsafe {
let mut stats = MaybeUninit::<libc::statfs>::uninit();
if m.source
.with_nix_path(|path| libc::statfs(path.as_ptr(), stats.as_mut_ptr()))
.is_ok()
{
if stats.assume_init().f_type == PROC_SUPER_MAGIC {
return Ok(());
}
} else {
return Ok(());
}
return Err(anyhow!(format!(
"{} cannot be mounted to {} because it is not of type proc",
m.source, m.destination
)));
}
}
if m.destination.starts_with(PROC_PATH) {
return Err(anyhow!(format!(
"{} cannot be mounted because it is inside /proc",
m.destination
)));
}
Ok(())
}
fn mount_cgroups_v2(cfd_log: RawFd, m: &Mount, rootfs: &str, flags: MsFlags) -> Result<()> {
let olddir = unistd::getcwd()?;
unistd::chdir(rootfs)?;
// https://github.com/opencontainers/runc/blob/09ddc63afdde16d5fb859a1d3ab010bd45f08497/libcontainer/rootfs_linux.go#L287
let bm = Mount {
source: "cgroup".to_string(),
r#type: "cgroup2".to_string(),
destination: m.destination.clone(),
options: Vec::new(),
};
let mount_flags: MsFlags = flags;
mount_from(cfd_log, &bm, rootfs, mount_flags, "", "")?;
unistd::chdir(&olddir)?;
if flags.contains(MsFlags::MS_RDONLY) {
let dest = format!("{}{}", rootfs, m.destination.as_str());
mount(
Some(dest.as_str()),
dest.as_str(),
None::<&str>,
flags | MsFlags::MS_BIND | MsFlags::MS_REMOUNT,
None::<&str>,
)?;
}
Ok(())
}
fn mount_cgroups(
cfd_log: RawFd,
m: &Mount,
rootfs: &str,
flags: MsFlags,
_data: &str,
cpath: &HashMap<String, String>,
mounts: &HashMap<String, String>,
) -> Result<()> {
if cgroups::hierarchies::is_cgroup2_unified_mode() {
return mount_cgroups_v2(cfd_log, &m, rootfs, flags);
}
// mount tmpfs
let ctm = Mount {
source: "tmpfs".to_string(),
r#type: "tmpfs".to_string(),
destination: m.destination.clone(),
options: Vec::new(),
};
let cflags = MsFlags::MS_NOEXEC | MsFlags::MS_NOSUID | MsFlags::MS_NODEV;
mount_from(cfd_log, &ctm, rootfs, cflags, "", "")?;
let olddir = unistd::getcwd()?;
unistd::chdir(rootfs)?;
let mut srcs: HashSet<String> = HashSet::new();
// bind mount cgroups
for (key, mount) in mounts.iter() {
log_child!(cfd_log, "mount cgroup subsystem {}", key);
let source = if cpath.get(key).is_some() {
cpath.get(key).unwrap()
} else {
continue;
};
let base = if let Some(o) = mount.rfind('/') {
&mount[o + 1..]
} else {
&mount[..]
};
let destination = format!("{}/{}", m.destination.as_str(), base);
if srcs.contains(source) {
// already mounted, xxx,yyy style cgroup
if key != base {
let src = format!("{}/{}", m.destination.as_str(), key);
unix::fs::symlink(destination.as_str(), &src[1..])?;
}
continue;
}
srcs.insert(source.to_string());
log_child!(cfd_log, "mount destination: {}", destination.as_str());
let bm = Mount {
source: source.to_string(),
r#type: "bind".to_string(),
destination: destination.clone(),
options: Vec::new(),
};
let mut mount_flags: MsFlags = flags | MsFlags::MS_REC | MsFlags::MS_BIND;
if key.contains("systemd") {
mount_flags &= !MsFlags::MS_RDONLY;
}
mount_from(cfd_log, &bm, rootfs, mount_flags, "", "")?;
if key != base {
let src = format!("{}/{}", m.destination.as_str(), key);
unix::fs::symlink(destination.as_str(), &src[1..]).map_err(|e| {
log_child!(
cfd_log,
"symlink: {} {} err: {}",
key,
destination.as_str(),
e.to_string()
);
e
})?;
}
}
unistd::chdir(&olddir)?;
if flags.contains(MsFlags::MS_RDONLY) {
let dest = format!("{}{}", rootfs, m.destination.as_str());
mount(
Some(dest.as_str()),
dest.as_str(),
None::<&str>,
flags | MsFlags::MS_BIND | MsFlags::MS_REMOUNT,
None::<&str>,
)?;
}
Ok(())
}
#[allow(unused_variables)]
fn pivot_root<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
new_root: &P1,
put_old: &P2,
) -> anyhow::Result<(), nix::Error> {
#[cfg(not(test))]
return unistd::pivot_root(new_root, put_old);
#[cfg(test)]
return Ok(());
}
pub fn pivot_rootfs<P: ?Sized + NixPath + std::fmt::Debug>(path: &P) -> Result<()> {
let oldroot = fcntl::open("/", OFlag::O_DIRECTORY | OFlag::O_RDONLY, Mode::empty())?;
defer!(unistd::close(oldroot).unwrap());
let newroot = fcntl::open(path, OFlag::O_DIRECTORY | OFlag::O_RDONLY, Mode::empty())?;
defer!(unistd::close(newroot).unwrap());
// Change to the new root so that the pivot_root actually acts on it.
unistd::fchdir(newroot)?;
pivot_root(".", ".").context(format!("failed to pivot_root on {:?}", path))?;
// Currently our "." is oldroot (according to the current kernel code).
// However, purely for safety, we will fchdir(oldroot) since there isn't
// really any guarantee from the kernel what /proc/self/cwd will be after a
// pivot_root(2).
unistd::fchdir(oldroot)?;
// Make oldroot rslave to make sure our unmounts don't propagate to the
// host. We don't use rprivate because this is known to cause issues due
// to races where we still have a reference to a mount while a process in
// the host namespace are trying to operate on something they think has no
// mounts (devicemapper in particular).
mount(
Some("none"),
".",
Some(""),
MsFlags::MS_SLAVE | MsFlags::MS_REC,
Some(""),
)?;
// Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd.
umount2(".", MntFlags::MNT_DETACH).context("failed to do umount2")?;
// Switch back to our shiny new root.
unistd::chdir("/")?;
stat::umask(Mode::from_bits_truncate(0o022));
Ok(())
}
fn rootfs_parent_mount_private(path: &str) -> Result<()> {
let mount_infos = parse_mount_table()?;
let mut max_len = 0;
let mut mount_point = String::from("");
let mut options = String::from("");
for i in mount_infos {
if path.starts_with(&i.mount_point) && i.mount_point.len() > max_len {
max_len = i.mount_point.len();
mount_point = i.mount_point;
options = i.optional;
}
}
if options.contains("shared:") {
mount(
None::<&str>,
mount_point.as_str(),
None::<&str>,
MsFlags::MS_PRIVATE,
None::<&str>,
)?;
}
Ok(())
}
// Parse /proc/self/mountinfo because comparing Dev and ino does not work from
// bind mounts
fn parse_mount_table() -> Result<Vec<Info>> {
let file = File::open("/proc/self/mountinfo")?;
let reader = BufReader::new(file);
let mut infos = Vec::new();
for (_index, line) in reader.lines().enumerate() {
let line = line?;
let (id, parent, major, minor, root, mount_point, opts, optional) = scan_fmt!(
&line,
MOUNTINFOFORMAT,
i32,
i32,
i32,
i32,
String,
String,
String,
String
)?;
let fields: Vec<&str> = line.split(" - ").collect();
if fields.len() == 2 {
let (fstype, source, vfs_opts) =
scan_fmt!(fields[1], "{} {} {}", String, String, String)?;
let mut optional_new = String::new();
if optional != "-" {
optional_new = optional;
}
let info = Info {
id,
parent,
major,
minor,
root,
mount_point,
opts,
optional: optional_new,
fstype,
source,
vfs_opts,
};
infos.push(info);
} else {
return Err(anyhow!("failed to parse mount info file".to_string()));
}
}
Ok(infos)
}
#[inline(always)]
#[allow(unused_variables)]
fn chroot<P: ?Sized + NixPath>(path: &P) -> Result<(), nix::Error> {
#[cfg(not(test))]
return unistd::chroot(path);
#[cfg(test)]
return Ok(());
}
pub fn ms_move_root(rootfs: &str) -> Result<bool> {
unistd::chdir(rootfs)?;
let mount_infos = parse_mount_table()?;
let root_path = Path::new(rootfs);
let abs_root_buf = root_path.absolutize()?;
let abs_root = abs_root_buf
.to_str()
.ok_or_else(|| anyhow!("failed to parse {} to absolute path", rootfs))?;
for info in mount_infos.iter() {
let mount_point = Path::new(&info.mount_point);
let abs_mount_buf = mount_point.absolutize()?;
let abs_mount_point = abs_mount_buf
.to_str()
.ok_or_else(|| anyhow!("failed to parse {} to absolute path", info.mount_point))?;
let abs_mount_point_string = String::from(abs_mount_point);
// Umount every syfs and proc file systems, except those under the container rootfs
if (info.fstype != "proc" && info.fstype != "sysfs")
|| abs_mount_point_string.starts_with(abs_root)
{
continue;
}
// Be sure umount events are not propagated to the host.
mount(
None::<&str>,
abs_mount_point,
None::<&str>,
MsFlags::MS_SLAVE | MsFlags::MS_REC,
None::<&str>,
)?;
umount2(abs_mount_point, MntFlags::MNT_DETACH).or_else(|e| {
if e.ne(&nix::Error::from(Errno::EINVAL)) && e.ne(&nix::Error::from(Errno::EPERM)) {
return Err(anyhow!(e));
}
// If we have not privileges for umounting (e.g. rootless), then
// cover the path.
mount(
Some("tmpfs"),
abs_mount_point,
Some("tmpfs"),
MsFlags::empty(),
None::<&str>,
)?;
Ok(())
})?;
}
mount(
Some(abs_root),
"/",
None::<&str>,
MsFlags::MS_MOVE,
None::<&str>,
)?;
chroot(".")?;
unistd::chdir("/")?;
Ok(true)
}
fn parse_mount(m: &Mount) -> (MsFlags, String) {
let mut flags = MsFlags::empty();
let mut data = Vec::new();
for o in &m.options {
match OPTIONS.get(o.as_str()) {
Some(v) => {
let (clear, fl) = *v;
if clear {
flags &= !fl;
} else {
flags |= fl;
}
}
None => data.push(o.clone()),
}
}
(flags, data.join(","))
}
// This function constructs a canonicalized path by combining the `rootfs` and `unsafe_path` elements.
// The resulting path is guaranteed to be ("below" / "in a directory under") the `rootfs` directory.
//
// Parameters:
//
// - `rootfs` is the absolute path to the root of the containers root filesystem directory.
// - `unsafe_path` is path inside a container. It is unsafe since it may try to "escape" from the containers
// rootfs by using one or more "../" path elements or is its a symlink to path.
fn secure_join(rootfs: &str, unsafe_path: &str) -> String {
let mut path = PathBuf::from(format!("{}/", rootfs));
let unsafe_p = Path::new(&unsafe_path);
for it in unsafe_p.iter() {
let it_p = Path::new(&it);
// if it_p leads with "/", path.push(it) will be replace as it, so ignore "/"
if it_p.has_root() {
continue;
};
path.push(it);
if let Ok(v) = path.read_link() {
if v.is_absolute() {
path = PathBuf::from(format!("{}{}", rootfs, v.to_str().unwrap().to_string()));
} else {
path.pop();
for it in v.iter() {
path.push(it);
if path.exists() {
path = path.canonicalize().unwrap();
if !path.starts_with(rootfs) {
path = PathBuf::from(rootfs.to_string());
}
}
}
}
}
// skip any ".."
if path.ends_with("..") {
path.pop();
}
}
path.to_str().unwrap().to_string()
}
fn mount_from(
cfd_log: RawFd,
m: &Mount,
rootfs: &str,
flags: MsFlags,
data: &str,
_label: &str,
) -> Result<()> {
let d = String::from(data);
let dest = secure_join(rootfs, &m.destination);
let src = if m.r#type.as_str() == "bind" {
let src = fs::canonicalize(m.source.as_str())?;
let dir = if src.is_dir() {
Path::new(&dest)
} else {
Path::new(&dest).parent().unwrap()
};
let _ = fs::create_dir_all(&dir).map_err(|e| {
log_child!(
cfd_log,
"creat dir {}: {}",
dir.to_str().unwrap(),
e.to_string()
)
});
// make sure file exists so we can bind over it
if !src.is_dir() {
let _ = OpenOptions::new().create(true).write(true).open(&dest);
}
src.to_str().unwrap().to_string()
} else {
let _ = fs::create_dir_all(&dest);
if m.r#type.as_str() == "cgroup2" {
"cgroup2".to_string()
} else {
let tmp = PathBuf::from(&m.source);
tmp.to_str().unwrap().to_string()
}
};
let _ = stat::stat(dest.as_str()).map_err(|e| {
log_child!(
cfd_log,
"dest stat error. {}: {:?}",
dest.as_str(),
e.as_errno()
)
});
mount(
Some(src.as_str()),
dest.as_str(),
Some(m.r#type.as_str()),
flags,
Some(d.as_str()),
)
.map_err(|e| {
log_child!(cfd_log, "mount error: {:?}", e.as_errno());
e
})?;
if flags.contains(MsFlags::MS_BIND)
&& flags.intersects(
!(MsFlags::MS_REC
| MsFlags::MS_REMOUNT
| MsFlags::MS_BIND
| MsFlags::MS_PRIVATE
| MsFlags::MS_SHARED
| MsFlags::MS_SLAVE),
)
{
mount(
Some(dest.as_str()),
dest.as_str(),
None::<&str>,
flags | MsFlags::MS_REMOUNT,
None::<&str>,
)
.map_err(|e| {
log_child!(cfd_log, "remout {}: {:?}", dest.as_str(), e.as_errno());
e
})?;
}
Ok(())
}
static SYMLINKS: &[(&str, &str)] = &[
("/proc/self/fd", "dev/fd"),
("/proc/self/fd/0", "dev/stdin"),
("/proc/self/fd/1", "dev/stdout"),
("/proc/self/fd/2", "dev/stderr"),
];
fn default_symlinks() -> Result<()> {
if Path::new("/proc/kcore").exists() {
unix::fs::symlink("/proc/kcore", "dev/kcore")?;
}
for &(src, dst) in SYMLINKS {
unix::fs::symlink(src, dst)?;
}
Ok(())
}
fn create_devices(devices: &[LinuxDevice], bind: bool) -> Result<()> {
let op: fn(&LinuxDevice) -> Result<()> = if bind { bind_dev } else { mknod_dev };
let old = stat::umask(Mode::from_bits_truncate(0o000));
for dev in DEFAULT_DEVICES.iter() {
op(dev)?;
}
for dev in devices {
if !dev.path.starts_with("/dev") || dev.path.contains("..") {
let msg = format!("{} is not a valid device path", dev.path);
bail!(anyhow!(msg));
}
op(dev)?;
}
stat::umask(old);
Ok(())
}
fn ensure_ptmx() -> Result<()> {
let _ = fs::remove_file("dev/ptmx");
unix::fs::symlink("pts/ptmx", "dev/ptmx")?;
Ok(())
}
lazy_static! {
static ref LINUXDEVICETYPE: HashMap<&'static str, SFlag> = {
let mut m = HashMap::new();
m.insert("c", SFlag::S_IFCHR);
m.insert("b", SFlag::S_IFBLK);
m.insert("p", SFlag::S_IFIFO);
m
};
}
fn mknod_dev(dev: &LinuxDevice) -> Result<()> {
let f = match LINUXDEVICETYPE.get(dev.r#type.as_str()) {
Some(v) => v,
None => return Err(anyhow!("invalid spec".to_string())),
};
stat::mknod(
&dev.path[1..],
*f,
Mode::from_bits_truncate(dev.file_mode.unwrap_or(0)),
nix::sys::stat::makedev(dev.major as u64, dev.minor as u64),
)?;
unistd::chown(
&dev.path[1..],
Some(Uid::from_raw(dev.uid.unwrap_or(0) as uid_t)),
Some(Gid::from_raw(dev.gid.unwrap_or(0) as uid_t)),
)?;
Ok(())
}
fn bind_dev(dev: &LinuxDevice) -> Result<()> {
let fd = fcntl::open(
&dev.path[1..],
OFlag::O_RDWR | OFlag::O_CREAT,
Mode::from_bits_truncate(0o644),
)?;
unistd::close(fd)?;
mount(
Some(&*dev.path),
&dev.path[1..],
None::<&str>,
MsFlags::MS_BIND,
None::<&str>,
)?;
Ok(())
}
pub fn finish_rootfs(cfd_log: RawFd, spec: &Spec) -> Result<()> {
let olddir = unistd::getcwd()?;
log_child!(cfd_log, "old cwd: {}", olddir.to_str().unwrap());
unistd::chdir("/")?;
if spec.linux.is_some() {
let linux = spec.linux.as_ref().unwrap();
for path in linux.masked_paths.iter() {
mask_path(path)?;
}
for path in linux.readonly_paths.iter() {
readonly_path(path)?;
}
}
for m in spec.mounts.iter() {
if m.destination == "/dev" {
let (flags, _) = parse_mount(m);
if flags.contains(MsFlags::MS_RDONLY) {
mount(
Some("/dev"),
"/dev",
None::<&str>,
flags | MsFlags::MS_REMOUNT,
None::<&str>,
)?;
}
}
}
if spec.root.as_ref().unwrap().readonly {
let flags = MsFlags::MS_BIND | MsFlags::MS_RDONLY | MsFlags::MS_NODEV | MsFlags::MS_REMOUNT;
mount(Some("/"), "/", None::<&str>, flags, None::<&str>)?;
}
stat::umask(Mode::from_bits_truncate(0o022));
unistd::chdir(&olddir)?;
Ok(())
}
fn mask_path(path: &str) -> Result<()> {
if !path.starts_with('/') || path.contains("..") {
return Err(nix::Error::Sys(Errno::EINVAL).into());
}
match mount(
Some("/dev/null"),
path,
None::<&str>,
MsFlags::MS_BIND,
None::<&str>,
) {
Err(nix::Error::Sys(e)) => {
if e != Errno::ENOENT && e != Errno::ENOTDIR {
//info!("{}: {}", path, e.desc());
return Err(nix::Error::Sys(e).into());
}
}
Err(e) => {
return Err(e.into());
}
Ok(_) => {}
}
Ok(())
}
fn readonly_path(path: &str) -> Result<()> {
if !path.starts_with('/') || path.contains("..") {
return Err(nix::Error::Sys(Errno::EINVAL).into());
}
match mount(
Some(&path[1..]),
path,
None::<&str>,
MsFlags::MS_BIND | MsFlags::MS_REC,
None::<&str>,
) {
Err(nix::Error::Sys(e)) => {
if e == Errno::ENOENT {
return Ok(());
} else {
//info!("{}: {}", path, e.desc());
return Err(nix::Error::Sys(e).into());
}
}
Err(e) => {
return Err(e.into());
}
Ok(_) => {}
}
mount(
Some(&path[1..]),
&path[1..],
None::<&str>,
MsFlags::MS_BIND | MsFlags::MS_REC | MsFlags::MS_RDONLY | MsFlags::MS_REMOUNT,
None::<&str>,
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::skip_if_not_root;
use std::fs::create_dir;
use std::fs::create_dir_all;
use std::fs::remove_dir_all;
use std::os::unix::fs;
use std::os::unix::io::AsRawFd;
use tempfile::tempdir;
#[test]
#[serial(chdir)]
fn test_init_rootfs() {
let stdout_fd = std::io::stdout().as_raw_fd();
let mut spec = oci::Spec::default();
let cpath = HashMap::new();
let mounts = HashMap::new();
// there is no spec.linux, should fail
let ret = init_rootfs(stdout_fd, &spec, &cpath, &mounts, true);
assert!(
ret.is_err(),
"Should fail: there is no spec.linux. Got: {:?}",
ret
);
// there is no spec.Root, should fail
spec.linux = Some(oci::Linux::default());
let ret = init_rootfs(stdout_fd, &spec, &cpath, &mounts, true);
assert!(
ret.is_err(),
"should fail: there is no spec.Root. Got: {:?}",
ret
);
let rootfs = tempdir().unwrap();
let ret = create_dir(rootfs.path().join("dev"));
assert!(ret.is_ok(), "Got: {:?}", ret);
spec.root = Some(oci::Root {
path: rootfs.path().to_str().unwrap().to_string(),
readonly: false,
});
// there is no spec.mounts, but should pass
let ret = init_rootfs(stdout_fd, &spec, &cpath, &mounts, true);
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
let _ = remove_dir_all(rootfs.path().join("dev"));
let _ = create_dir(rootfs.path().join("dev"));
// Adding bad mount point to spec.mounts
spec.mounts.push(oci::Mount {
destination: "error".into(),
r#type: "bind".into(),
source: "error".into(),
options: vec!["shared".into(), "rw".into(), "dev".into()],
});
// destination doesn't start with /, should fail
let ret = init_rootfs(stdout_fd, &spec, &cpath, &mounts, true);
assert!(
ret.is_err(),
"Should fail: destination doesn't start with '/'. Got: {:?}",
ret
);
spec.mounts.pop();
let _ = remove_dir_all(rootfs.path().join("dev"));
let _ = create_dir(rootfs.path().join("dev"));
// mounting a cgroup
spec.mounts.push(oci::Mount {
destination: "/cgroup".into(),
r#type: "cgroup".into(),
source: "/cgroup".into(),
options: vec!["shared".into()],
});
let ret = init_rootfs(stdout_fd, &spec, &cpath, &mounts, true);
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
spec.mounts.pop();
let _ = remove_dir_all(rootfs.path().join("dev"));
let _ = create_dir(rootfs.path().join("dev"));
// mounting /dev
spec.mounts.push(oci::Mount {
destination: "/dev".into(),
r#type: "bind".into(),
source: "/dev".into(),
options: vec!["shared".into()],
});
let ret = init_rootfs(stdout_fd, &spec, &cpath, &mounts, true);
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
#[serial(chdir)]
fn test_mount_cgroups() {
let stdout_fd = std::io::stdout().as_raw_fd();
let mount = oci::Mount {
destination: "/cgroups".to_string(),
r#type: "cgroup".to_string(),
source: "/cgroups".to_string(),
options: vec!["shared".to_string()],
};
let tempdir = tempdir().unwrap();
let rootfs = tempdir.path().to_str().unwrap().to_string();
let flags = MsFlags::MS_RDONLY;
let mut cpath = HashMap::new();
let mut cgroup_mounts = HashMap::new();
cpath.insert("cpu".to_string(), "cpu".to_string());
cpath.insert("memory".to_string(), "memory".to_string());
cgroup_mounts.insert("default".to_string(), "default".to_string());
cgroup_mounts.insert("cpu".to_string(), "cpu".to_string());
cgroup_mounts.insert("memory".to_string(), "memory".to_string());
let ret = create_dir_all(tempdir.path().join("cgroups"));
assert!(ret.is_ok(), "Should pass. Got {:?}", ret);
let ret = create_dir_all(tempdir.path().join("cpu"));
assert!(ret.is_ok(), "Should pass. Got {:?}", ret);
let ret = create_dir_all(tempdir.path().join("memory"));
assert!(ret.is_ok(), "Should pass. Got {:?}", ret);
let ret = mount_cgroups(
stdout_fd,
&mount,
&rootfs,
flags,
"",
&cpath,
&cgroup_mounts,
);
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
#[serial(chdir)]
fn test_pivot_root() {
let ret = pivot_rootfs("/tmp");
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
#[serial(chdir)]
fn test_ms_move_rootfs() {
let ret = ms_move_root("/abc");
assert!(
ret.is_err(),
"Should fail. path doesn't exist. Got: {:?}",
ret
);
let ret = ms_move_root("/tmp");
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
fn test_mask_path() {
let ret = mask_path("abc");
assert!(
ret.is_err(),
"Should fail: path doesn't start with '/'. Got: {:?}",
ret
);
let ret = mask_path("abc/../");
assert!(
ret.is_err(),
"Should fail: path contains '..'. Got: {:?}",
ret
);
let ret = mask_path("/tmp");
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
#[serial(chdir)]
fn test_finish_rootfs() {
let stdout_fd = std::io::stdout().as_raw_fd();
let mut spec = oci::Spec::default();
spec.linux = Some(oci::Linux::default());
spec.linux.as_mut().unwrap().masked_paths = vec!["/tmp".to_string()];
spec.linux.as_mut().unwrap().readonly_paths = vec!["/tmp".to_string()];
spec.root = Some(oci::Root {
path: "/tmp".to_string(),
readonly: true,
});
spec.mounts = vec![oci::Mount {
destination: "/dev".to_string(),
r#type: "bind".to_string(),
source: "/dev".to_string(),
options: vec!["ro".to_string(), "shared".to_string()],
}];
let ret = finish_rootfs(stdout_fd, &spec);
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
fn test_readonly_path() {
let ret = readonly_path("abc");
assert!(ret.is_err(), "Should fail. Got: {:?}", ret);
let ret = readonly_path("../../");
assert!(ret.is_err(), "Should fail. Got: {:?}", ret);
let ret = readonly_path("/tmp");
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
#[serial(chdir)]
fn test_mknod_dev() {
skip_if_not_root!();
let tempdir = tempdir().unwrap();
let olddir = unistd::getcwd().unwrap();
defer!(let _ = unistd::chdir(&olddir););
let _ = unistd::chdir(tempdir.path());
let dev = oci::LinuxDevice {
path: "/fifo".to_string(),
r#type: "c".to_string(),
major: 0,
minor: 0,
file_mode: Some(0660),
uid: Some(unistd::getuid().as_raw()),
gid: Some(unistd::getgid().as_raw()),
};
let ret = mknod_dev(&dev);
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
let ret = stat::stat("fifo");
assert!(ret.is_ok(), "Should pass. Got: {:?}", ret);
}
#[test]
fn test_check_proc_mount() {
let mount = oci::Mount {
destination: "/proc".to_string(),
r#type: "bind".to_string(),
source: "/test".to_string(),
options: vec!["shared".to_string()],
};
assert!(check_proc_mount(&mount).is_err());
let mount = oci::Mount {
destination: "/proc/cpuinfo".to_string(),
r#type: "bind".to_string(),
source: "/test".to_string(),
options: vec!["shared".to_string()],
};
assert!(check_proc_mount(&mount).is_ok());
let mount = oci::Mount {
destination: "/proc/test".to_string(),
r#type: "bind".to_string(),
source: "/test".to_string(),
options: vec!["shared".to_string()],
};
assert!(check_proc_mount(&mount).is_err());
}
#[test]
fn test_secure_join() {
#[derive(Debug)]
struct TestData<'a> {
name: &'a str,
rootfs: &'a str,
unsafe_path: &'a str,
symlink_path: &'a str,
result: &'a str,
}
// create tempory directory to simulate container rootfs with symlink
let rootfs_dir = tempdir().expect("failed to create tmpdir");
let rootfs_path = rootfs_dir.path().to_str().unwrap();
let tests = &[
TestData {
name: "rootfs_not_exist",
rootfs: "/home/rootfs",
unsafe_path: "a/b/c",
symlink_path: "",
result: "/home/rootfs/a/b/c",
},
TestData {
name: "relative_path",
rootfs: "/home/rootfs",
unsafe_path: "../../../a/b/c",
symlink_path: "",
result: "/home/rootfs/a/b/c",
},
TestData {
name: "skip any ..",
rootfs: "/home/rootfs",
unsafe_path: "../../../a/../../b/../../c",
symlink_path: "",
result: "/home/rootfs/a/b/c",
},
TestData {
name: "rootfs is null",
rootfs: "",
unsafe_path: "",
symlink_path: "",
result: "/",
},
TestData {
name: "relative softlink beyond container rootfs",
rootfs: rootfs_path,
unsafe_path: "1",
symlink_path: "../../../",
result: rootfs_path,
},
TestData {
name: "abs softlink points to the non-exist directory",
rootfs: rootfs_path,
unsafe_path: "2",
symlink_path: "/dddd",
result: &format!("{}/dddd", rootfs_path).as_str().to_owned(),
},
TestData {
name: "abs softlink points to the root",
rootfs: rootfs_path,
unsafe_path: "3",
symlink_path: "/",
result: &format!("{}/", rootfs_path).as_str().to_owned(),
},
];
for (i, t) in tests.iter().enumerate() {
// Create a string containing details of the test
let msg = format!("test[{}]: {:?}", i, t);
// if is_symlink, then should be prepare the softlink environment
if t.symlink_path != "" {
fs::symlink(t.symlink_path, format!("{}/{}", t.rootfs, t.unsafe_path)).unwrap();
}
let result = secure_join(t.rootfs, t.unsafe_path);
// Update the test details string with the results of the call
let msg = format!("{}, result: {:?}", msg, result);
// Perform the checks
assert!(result == t.result, msg);
}
}
}
| 30.148688 | 125 | 0.508365 |
623b6ad4ead2359f3454ef667d8695915fa81998 | 4,828 | use std::hash::{Hash, Hasher};
use std::{collections::hash_map::DefaultHasher, sync::Arc};
use hash_hasher::HashedMap;
use crate::array::TryExtend;
use crate::{
array::{primitive::MutablePrimitiveArray, Array, MutableArray},
bitmap::MutableBitmap,
datatypes::DataType,
error::{ArrowError, Result},
};
use super::{DictionaryArray, DictionaryKey};
/// A mutable, strong-typed version of [`DictionaryArray`].
#[derive(Debug)]
pub struct MutableDictionaryArray<K: DictionaryKey, M: MutableArray> {
data_type: DataType,
keys: MutablePrimitiveArray<K>,
map: HashedMap<u64, K>,
values: M,
}
impl<K: DictionaryKey, M: MutableArray> From<MutableDictionaryArray<K, M>> for DictionaryArray<K> {
fn from(mut other: MutableDictionaryArray<K, M>) -> Self {
DictionaryArray::<K>::from_data(other.keys.into(), other.values.as_arc())
}
}
impl<K: DictionaryKey, M: MutableArray> From<M> for MutableDictionaryArray<K, M> {
fn from(values: M) -> Self {
Self {
data_type: DataType::Dictionary(K::KEY_TYPE, Box::new(values.data_type().clone())),
keys: MutablePrimitiveArray::<K>::new(),
map: HashedMap::default(),
values,
}
}
}
impl<K: DictionaryKey, M: MutableArray + Default> MutableDictionaryArray<K, M> {
/// Creates an empty [`MutableDictionaryArray`].
pub fn new() -> Self {
let values = M::default();
Self {
data_type: DataType::Dictionary(K::KEY_TYPE, Box::new(values.data_type().clone())),
keys: MutablePrimitiveArray::<K>::new(),
map: HashedMap::default(),
values,
}
}
}
impl<K: DictionaryKey, M: MutableArray + Default> Default for MutableDictionaryArray<K, M> {
fn default() -> Self {
Self::new()
}
}
impl<K: DictionaryKey, M: MutableArray> MutableDictionaryArray<K, M> {
/// Returns whether the value should be pushed to the values or not
pub fn try_push_valid<T: Hash>(&mut self, value: &T) -> Result<bool> {
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
let hash = hasher.finish();
match self.map.get(&hash) {
Some(key) => {
self.keys.push(Some(*key));
Ok(false)
}
None => {
let key = K::from_usize(self.map.len()).ok_or(ArrowError::KeyOverflowError)?;
self.map.insert(hash, key);
self.keys.push(Some(key));
Ok(true)
}
}
}
/// pushes a null value
pub fn push_null(&mut self) {
self.keys.push(None)
}
/// returns a mutable reference to the inner values.
pub fn mut_values(&mut self) -> &mut M {
&mut self.values
}
/// returns a reference to the inner values.
pub fn values(&self) -> &M {
&self.values
}
/// converts itself into `Arc<dyn Array>`
pub fn into_arc(self) -> Arc<dyn Array> {
let a: DictionaryArray<K> = self.into();
Arc::new(a)
}
/// Shrinks the capacity of the [`MutableDictionaryArray`] to fit its current length.
pub fn shrink_to_fit(&mut self) {
self.values.shrink_to_fit();
self.keys.shrink_to_fit();
}
}
impl<K: DictionaryKey, M: 'static + MutableArray> MutableArray for MutableDictionaryArray<K, M> {
fn len(&self) -> usize {
self.keys.len()
}
fn validity(&self) -> Option<&MutableBitmap> {
self.keys.validity()
}
fn as_box(&mut self) -> Box<dyn Array> {
Box::new(DictionaryArray::<K>::from_data(
std::mem::take(&mut self.keys).into(),
self.values.as_arc(),
))
}
fn as_arc(&mut self) -> Arc<dyn Array> {
Arc::new(DictionaryArray::<K>::from_data(
std::mem::take(&mut self.keys).into(),
self.values.as_arc(),
))
}
fn data_type(&self) -> &DataType {
&self.data_type
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
fn push_null(&mut self) {
self.keys.push(None)
}
fn shrink_to_fit(&mut self) {
self.shrink_to_fit()
}
}
impl<K, M, T: Hash> TryExtend<Option<T>> for MutableDictionaryArray<K, M>
where
K: DictionaryKey,
M: MutableArray + TryExtend<Option<T>>,
{
fn try_extend<II: IntoIterator<Item = Option<T>>>(&mut self, iter: II) -> Result<()> {
for value in iter {
if let Some(value) = value {
if self.try_push_valid(&value)? {
self.mut_values().try_extend(std::iter::once(Some(value)))?;
}
} else {
self.push_null();
}
}
Ok(())
}
}
| 28.4 | 99 | 0.569801 |
0843d4f95065854e551e67075e30f2fbcb2399f7 | 8,573 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! https://adventofcode.com/2018/day/11
use aoc2018::point;
use aoc2018::Matrix;
// Performance can probably be improved by remembering the sum of some
// (aligned? even sized?) blocks and using them when computing the sum of
// larger enclosing blocks. But the brute force approach works in a basically
// acceptable amount of time; about 50s.
//
// Or: roll lines of squares into and out of the currently computed square,
// as it moves across the page, rather than summing up every square as we go.
// And in fact, to move down a line, we need only roll one set of squares in
// and one set out.
const SIZE: usize = 300;
fn solve_a() -> ((usize, usize), i32) {
Map::new(7672).hottest(3)
}
fn solve_b() -> ((usize, usize), usize, i32) {
Map::new(7672).hottest_square()
}
pub fn main() {
println!("best of size 3: {:?}", solve_a());
println!("best of any size: {:?}", solve_b());
}
struct Map {
/// Power levels indexed by `point(x, y)`.
/// In the problem description indices are 1-based but for simplicity
/// these are 1-based, and we convert on output.
p: Matrix<i32>,
}
impl Map {
pub fn new(grid: i32) -> Map {
let mut p = Matrix::new(SIZE + 1, SIZE + 1, i32::min_value());
for x in 0..SIZE {
for y in 0..SIZE {
// Find the fuel cell's rack ID, which is its X coordinate
// plus 10.
let rack_id = (x + 1) as i32 + 10;
// Begin with a power level of the rack ID times the Y coordinate.
let mut pwr: i32 = rack_id * (y + 1) as i32;
// Increase the power level by the value of the grid serial
// number (your puzzle input).
pwr += grid;
// Set the power level to itself multiplied by the rack ID.
pwr *= rack_id;
// Keep only the hundreds digit of the power level (so 12345 becomes 3;
// numbers with no hundreds digit become 0).
pwr = (pwr / 100) % 10;
// Subtract 5 from the power level.
pwr -= 5;
p[point(x, y)] = pwr;
}
}
Map { p }
}
#[cfg(test)]
pub fn get(&self, c: (usize, usize)) -> i32 {
self.p[point(c.0, c.1)]
}
pub fn squaresum(&self, c: (usize, usize), sqsz: usize) -> i32 {
let mut s: i32 = 0;
for x in c.0..(c.0 + sqsz) {
for y in c.1..(c.1 + sqsz) {
s += self.p[point(x, y)];
}
}
s
}
pub fn hottest(&self, sqsz: usize) -> ((usize, usize), i32) {
let mut best_power: i32 = i32::min_value();
let mut best_point: (usize, usize) = (0, 0);
for x in 0..(SIZE - sqsz) {
for y in 0..(SIZE - sqsz) {
let p = (x, y);
let pwr = self.squaresum(p, sqsz);
if pwr > best_power {
best_power = pwr;
best_point = p;
}
}
}
((best_point.0 + 1, best_point.1 + 1), best_power)
}
/// Find the square within the map that has the largest total power.
///
/// Returns the (x,y) coords of the top of that square, its size, and the
/// total power.
pub fn hottest_square(&self) -> ((usize, usize), usize, i32) {
// General approach here is to work up through squares of increasing
// sizes, starting from 1.
//
// As we go along, we simply remember the origin, size, and total power
// of the most powerful cell we've seen.
//
// As we go along we remember the sum of power of strips of size
// S running vertically down from every possible cell, and also
// horizontally across from every possible cell. (Not from those
// within S of the boundary.) We also remember the sum of power
// for squares of size S in every possible position.
//
// To start with at S=1 these are all trivially the value of each
// cell itself.
//
// To proceed to S+1, we first extend each of the squares
// by adding in the vertical strip for the next column, and the
// horizontal strip for the next row, and the single cell in the
// corner between them. Then, we extend the strips by adding in
// one more square in each direction.
let mut sqs = Matrix::new(SIZE, SIZE, 0i32);
let mut vstr = Matrix::new(SIZE, SIZE, 0i32);
let mut hstr = Matrix::new(SIZE, SIZE, 0i32);
let mut best_p = point(0, 0);
let mut best_power = i32::min_value();
let mut best_size = 1;
// Start at size 1: everything is simply the contents of that cell.
for x in 0..SIZE {
for y in 0..SIZE {
let p = point(x, y);
vstr[p] = self.p[p];
hstr[p] = self.p[p];
sqs[p] = self.p[p];
if self.p[p] > best_power {
best_power = self.p[p];
best_p = p;
}
}
}
for sz in 2..SIZE {
// First, grow all the squares (that can still fit) by adding a strip
// of sz-1 to the right and one to the bottom and one cell in the
// corner.
//
// Squares that don't fit are just ignored henceforth.
let osz = sz - 1;
for x in 0..(SIZE - sz) {
for y in 0..(SIZE - sz) {
let p = point(x, y);
sqs[p] += vstr[point(x + osz, y)]
+ hstr[point(x, y + osz)]
+ self.p[point(x + osz, y + osz)];
if sqs[p] > best_power {
best_power = sqs[p];
best_p = p;
best_size = sz;
}
}
}
// Now, grow all the strips (that can still fit) from osz to sz
// by adding one more square.
for x in 0..(SIZE - sz) {
for y in 0..(SIZE - sz) {
let p = point(x, y);
vstr[p] += self.p[point(x, y + osz)];
hstr[p] += self.p[point(x + osz, y)];
}
}
}
((best_p.x + 1, best_p.y + 1), best_size, best_power)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn examples() {
assert_eq!(Map::new(57).get((122 - 1, 79 - 1)), -5);
// Fuel cell at 217,196, grid serial number 39: power level 0.
assert_eq!(Map::new(39).get((217 - 1, 196 - 1)), 0);
// Fuel cell at 101,153, grid serial number 71: power level 4.
assert_eq!(Map::new(71).get((101 - 1, 153 - 1)), 4);
}
#[test]
fn squaresum_examples() {
let m = Map::new(18);
assert_eq!(m.squaresum((33 - 1, 45 - 1), 3), 29);
assert_eq!(m.hottest(3), ((33, 45), 29));
let m = Map::new(42);
assert_eq!(m.squaresum((21 - 1, 61 - 1), 3), 30);
assert_eq!(m.hottest(3), ((21, 61), 30));
}
#[test]
fn variable_size_1_new() {
// For grid serial number 18, the largest total square (with a total power of 113) is 16x16 and has a top-left corner of 90,269, so its identifier is 90,269,16.
assert_eq!(Map::new(18).hottest_square(), ((90, 269), 16, 113));
}
#[test]
fn variable_size_2_new() {
// For grid serial number 42, the largest total square (with a total power of 119) is 12x12 and has a top-left corner of 232,251, so its identifier is 232,251,12.
assert_eq!(Map::new(42).hottest_square(), ((232, 251), 12, 119));
}
#[test]
fn part_a_solution() {
assert_eq!(super::solve_a(), ((22, 18), 29));
}
#[test]
fn part_b_solution() {
assert_eq!(super::solve_b(), ((234, 197), 14, 98));
}
}
| 35.572614 | 170 | 0.52642 |
1e1c6e4fab9f244895e2cabd6eb9311cf4b3f02f | 22,119 | use std::borrow::Cow;
use crate::avm1::activation::Activation;
use crate::avm1::error::Error;
use crate::avm1::function::{Executable, FunctionObject};
use crate::avm1::object::shared_object::SharedObject;
use crate::avm1::property::Attribute;
use crate::avm1::property_decl::{define_properties_on, Declaration};
use crate::avm1::{Object, ScriptObject, TObject, Value};
use crate::avm_warn;
use crate::display_object::TDisplayObject;
use crate::string::AvmString;
use flash_lso::types::Value as AmfValue;
use flash_lso::types::{AMFVersion, Element, Lso};
use gc_arena::MutationContext;
use json::JsonValue;
const PROTO_DECLS: &[Declaration] = declare_properties! {
"clear" => method(clear);
"close" => method(close);
"connect" => method(connect);
"flush" => method(flush);
"getSize" => method(get_size);
"send" => method(send);
"setFps" => method(set_fps);
"onStatus" => method(on_status);
"onSync" => method(on_sync);
};
const OBJECT_DECLS: &[Declaration] = declare_properties! {
"deleteAll" => method(delete_all);
"getDiskUsage" => method(get_disk_usage);
"getLocal" => method(get_local);
"getRemote" => method(get_remote);
"getMaxSize" => method(get_max_size);
"addListener" => method(add_listener);
"removeListener" => method(remove_listener);
};
pub fn delete_all<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.deleteAll() not implemented");
Ok(Value::Undefined)
}
pub fn get_disk_usage<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.getDiskUsage() not implemented");
Ok(Value::Undefined)
}
/// Serialize a Value to an AmfValue
fn serialize_value<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
elem: Value<'gc>,
) -> Option<AmfValue> {
match elem {
Value::Undefined => Some(AmfValue::Undefined),
Value::Null => Some(AmfValue::Null),
Value::Bool(b) => Some(AmfValue::Bool(b)),
Value::Number(f) => Some(AmfValue::Number(f)),
Value::String(s) => Some(AmfValue::String(s.to_string())),
Value::Object(o) => {
// TODO: Find a more general rule for which object types should be skipped,
// and which turn into undefined.
if o.as_executable().is_some() {
None
} else if o.as_display_object().is_some() {
Some(AmfValue::Undefined)
} else if o.as_array_object().is_some() {
let mut values = Vec::new();
recursive_serialize(activation, o, &mut values);
// TODO: What happens if an exception is thrown here?
let length = o.length(activation).unwrap();
Some(AmfValue::ECMAArray(vec![], values, length as u32))
} else if let Some(xml_node) = o.as_xml_node() {
xml_node
.into_string(&mut |_| true)
.map(|xml_string| AmfValue::XML(xml_string, true))
.ok()
} else if let Some(date) = o.as_date_object() {
date.date_time()
.map(|date_time| AmfValue::Date(date_time.timestamp_millis() as f64, None))
} else {
let mut object_body = Vec::new();
recursive_serialize(activation, o, &mut object_body);
Some(AmfValue::Object(object_body, None))
}
}
}
}
/// Serialize an Object and any children to a JSON object
fn recursive_serialize<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
obj: Object<'gc>,
elements: &mut Vec<Element>,
) {
// Reversed to match flash player ordering
for element_name in obj.get_keys(activation).into_iter().rev() {
if let Ok(elem) = obj.get(element_name, activation) {
if let Some(v) = serialize_value(activation, elem) {
elements.push(Element::new(element_name.to_utf8_lossy(), v));
}
}
}
}
/// Deserialize a AmfValue to a Value
fn deserialize_value<'gc>(activation: &mut Activation<'_, 'gc, '_>, val: &AmfValue) -> Value<'gc> {
match val {
AmfValue::Null => Value::Null,
AmfValue::Undefined => Value::Undefined,
AmfValue::Number(f) => (*f).into(),
AmfValue::String(s) => Value::String(AvmString::new_utf8(activation.context.gc_context, s)),
AmfValue::Bool(b) => (*b).into(),
AmfValue::ECMAArray(_, associative, len) => {
let array_constructor = activation.context.avm1.prototypes.array_constructor;
if let Ok(Value::Object(obj)) =
array_constructor.construct(activation, &[(*len).into()])
{
for entry in associative {
let value = deserialize_value(activation, entry.value());
if let Ok(i) = entry.name().parse::<i32>() {
obj.set_element(activation, i, value).unwrap();
} else {
obj.define_value(
activation.context.gc_context,
AvmString::new_utf8(activation.context.gc_context, &entry.name),
value,
Attribute::empty(),
);
}
}
obj.into()
} else {
Value::Undefined
}
}
AmfValue::Object(elements, _) => {
// Deserialize Object
let obj = ScriptObject::object(
activation.context.gc_context,
Some(activation.context.avm1.prototypes.object),
);
for entry in elements {
let value = deserialize_value(activation, entry.value());
let name = AvmString::new_utf8(activation.context.gc_context, &entry.name);
obj.define_value(
activation.context.gc_context,
name,
value,
Attribute::empty(),
);
}
obj.into()
}
AmfValue::Date(time, _) => {
let date_proto = activation.context.avm1.prototypes.date_constructor;
if let Ok(Value::Object(obj)) = date_proto.construct(activation, &[(*time).into()]) {
Value::Object(obj)
} else {
Value::Undefined
}
}
AmfValue::XML(content, _) => {
let xml_proto = activation.context.avm1.prototypes.xml_constructor;
if let Ok(Value::Object(obj)) = xml_proto.construct(
activation,
&[Value::String(AvmString::new_utf8(
activation.context.gc_context,
content,
))],
) {
Value::Object(obj)
} else {
Value::Undefined
}
}
_ => Value::Undefined,
}
}
/// Deserializes a Lso into an object containing the properties stored
fn deserialize_lso<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
lso: &Lso,
) -> Result<Object<'gc>, Error<'gc>> {
let obj = ScriptObject::object(
activation.context.gc_context,
Some(activation.context.avm1.prototypes.object),
);
for child in &lso.body {
obj.define_value(
activation.context.gc_context,
AvmString::new_utf8(activation.context.gc_context, &child.name),
deserialize_value(activation, child.value()),
Attribute::empty(),
);
}
Ok(obj.into())
}
/// Deserialize a Json shared object element into a Value
fn recursive_deserialize_json<'gc>(
json_value: JsonValue,
activation: &mut Activation<'_, 'gc, '_>,
) -> Value<'gc> {
match json_value {
JsonValue::Null => Value::Null,
JsonValue::Short(s) => Value::String(AvmString::new_utf8(
activation.context.gc_context,
s.to_string(),
)),
JsonValue::String(s) => {
Value::String(AvmString::new_utf8(activation.context.gc_context, s))
}
JsonValue::Number(f) => Value::Number(f.into()),
JsonValue::Boolean(b) => b.into(),
JsonValue::Object(o) => {
if o.get("__proto__").and_then(JsonValue::as_str) == Some("Array") {
deserialize_array_json(o, activation)
} else {
deserialize_object_json(o, activation)
}
}
JsonValue::Array(_) => Value::Undefined,
}
}
/// Deserialize an Object and any children from a JSON object
fn deserialize_object_json<'gc>(
json_obj: json::object::Object,
activation: &mut Activation<'_, 'gc, '_>,
) -> Value<'gc> {
// Deserialize Object
let obj = ScriptObject::object(
activation.context.gc_context,
Some(activation.context.avm1.prototypes.object),
);
for entry in json_obj.iter() {
let value = recursive_deserialize_json(entry.1.clone(), activation);
let name = AvmString::new_utf8(activation.context.gc_context, entry.0);
obj.define_value(
activation.context.gc_context,
name,
value,
Attribute::empty(),
);
}
obj.into()
}
/// Deserialize an Array and any children from a JSON object
fn deserialize_array_json<'gc>(
mut json_obj: json::object::Object,
activation: &mut Activation<'_, 'gc, '_>,
) -> Value<'gc> {
let array_constructor = activation.context.avm1.prototypes.array_constructor;
let len = json_obj
.get("length")
.and_then(JsonValue::as_i32)
.unwrap_or_default();
if let Ok(Value::Object(obj)) = array_constructor.construct(activation, &[len.into()]) {
// Remove length and proto meta-properties.
json_obj.remove("length");
json_obj.remove("__proto__");
for entry in json_obj.iter() {
let value = recursive_deserialize_json(entry.1.clone(), activation);
if let Ok(i) = entry.0.parse::<i32>() {
obj.set_element(activation, i, value).unwrap();
} else {
let name = AvmString::new_utf8(activation.context.gc_context, entry.0);
obj.define_value(
activation.context.gc_context,
name,
value,
Attribute::empty(),
);
}
}
obj.into()
} else {
Value::Undefined
}
}
pub fn get_local<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
// TODO: It appears that Flash does some kind of escaping here:
// the name "foo\uD800" correspond to a file named "fooE#FB#FB#D.sol".
let name = args
.get(0)
.unwrap_or(&Value::Undefined)
.coerce_to_string(activation)?;
let name = name.to_utf8_lossy();
const INVALID_CHARS: &str = "~%&\\;:\"',<>?# ";
if name.contains(|c| INVALID_CHARS.contains(c)) {
log::error!("SharedObject::get_local: Invalid character in name");
return Ok(Value::Null);
}
let movie = if let Some(movie) = activation.base_clip().movie() {
movie
} else {
log::error!("SharedObject::get_local: Movie was None");
return Ok(Value::Null);
};
let mut movie_url = if let Some(url) = movie.url() {
if let Ok(url) = url::Url::parse(url) {
url
} else {
log::error!("SharedObject::get_local: Unable to parse movie URL");
return Ok(Value::Null);
}
} else {
// No URL (loading local data). Use a dummy URL to allow SharedObjects to work.
url::Url::parse("file://localhost").unwrap()
};
movie_url.set_query(None);
movie_url.set_fragment(None);
let secure = args
.get(2)
.unwrap_or(&Value::Undefined)
.as_bool(activation.swf_version());
// Secure parameter disallows using the shared object from non-HTTPS.
if secure && movie_url.scheme() != "https" {
log::warn!(
"SharedObject.get_local: Tried to load a secure shared object from non-HTTPS origin"
);
return Ok(Value::Null);
}
// Shared objects are sandboxed per-domain.
// By default, they are keyed based on the SWF URL, but the `localHost` parameter can modify this path.
let mut movie_path = movie_url.path();
// Remove leading/trailing slashes.
movie_path = movie_path.strip_prefix('/').unwrap_or(movie_path);
movie_path = movie_path.strip_suffix('/').unwrap_or(movie_path);
let movie_host = if movie_url.scheme() == "file" {
// Remove drive letter on Windows (TODO: move this logic into DiskStorageBackend?)
if let [_, b':', b'/', ..] = movie_path.as_bytes() {
movie_path = &movie_path[3..];
}
"localhost"
} else {
movie_url.host_str().unwrap_or_default()
};
let local_path = if let Some(Value::String(local_path)) = args.get(1) {
// Empty local path always fails.
if local_path.is_empty() {
return Ok(Value::Null);
}
// Remove leading/trailing slashes.
let mut local_path = local_path.to_utf8_lossy();
if local_path.ends_with('/') {
match &mut local_path {
Cow::Owned(p) => {
p.pop();
}
Cow::Borrowed(p) => *p = &p[..p.len() - 1],
}
}
if local_path.starts_with('/') {
match &mut local_path {
Cow::Owned(p) => {
p.remove(0);
}
Cow::Borrowed(p) => *p = &p[1..],
}
}
// Verify that local_path is a prefix of the SWF path.
if movie_path.starts_with(local_path.as_ref())
&& (local_path.is_empty()
|| movie_path.len() == local_path.len()
|| movie_path[local_path.len()..].starts_with('/'))
{
local_path
} else {
log::warn!("SharedObject.get_local: localPath parameter does not match SWF path");
return Ok(Value::Null);
}
} else {
Cow::Borrowed(movie_path)
};
// Final SO path: foo.com/folder/game.swf/SOName
// SOName may be a path containing slashes. In this case, prefix with # to mimic Flash Player behavior.
let prefix = if name.contains('/') { "#" } else { "" };
let full_name = format!("{}/{}/{}{}", movie_host, local_path, prefix, name);
// Avoid any paths with `..` to prevent SWFs from crawling the file system on desktop.
// Flash will generally fail to save shared objects with a path component starting with `.`,
// so let's disallow them altogether.
if full_name.split('/').any(|s| s.starts_with('.')) {
log::error!("SharedObject.get_local: Invalid path with .. segments");
return Ok(Value::Null);
}
// Check if this is referencing an existing shared object
if let Some(so) = activation.context.shared_objects.get(&full_name) {
return Ok((*so).into());
}
// Data property only should exist when created with getLocal/Remote
let constructor = activation.context.avm1.prototypes.shared_object_constructor;
let this = constructor
.construct(activation, &[])?
.coerce_to_object(activation);
// Set the internal name
let obj_so = this.as_shared_object().unwrap();
obj_so.set_name(activation.context.gc_context, full_name.clone());
let mut data = Value::Undefined;
// Load the data object from storage if it existed prior
if let Some(saved) = activation.context.storage.get(&full_name) {
// Attempt to load it as an Lso
if let Ok(lso) = flash_lso::read::Reader::default().parse(&saved) {
data = deserialize_lso(activation, &lso)?.into();
} else {
// Attempt to load legacy Json
if let Ok(saved_string) = String::from_utf8(saved) {
if let Ok(json_data) = json::parse(&saved_string) {
data = recursive_deserialize_json(json_data, activation);
}
}
}
}
if data == Value::Undefined {
// No data; create a fresh data object.
data = ScriptObject::object(
activation.context.gc_context,
Some(activation.context.avm1.prototypes.object),
)
.into();
}
this.define_value(
activation.context.gc_context,
"data",
data,
Attribute::DONT_DELETE,
);
activation.context.shared_objects.insert(full_name, this);
Ok(this.into())
}
pub fn get_remote<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.getRemote() not implemented");
Ok(Value::Undefined)
}
pub fn get_max_size<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.getMaxSize() not implemented");
Ok(Value::Undefined)
}
pub fn add_listener<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.addListener() not implemented");
Ok(Value::Undefined)
}
pub fn remove_listener<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.removeListener() not implemented");
Ok(Value::Undefined)
}
pub fn create_shared_object_object<'gc>(
gc_context: MutationContext<'gc, '_>,
shared_object_proto: Object<'gc>,
fn_proto: Object<'gc>,
) -> Object<'gc> {
let shared_obj = FunctionObject::constructor(
gc_context,
Executable::Native(constructor),
constructor_to_fn!(constructor),
Some(fn_proto),
shared_object_proto,
);
let object = shared_obj.as_script_object().unwrap();
define_properties_on(OBJECT_DECLS, gc_context, object, fn_proto);
shared_obj
}
pub fn clear<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
let data = this.get("data", activation)?.coerce_to_object(activation);
for k in &data.get_keys(activation) {
data.delete(activation, *k);
}
let so = this.as_shared_object().unwrap();
let name = so.get_name();
activation.context.storage.remove_key(&name);
Ok(Value::Undefined)
}
pub fn close<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.close() not implemented");
Ok(Value::Undefined)
}
pub fn connect<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.connect() not implemented");
Ok(Value::Undefined)
}
pub fn flush<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
let data = this.get("data", activation)?.coerce_to_object(activation);
let this_obj = this.as_shared_object().unwrap();
let name = this_obj.get_name();
let mut elements = Vec::new();
recursive_serialize(activation, data, &mut elements);
let mut lso = Lso::new(
elements,
&name
.split('/')
.last()
.map(|e| e.to_string())
.unwrap_or_else(|| "<unknown>".to_string()),
AMFVersion::AMF0,
);
let bytes = flash_lso::write::write_to_bytes(&mut lso).unwrap_or_default();
Ok(activation.context.storage.put(&name, &bytes).into())
}
pub fn get_size<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.getSize() not implemented");
Ok(Value::Undefined)
}
pub fn send<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.send() not implemented");
Ok(Value::Undefined)
}
pub fn set_fps<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.setFps() not implemented");
Ok(Value::Undefined)
}
pub fn on_status<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.onStatus() not implemented");
Ok(Value::Undefined)
}
pub fn on_sync<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
_this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
avm_warn!(activation, "SharedObject.onSync() not implemented");
Ok(Value::Undefined)
}
pub fn create_proto<'gc>(
gc_context: MutationContext<'gc, '_>,
proto: Object<'gc>,
fn_proto: Object<'gc>,
) -> Object<'gc> {
let shared_obj = SharedObject::empty_shared_obj(gc_context, Some(proto));
let object = shared_obj.as_script_object().unwrap();
define_properties_on(PROTO_DECLS, gc_context, object, fn_proto);
shared_obj.into()
}
pub fn constructor<'gc>(
_activation: &mut Activation<'_, 'gc, '_>,
this: Object<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
Ok(this.into())
}
| 33.462935 | 107 | 0.578281 |
f7524033633a65466bcd142a228b666d0364c3ca | 1,511 | use std::{fs, net::SocketAddr, path::Path};
use anyhow::Result;
use http::Uri;
use serde::{de, Deserialize};
#[derive(Deserialize)]
pub struct Configuration {
/// Configuration for the Matrix server.
pub matrix: MatrixConfig,
/// Configuration for the HTTP API.
pub api: ApiConfig,
/// Configuration for the backend
pub backend: BackendConfig,
}
#[derive(Deserialize)]
pub struct MatrixConfig {
/// The bot's homeserver.
#[serde(deserialize_with = "deserialize_uri")]
pub homeserver: Uri,
/// The bot's account name.
pub user: String,
/// The bot's password.
pub password: String,
/// List of Matrix accounts with admin privileges for this bot.
pub admins: Vec<String>,
}
#[derive(Deserialize)]
pub struct ApiConfig {
/// The host and port to listen on.
pub listen: SocketAddr,
/// The API secret.
pub secret: String,
}
#[derive(Deserialize)]
pub struct BackendConfig {
pub host: String,
pub integrations_endpoint: Option<String>,
pub user: String,
pub password: String,
}
/// Read the configuration from the provided file.
pub fn parse<P: AsRef<Path>>(file: P) -> Result<Configuration> {
let content = fs::read_to_string(file)?;
let cfg = toml::from_str(&content)?;
Ok(cfg)
}
fn deserialize_uri<'de, D>(deserializer: D) -> Result<Uri, D::Error>
where
D: de::Deserializer<'de>,
{
let uri: &str = de::Deserialize::deserialize(deserializer)?;
uri.parse().map_err(de::Error::custom)
}
| 22.893939 | 68 | 0.663137 |
ebab8538c5ef0511c9e69aeaf0035aee63342b58 | 6,801 | use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService};
use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap};
use crate::config::ClientConfig;
use block_proposer::{test_utils::LocalSigner, BlockProducer};
use bls::Keypair;
use clap::{App, Arg};
use grpcio::{ChannelBuilder, EnvBuilder};
use protos::services_grpc::{BeaconBlockServiceClient, ValidatorServiceClient};
use slog::{error, info, o, Drain};
use slot_clock::SystemTimeSlotClock;
use std::path::PathBuf;
use std::sync::Arc;
use std::thread;
use types::ChainSpec;
mod block_producer_service;
mod config;
mod duties;
fn main() {
// Logging
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::CompactFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let log = slog::Logger::root(drain, o!());
// CLI
let matches = App::new("Lighthouse Validator Client")
.version("0.0.1")
.author("Sigma Prime <[email protected]>")
.about("Eth 2.0 Validator Client")
.arg(
Arg::with_name("datadir")
.long("datadir")
.value_name("DIR")
.help("Data directory for keys and databases.")
.takes_value(true),
)
.arg(
Arg::with_name("server")
.long("server")
.value_name("server")
.help("Address to connect to BeaconNode.")
.takes_value(true),
)
.arg(
Arg::with_name("spec")
.long("spec")
.value_name("spec")
.short("s")
.help("Configuration of Beacon Chain")
.takes_value(true)
.possible_values(&["foundation", "few_validators"])
.default_value("foundation"),
)
.get_matches();
let mut config = ClientConfig::default();
// Custom datadir
if let Some(dir) = matches.value_of("datadir") {
config.data_dir = PathBuf::from(dir.to_string());
}
// Custom server port
if let Some(server_str) = matches.value_of("server") {
if let Ok(addr) = server_str.parse::<u16>() {
config.server = addr.to_string();
} else {
error!(log, "Invalid address"; "server" => server_str);
return;
}
}
// TODO: Permit loading a custom spec from file.
// Custom spec
if let Some(spec_str) = matches.value_of("spec") {
match spec_str {
"foundation" => config.spec = ChainSpec::foundation(),
"few_validators" => config.spec = ChainSpec::few_validators(),
// Should be impossible due to clap's `possible_values(..)` function.
_ => unreachable!(),
};
}
// Log configuration
info!(log, "";
"data_dir" => &config.data_dir.to_str(),
"server" => &config.server);
// Beacon node gRPC beacon block endpoints.
let beacon_block_grpc_client = {
let env = Arc::new(EnvBuilder::new().build());
let ch = ChannelBuilder::new(env).connect(&config.server);
Arc::new(BeaconBlockServiceClient::new(ch))
};
// Beacon node gRPC validator endpoints.
let validator_grpc_client = {
let env = Arc::new(EnvBuilder::new().build());
let ch = ChannelBuilder::new(env).connect(&config.server);
Arc::new(ValidatorServiceClient::new(ch))
};
// Spec
let spec = Arc::new(config.spec.clone());
// Clock for determining the present slot.
// TODO: this shouldn't be a static time, instead it should be pulled from the beacon node.
// https://github.com/sigp/lighthouse/issues/160
let genesis_time = 1_549_935_547;
let slot_clock = {
info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time);
let clock = SystemTimeSlotClock::new(genesis_time, spec.seconds_per_slot)
.expect("Unable to instantiate SystemTimeSlotClock.");
Arc::new(clock)
};
let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision.
info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis);
/*
* Start threads.
*/
let mut threads = vec![];
// TODO: keypairs are randomly generated; they should be loaded from a file or generated.
// https://github.com/sigp/lighthouse/issues/160
let keypairs = vec![Keypair::random()];
for keypair in keypairs {
info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id());
let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch));
// Spawn a new thread to maintain the validator's `EpochDuties`.
let duties_manager_thread = {
let spec = spec.clone();
let duties_map = duties_map.clone();
let slot_clock = slot_clock.clone();
let log = log.clone();
let beacon_node = validator_grpc_client.clone();
let pubkey = keypair.pk.clone();
thread::spawn(move || {
let manager = DutiesManager {
duties_map,
pubkey,
spec,
slot_clock,
beacon_node,
};
let mut duties_manager_service = DutiesManagerService {
manager,
poll_interval_millis,
log,
};
duties_manager_service.run();
})
};
// Spawn a new thread to perform block production for the validator.
let producer_thread = {
let spec = spec.clone();
let signer = Arc::new(LocalSigner::new(keypair.clone()));
let duties_map = duties_map.clone();
let slot_clock = slot_clock.clone();
let log = log.clone();
let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone()));
thread::spawn(move || {
let block_producer =
BlockProducer::new(spec, duties_map, slot_clock, client, signer);
let mut block_producer_service = BlockProducerService {
block_producer,
poll_interval_millis,
log,
};
block_producer_service.run();
})
};
threads.push((duties_manager_thread, producer_thread));
}
// Naively wait for all the threads to complete.
for tuple in threads {
let (manager, producer) = tuple;
let _ = producer.join();
let _ = manager.join();
}
}
| 35.60733 | 124 | 0.575945 |
dd683eb86c32ac3c9a704cceb5654facfa83f8ee | 560 | #[allow(dead_code)]
mod opt {
include!("src/opt.rs");
}
use clap::IntoApp;
use clap_generate::generators::{Bash, Fish, Zsh};
fn main() {
let mut app = opt::Opt::into_app();
let name = app.get_name().to_string();
let outdir = match std::env::var_os("OUT_DIR") {
None => return,
Some(outdir) => outdir,
};
clap_generate::generate_to::<Bash, _, _>(&mut app, &name, &outdir);
clap_generate::generate_to::<Zsh, _, _>(&mut app, &name, &outdir);
clap_generate::generate_to::<Fish, _, _>(&mut app, &name, &outdir);
}
| 26.666667 | 71 | 0.603571 |
696eeaa337369dd70340f300d0ff92d4744a48d2 | 1,384 | use std::io;
use al_type;
use decode;
use reader::Reader;
use util;
use super::rustc_serialize::json;
#[derive(RustcDecodable, RustcEncodable)]
pub struct AssetInfo {
hash: [String; 2],
asset_type: u8,
file_size: u32,
filename: String,
}
pub fn gen_file_info(path: &str) -> io::Result<()> {
let mut data = try!(util::read_file(path));
decode::decode_file_list(&mut data);
let content = String::from_utf8(data).unwrap();
let mut arr = Vec::new();
for line in content.split_whitespace() {
let fields: Vec<&str> = line.split(',').collect();
arr.push(AssetInfo {
hash: [fields[0].to_string(), fields[1].to_string()],
asset_type: fields[2].parse().unwrap(),
file_size: fields[3].parse().unwrap(),
filename: fields[4].to_string(),
});
}
try!(util::write_str("generated/asset.json", json::encode(&arr).unwrap()));
Ok(())
}
pub fn decode_file(path: &str, filename: &str) -> io::Result<()> {
let data = try!(util::read_file(path));
let mut reader = Reader::create(&data);
let file_type = reader.read_chars(4);
match file_type.as_ref() {
"ALLZ" => {
al_type::allz::decode(reader, filename);
}
other => println!("Unrecognizable file type {}", other),
}
Ok(())
}
| 27.137255 | 79 | 0.570809 |
6a858d3c9b379f82750f9262920a40d610931e99 | 1,235 | extern crate libc;
use std::sync::{Once, ONCE_INIT};
pub mod db;
pub mod engine;
mod error;
mod ffi;
pub mod scan_settings;
pub mod version;
pub use error::ClamError;
/// Initializes clamav
///
/// This must be called once per process. This is safe to call multiple times.
pub fn initialize() -> Result<(), ClamError> {
// the cl_init implementation isn't thread-safe, which is painful for tests
static ONCE: Once = ONCE_INIT;
static mut RESULT: ffi::cl_error = ffi::cl_error::CL_SUCCESS;
unsafe {
ONCE.call_once(|| {
RESULT = ffi::cl_init(ffi::CL_INIT_DEFAULT);
// this function always returns OK
if RESULT == ffi::cl_error::CL_SUCCESS {
ffi::cl_initialize_crypto();
libc::atexit(cleanup);
}
});
extern "C" fn cleanup() {
unsafe {
ffi::cl_cleanup_crypto();
}
}
match RESULT {
ffi::cl_error::CL_SUCCESS => Ok(()),
_ => Err(ClamError::new(RESULT)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initialize_success() {
assert!(initialize().is_ok(), "initialize should succeed");
}
}
| 23.301887 | 79 | 0.565182 |
76cf3c1149dd552e8665965cabeb1d2b0e3f921b | 5,721 | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-windows failing on win32 bot
// ignore-tidy-linelength
// ignore-lldb
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-use-pretty-printer
// This test uses some GDB Python API features (e.g. accessing anonymous fields)
// which are only available in newer GDB version. The following directive will
// case the test runner to ignore this test if an older GDB version is used:
// min-gdb-version 7.7
// gdb-command: run
// gdb-command: print regular_struct
// gdb-check:$1 = RegularStruct = {the_first_field = 101, the_second_field = 102.5, the_third_field = false, the_fourth_field = "I'm so pretty, oh so pretty..."}
// gdb-command: print tuple
// gdb-check:$2 = {true, 103, "blub"}
// gdb-command: print tuple_struct
// gdb-check:$3 = TupleStruct = {-104.5, 105}
// gdb-command: print empty_struct
// gdb-check:$4 = EmptyStruct
// gdb-command: print c_style_enum1
// gdb-check:$5 = CStyleEnumVar1
// gdb-command: print c_style_enum2
// gdb-check:$6 = CStyleEnumVar2
// gdb-command: print c_style_enum3
// gdb-check:$7 = CStyleEnumVar3
// gdb-command: print mixed_enum_c_style_var
// gdb-check:$8 = MixedEnumCStyleVar
// gdb-command: print mixed_enum_tuple_var
// gdb-check:$9 = MixedEnumTupleVar = {106, 107, false}
// gdb-command: print mixed_enum_struct_var
// gdb-check:$10 = MixedEnumStructVar = {field1 = 108.5, field2 = 109}
// gdb-command: print some
// gdb-check:$11 = Some = {110}
// gdb-command: print none
// gdb-check:$12 = None
// gdb-command: print some_fat
// gdb-check:$13 = Some = {"abc"}
// gdb-command: print none_fat
// gdb-check:$14 = None
// gdb-command: print nested_variant1
// gdb-check:$15 = NestedVariant1 = {NestedStruct = {regular_struct = RegularStruct = {the_first_field = 111, the_second_field = 112.5, the_third_field = true, the_fourth_field = "NestedStructString1"}, tuple_struct = TupleStruct = {113.5, 114}, empty_struct = EmptyStruct, c_style_enum = CStyleEnumVar2, mixed_enum = MixedEnumTupleVar = {115, 116, false}}}
// gdb-command: print nested_variant2
// gdb-check:$16 = NestedVariant2 = {abc = NestedStruct = {regular_struct = RegularStruct = {the_first_field = 117, the_second_field = 118.5, the_third_field = false, the_fourth_field = "NestedStructString10"}, tuple_struct = TupleStruct = {119.5, 120}, empty_struct = EmptyStruct, c_style_enum = CStyleEnumVar3, mixed_enum = MixedEnumStructVar = {field1 = 121.5, field2 = -122}}}
use self::CStyleEnum::{CStyleEnumVar1, CStyleEnumVar2, CStyleEnumVar3};
use self::MixedEnum::{MixedEnumCStyleVar, MixedEnumTupleVar, MixedEnumStructVar};
use self::NestedEnum::{NestedVariant1, NestedVariant2};
struct RegularStruct {
the_first_field: int,
the_second_field: f64,
the_third_field: bool,
the_fourth_field: &'static str,
}
struct TupleStruct(f64, i16);
struct EmptyStruct;
enum CStyleEnum {
CStyleEnumVar1,
CStyleEnumVar2,
CStyleEnumVar3,
}
enum MixedEnum {
MixedEnumCStyleVar,
MixedEnumTupleVar(u32, u16, bool),
MixedEnumStructVar { field1: f64, field2: i32 }
}
struct NestedStruct {
regular_struct: RegularStruct,
tuple_struct: TupleStruct,
empty_struct: EmptyStruct,
c_style_enum: CStyleEnum,
mixed_enum: MixedEnum,
}
enum NestedEnum {
NestedVariant1(NestedStruct),
NestedVariant2 { abc: NestedStruct }
}
fn main() {
let regular_struct = RegularStruct {
the_first_field: 101,
the_second_field: 102.5,
the_third_field: false,
the_fourth_field: "I'm so pretty, oh so pretty..."
};
let tuple = ( true, 103u32, "blub" );
let tuple_struct = TupleStruct(-104.5, 105);
let empty_struct = EmptyStruct;
let c_style_enum1 = CStyleEnumVar1;
let c_style_enum2 = CStyleEnumVar2;
let c_style_enum3 = CStyleEnumVar3;
let mixed_enum_c_style_var = MixedEnumCStyleVar;
let mixed_enum_tuple_var = MixedEnumTupleVar(106, 107, false);
let mixed_enum_struct_var = MixedEnumStructVar { field1: 108.5, field2: 109 };
let some = Some(110u);
let none: Option<int> = None;
let some_fat = Some("abc");
let none_fat: Option<&'static str> = None;
let nested_variant1 = NestedVariant1(
NestedStruct {
regular_struct: RegularStruct {
the_first_field: 111,
the_second_field: 112.5,
the_third_field: true,
the_fourth_field: "NestedStructString1",
},
tuple_struct: TupleStruct(113.5, 114),
empty_struct: EmptyStruct,
c_style_enum: CStyleEnumVar2,
mixed_enum: MixedEnumTupleVar(115, 116, false)
}
);
let nested_variant2 = NestedVariant2 {
abc: NestedStruct {
regular_struct: RegularStruct {
the_first_field: 117,
the_second_field: 118.5,
the_third_field: false,
the_fourth_field: "NestedStructString10",
},
tuple_struct: TupleStruct(119.5, 120),
empty_struct: EmptyStruct,
c_style_enum: CStyleEnumVar3,
mixed_enum: MixedEnumStructVar {
field1: 121.5,
field2: -122
}
}
};
zzz(); // #break
}
fn zzz() { () }
| 32.140449 | 380 | 0.679951 |
4a4d6ecc4d65fdab9b5b70cad4408e2717c3a9fe | 1,356 | use super::ptr_j::*;
use super::result::ToJniResult;
use crate::panic::{handle_exception_result, ToResult};
use crate::ptr::RPtrRepresentable;
use jni::objects::{JObject};
use jni::sys::{jbyteArray, jobject};
use jni::JNIEnv;
use cardano_serialization_lib::crypto::{Ed25519KeyHash};
// cddl_lib: (&self) -> Vec<u8>
#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "C" fn Java_io_emurgo_rnhaskellshelley_Native_ed25519KeyHashToBytes(
env: JNIEnv, _: JObject, ed25519_key_hash: JRPtr
) -> jobject {
handle_exception_result(|| {
let ed25519_key_hash = ed25519_key_hash.rptr(&env)?;
ed25519_key_hash
.typed_ref::<Ed25519KeyHash>()
.map(|ed25519_key_hash| ed25519_key_hash.to_bytes())
.and_then(|bytes| env.byte_array_from_slice(&bytes).into_result())
.map(|arr| JObject::from(arr))
})
.jresult(&env)
}
// cddl_lib: from_bytes(Vec<u8>) -> Result<Address, JsValue>
#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "C" fn Java_io_emurgo_rnhaskellshelley_Native_ed25519KeyHashFromBytes(
env: JNIEnv, _: JObject, bytes: jbyteArray
) -> jobject {
handle_exception_result(|| {
env
.convert_byte_array(bytes)
.into_result()
.and_then(|bytes| Ed25519KeyHash::from_bytes(bytes).into_result())
.and_then(|ed25519_key_hash| ed25519_key_hash.rptr().jptr(&env))
})
.jresult(&env)
}
| 32.285714 | 88 | 0.721239 |
f71d754cd70124e42b3ed775f08eb818bb480556 | 10,067 | // Copyright (c) 2021 Shreepad Shukla
// SPDX-License-Identifier: MIT
#[derive(Debug, Clone, PartialEq)]
pub struct Packet {
version: u8,
type_id: u8,
lit_value: Option<u64>,
op_mode: Option<u8>,
op_sub_packets_length: Option<usize>,
op_sub_packets_count: Option<u32>,
op_sub_packets: Option<Vec<Packet>>,
}
impl Packet {
pub fn new(hex_str: String) -> Packet {
let mut packet = Packet {
version: 0,
type_id: 0,
lit_value: None,
op_mode: None,
op_sub_packets_length: None,
op_sub_packets_count: None,
op_sub_packets: None,
};
let binary_str = Self::hex_to_binary_str(hex_str);
let mut posn = 0usize;
Self::fill_packet(&mut packet, &binary_str, &mut posn);
packet
}
fn fill_packet(packet: &mut Packet, binary_str: &String, posn: &mut usize) {
// version - 3 bits
packet.version =
u8::from_str_radix(&binary_str[*posn..*posn + 3], 2).expect("Invalid version");
*posn += 3;
// type_id - 3 bits
packet.type_id =
u8::from_str_radix(&binary_str[*posn..*posn + 3], 2).expect("Invalid type id");
*posn += 3;
if packet.type_id == 4 {
// literal
let mut reached_end = false;
let mut literal_str = String::new();
while !reached_end {
// Check leading digit for end (0)
if binary_str[*posn..*posn + 1].starts_with("0") {
reached_end = true;
}
*posn += 1;
// Collect 4 bits of literal
literal_str.push_str(&binary_str[*posn..*posn + 4]);
*posn += 4;
}
packet.lit_value = Some(u64::from_str_radix(&literal_str, 2).expect("Invalid literal"));
}
// end literal
else {
// operator
let mut sub_packets: Vec<Packet> = Vec::new();
// Check leading digit for mode (0)
if binary_str[*posn..*posn + 1].starts_with("0") {
packet.op_mode = Some(0);
*posn += 1;
// Sub-packet length - 15 bits
packet.op_sub_packets_length = Some(
usize::from_str_radix(&binary_str[*posn..*posn + 15], 2)
.expect("Invalid sp length"),
);
*posn += 15;
let current_posn: usize = *posn;
while *posn < current_posn + packet.op_sub_packets_length.unwrap() {
let mut sub_packet = Packet {
version: 0,
type_id: 0,
lit_value: None,
op_mode: None,
op_sub_packets_length: None,
op_sub_packets_count: None,
op_sub_packets: None,
};
Self::fill_packet(&mut sub_packet, binary_str, posn);
sub_packets.push(sub_packet);
}
}
// end mode 0
else {
packet.op_mode = Some(1);
*posn += 1;
// Sub-packet count - 11 bits
packet.op_sub_packets_count = Some(
u32::from_str_radix(&binary_str[*posn..*posn + 11], 2)
.expect("Invalid sp count"),
);
*posn += 11;
// collect packets recursively
for _ in 1..=packet.op_sub_packets_count.unwrap() {
let mut sub_packet = Packet {
version: 0,
type_id: 0,
lit_value: None,
op_mode: None,
op_sub_packets_length: None,
op_sub_packets_count: None,
op_sub_packets: None,
};
Self::fill_packet(&mut sub_packet, binary_str, posn);
sub_packets.push(sub_packet);
}
} // end mode 1
packet.op_sub_packets = Some(sub_packets);
} // end operator
//println!("Filled packet: {:?}", packet);
}
fn hex_to_binary_str(hex_str: String) -> String {
let mut binary_str = String::with_capacity(6000);
for hex_char in hex_str.trim().chars() {
let hex_value = hex_char.to_digit(16).unwrap();
binary_str.push_str(&format!("{:04b}", hex_value));
}
binary_str
}
pub fn version_sum(&self) -> u32 {
let mut sum = 0u32;
sum += self.version as u32;
if self.op_sub_packets == None {
return sum;
}
for sub_packet in self.op_sub_packets.as_ref().unwrap().iter() {
sum += sub_packet.version_sum();
}
sum
}
pub fn value(&self) -> u64 {
match self.type_id {
0 => self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64)
.sum(),
1 => self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64)
.product(),
2 => self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64)
.min()
.unwrap(),
3 => self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64)
.max()
.unwrap(),
4 => self.lit_value.unwrap(),
5 => {
// gt
let mut iter_gt = self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64);
if iter_gt.next().unwrap() > iter_gt.next().unwrap() {
1
} else {
0
}
}
6 => {
//lt
let mut iter_gt = self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64);
if iter_gt.next().unwrap() < iter_gt.next().unwrap() {
1
} else {
0
}
}
7 => {
//eq
let mut iter_gt = self
.op_sub_packets
.as_ref()
.unwrap()
.iter()
.map(|packet| packet.value() as u64);
if iter_gt.next().unwrap() == iter_gt.next().unwrap() {
1
} else {
0
}
}
_ => 0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packet_literal() {
let result = Packet::new("D2FE28".to_string());
println!("Literal packet: {:?}", result);
assert_eq!(6, result.version_sum()); // fail to print
}
#[test]
fn packet_operator_mode1() {
let result = Packet::new("EE00D40C823060".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(14, result.version_sum()); // fail to print
}
#[test]
fn packet_operator_mode0() {
let result = Packet::new("38006F45291200".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(9, result.version_sum()); // fail to print
}
#[test]
fn packet_3nestedoperator_lit() {
let result = Packet::new("8A004A801A8002F478".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(16, result.version_sum()); // fail to print
}
#[test]
fn packet_3nestedoperator_5lit() {
let result = Packet::new("A0016C880162017C3686B18A3D4780".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(31, result.version_sum()); // fail to print
}
#[test]
fn packet_sum_2lit() {
let result = Packet::new("C200B40A82".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(3, result.value()); // fail to print
}
#[test]
fn packet_min_3lit() {
let result = Packet::new("880086C3E88112".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(7, result.value()); // fail to print
}
#[test]
fn packet_max_3lit() {
let result = Packet::new("CE00C43D881120".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(9, result.value()); // fail to print
}
#[test]
fn packet_gt_2lit() {
let result = Packet::new("F600BC2D8F".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(0, result.value()); // fail to print
}
#[test]
fn packet_lt_2lit() {
let result = Packet::new("D8005AC2A8F0".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(1, result.value()); // fail to print
}
#[test]
fn packet_eq_2lit() {
let result = Packet::new("9C005AC2F8F0".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(0, result.value()); // fail to print
}
#[test]
fn packet_eq_sumprod_2lits() {
let result = Packet::new("9C0141080250320F1802104A08".to_string());
println!("Operator packet: {:?}", result);
assert_eq!(1, result.value()); // fail to print
}
}
| 30.231231 | 100 | 0.459124 |
6abc39c16741e1987bcd1a485ef0b26668c080b2 | 13,696 | /*!
[XTS block mode](https://en.wikipedia.org/wiki/Disk_encryption_theory#XEX-based_tweaked-codebook_mode_with_ciphertext_stealing_(XTS)) implementation in Rust.
Currently this implementation supports only ciphers with 128-bit (16-byte) block size (distinct from key size). Note that AES-256 uses 128-bit blocks, so it works with this crate. If you require other cipher block sizes, please open an issue.
# Examples:
Encrypting and decrypting multiple sectors at a time:
```
use aes::{Aes128, cipher::KeyInit, cipher::generic_array::GenericArray};
use xts_mode::{Xts128, get_tweak_default};
// Load the encryption key
let key = [1; 32];
let plaintext = [5; 0x400];
// Load the data to be encrypted
let mut buffer = plaintext.to_owned();
let cipher_1 = Aes128::new(GenericArray::from_slice(&key[..16]));
let cipher_2 = Aes128::new(GenericArray::from_slice(&key[16..]));
let xts = Xts128::<Aes128>::new(cipher_1, cipher_2);
let sector_size = 0x200;
let first_sector_index = 0;
// Encrypt data in the buffer
xts.encrypt_area(&mut buffer, sector_size, first_sector_index, get_tweak_default);
// Decrypt data in the buffer
xts.decrypt_area(&mut buffer, sector_size, first_sector_index, get_tweak_default);
assert_eq!(&buffer[..], &plaintext[..]);
```
AES-256 works too:
```
use aes::{Aes256, cipher::KeyInit, cipher::generic_array::GenericArray};
use xts_mode::{Xts128, get_tweak_default};
// Load the encryption key
let key = [1; 64];
let plaintext = [5; 0x400];
// Load the data to be encrypted
let mut buffer = plaintext.to_owned();
let cipher_1 = Aes256::new(GenericArray::from_slice(&key[..32]));
let cipher_2 = Aes256::new(GenericArray::from_slice(&key[32..]));
let xts = Xts128::<Aes256>::new(cipher_1, cipher_2);
let sector_size = 0x200;
let first_sector_index = 0;
xts.encrypt_area(&mut buffer, sector_size, first_sector_index, get_tweak_default);
xts.decrypt_area(&mut buffer, sector_size, first_sector_index, get_tweak_default);
assert_eq!(&buffer[..], &plaintext[..]);
```
Encrypting and decrypting a single sector:
```
use aes::{Aes128, cipher::KeyInit, cipher::generic_array::GenericArray};
use xts_mode::{Xts128, get_tweak_default};
// Load the encryption key
let key = [1; 32];
let plaintext = [5; 0x200];
// Load the data to be encrypted
let mut buffer = plaintext.to_owned();
let cipher_1 = Aes128::new(GenericArray::from_slice(&key[..16]));
let cipher_2 = Aes128::new(GenericArray::from_slice(&key[16..]));
let xts = Xts128::<Aes128>::new(cipher_1, cipher_2);
let tweak = get_tweak_default(0); // 0 is the sector index
// Encrypt data in the buffer
xts.encrypt_sector(&mut buffer, tweak);
// Decrypt data in the buffer
xts.decrypt_sector(&mut buffer, tweak);
assert_eq!(&buffer[..], &plaintext[..]);
```
Decrypting a [NCA](https://switchbrew.org/wiki/NCA_Format) (nintendo content archive) header:
```
use aes::{Aes128, cipher::KeyInit, cipher::generic_array::GenericArray};
use xts_mode::{Xts128, get_tweak_default};
pub fn get_nintendo_tweak(sector_index: u128) -> [u8; 0x10] {
sector_index.to_be_bytes()
}
// Load the header key
let header_key = &[0; 0x20];
// Read into buffer header to be decrypted
let mut buffer = vec![0; 0xC00];
let cipher_1 = Aes128::new(GenericArray::from_slice(&header_key[..0x10]));
let cipher_2 = Aes128::new(GenericArray::from_slice(&header_key[0x10..]));
let mut xts = Xts128::new(cipher_1, cipher_2);
// Decrypt the first 0x400 bytes of the header in 0x200 sections
xts.decrypt_area(&mut buffer[0..0x400], 0x200, 0, get_nintendo_tweak);
let magic = &buffer[0x200..0x204];
# if false { // Removed from tests as we're not decrypting an actual NCA
assert_eq!(magic, b"NCA3"); // In older NCA versions the section index used in header encryption was different
# }
// Decrypt the rest of the header
xts.decrypt_area(&mut buffer[0x400..0xC00], 0x200, 2, get_nintendo_tweak);
```
*/
use std::convert::TryFrom;
use std::convert::TryInto;
use byteorder::{ByteOrder, LittleEndian};
use cipher::generic_array::typenum::Unsigned;
use cipher::generic_array::GenericArray;
use cipher::{BlockCipher, BlockDecrypt, BlockEncrypt, BlockSizeUser};
/// Xts128 block cipher. Does not implement implement BlockMode due to XTS differences detailed
/// [here](https://github.com/RustCrypto/block-ciphers/issues/48#issuecomment-574440662).
pub struct Xts128<C: BlockEncrypt + BlockDecrypt + BlockCipher> {
/// This cipher is actually used to encrypt the blocks.
cipher_1: C,
/// This cipher is used only to compute the tweak at each sector start.
cipher_2: C,
}
impl<C: BlockEncrypt + BlockDecrypt + BlockCipher> Xts128<C> {
/// Creates a new Xts128 using two cipher instances: the first one's used to encrypt the blocks
/// and the second one to compute the tweak at the start of each sector.
///
/// Usually both cipher's are the same algorithm and the key is stored as double sized
/// (256 bits for Aes128), and the key is split in half, the first half used for cipher_1 and
/// the other for cipher_2.
///
/// If you require support for different cipher types, or block sizes different than 16 bytes,
/// open an issue.
pub fn new(cipher_1: C, cipher_2: C) -> Xts128<C> {
Xts128 { cipher_1, cipher_2 }
}
/// Encrypts a single sector in place using the given tweak.
///
/// # Panics
/// - If the block size is not 16 bytes.
/// - If there's less than a single block in the sector.
pub fn encrypt_sector(&self, sector: &mut [u8], mut tweak: [u8; 16]) {
assert_eq!(
<C as BlockSizeUser>::BlockSize::to_usize(),
128 / 8,
"Wrong block size"
);
assert!(
sector.len() >= 16,
"AES-XTS needs at least two blocks to perform stealing, or a single complete block"
);
let block_count = sector.len() / 16;
let need_stealing = sector.len() % 16 != 0;
// Compute tweak
self.cipher_2
.encrypt_block(GenericArray::from_mut_slice(&mut tweak));
let nosteal_block_count = if need_stealing {
block_count - 1
} else {
block_count
};
for i in (0..sector.len()).step_by(16).take(nosteal_block_count) {
let block = &mut sector[i..i + 16];
xor(block, &tweak);
self.cipher_1
.encrypt_block(GenericArray::from_mut_slice(block));
xor(block, &tweak);
tweak = galois_field_128_mul_le(tweak);
}
if need_stealing {
let next_to_last_tweak = tweak;
let last_tweak = galois_field_128_mul_le(tweak);
let remaining = sector.len() % 16;
let mut block: [u8; 16] = sector[16 * (block_count - 1)..16 * block_count]
.try_into()
.unwrap();
xor(&mut block, &next_to_last_tweak);
self.cipher_1
.encrypt_block(GenericArray::from_mut_slice(&mut block));
xor(&mut block, &next_to_last_tweak);
let mut last_block = [0u8; 16];
last_block[..remaining].copy_from_slice(§or[16 * block_count..]);
last_block[remaining..].copy_from_slice(&block[remaining..]);
xor(&mut last_block, &last_tweak);
self.cipher_1
.encrypt_block(GenericArray::from_mut_slice(&mut last_block));
xor(&mut last_block, &last_tweak);
sector[16 * (block_count - 1)..16 * block_count].copy_from_slice(&last_block);
sector[16 * block_count..].copy_from_slice(&block[..remaining]);
}
}
/// Decrypts a single sector in place using the given tweak.
///
/// # Panics
/// - If the block size is not 16 bytes.
/// - If there's less than a single block in the sector.
pub fn decrypt_sector(&self, sector: &mut [u8], mut tweak: [u8; 16]) {
assert_eq!(
<C as BlockSizeUser>::BlockSize::to_usize(),
128 / 8,
"Wrong block size"
);
assert!(
sector.len() >= 16,
"AES-XTS needs at least two blocks to perform stealing, or a single complete block"
);
let block_count = sector.len() / 16;
let need_stealing = sector.len() % 16 != 0;
// Compute tweak
self.cipher_2
.encrypt_block(GenericArray::from_mut_slice(&mut tweak));
let nosteal_block_count = if need_stealing {
block_count - 1
} else {
block_count
};
for i in (0..sector.len()).step_by(16).take(nosteal_block_count) {
let block = &mut sector[i..i + 16];
xor(block, &tweak);
self.cipher_1
.decrypt_block(GenericArray::from_mut_slice(block));
xor(block, &tweak);
tweak = galois_field_128_mul_le(tweak);
}
if need_stealing {
let next_to_last_tweak = tweak;
let last_tweak = galois_field_128_mul_le(tweak);
let remaining = sector.len() % 16;
let mut block: [u8; 16] = sector[16 * (block_count - 1)..16 * block_count]
.try_into()
.unwrap();
xor(&mut block, &last_tweak);
self.cipher_1
.decrypt_block(GenericArray::from_mut_slice(&mut block));
xor(&mut block, &last_tweak);
let mut last_block = [0u8; 16];
last_block[..remaining].copy_from_slice(§or[16 * block_count..]);
last_block[remaining..].copy_from_slice(&block[remaining..]);
xor(&mut last_block, &next_to_last_tweak);
self.cipher_1
.decrypt_block(GenericArray::from_mut_slice(&mut last_block));
xor(&mut last_block, &next_to_last_tweak);
sector[16 * (block_count - 1)..16 * block_count].copy_from_slice(&last_block);
sector[16 * block_count..].copy_from_slice(&block[..remaining]);
}
}
/// Encrypts a whole area in place, usually consisting of multiple sectors.
///
/// The tweak is computed at the start of every sector using get_tweak_fn(sector_index).
/// `get_tweak_fn` is usually `get_tweak_default`.
///
/// # Panics
/// - If the block size is not 16 bytes.
/// - If there's less than a single block in the last sector.
pub fn encrypt_area(
&self,
area: &mut [u8],
sector_size: usize,
first_sector_index: u128,
get_tweak_fn: impl Fn(u128) -> [u8; 16],
) {
let area_len = area.len();
let mut chunks = area.chunks_exact_mut(sector_size);
for (i, chunk) in (&mut chunks).enumerate() {
let tweak = get_tweak_fn(
u128::try_from(i).expect("usize cannot be bigger than u128") + first_sector_index,
);
self.encrypt_sector(chunk, tweak);
}
let remainder = chunks.into_remainder();
if !remainder.is_empty() {
let i = area_len / sector_size;
let tweak = get_tweak_fn(
u128::try_from(i).expect("usize cannot be bigger than u128") + first_sector_index,
);
self.encrypt_sector(remainder, tweak);
}
}
/// Decrypts a whole area in place, usually consisting of multiple sectors.
///
/// The tweak is computed at the start of every sector using get_tweak_fn(sector_index).
/// `get_tweak_fn` is usually `get_tweak_default`.
///
/// # Panics
/// - If the block size is not 16 bytes.
/// - If there's less than a single block in the last sector.
pub fn decrypt_area(
&self,
area: &mut [u8],
sector_size: usize,
first_sector_index: u128,
get_tweak_fn: impl Fn(u128) -> [u8; 16],
) {
let area_len = area.len();
let mut chunks = area.chunks_exact_mut(sector_size);
for (i, chunk) in (&mut chunks).enumerate() {
let tweak = get_tweak_fn(
u128::try_from(i).expect("usize cannot be bigger than u128") + first_sector_index,
);
self.decrypt_sector(chunk, tweak);
}
let remainder = chunks.into_remainder();
if !remainder.is_empty() {
let i = area_len / sector_size;
let tweak = get_tweak_fn(
u128::try_from(i).expect("usize cannot be bigger than u128") + first_sector_index,
);
self.decrypt_sector(remainder, tweak);
}
}
}
/// This is the default way to get the tweak, which just consists of separating the sector_index
/// in an array of 16 bytes with little endian. May be called to get the tweak for every sector
/// or passed directly to `(en/de)crypt_area`, which will basically do that.
pub fn get_tweak_default(sector_index: u128) -> [u8; 16] {
sector_index.to_le_bytes()
}
#[inline(always)]
fn xor(buf: &mut [u8], key: &[u8]) {
debug_assert_eq!(buf.len(), key.len());
for (a, b) in buf.iter_mut().zip(key) {
*a ^= *b;
}
}
fn galois_field_128_mul_le(tweak_source: [u8; 16]) -> [u8; 16] {
let low_bytes = u64::from_le_bytes(tweak_source[0..8].try_into().unwrap());
let high_bytes = u64::from_le_bytes(tweak_source[8..16].try_into().unwrap());
let new_low_bytes = (low_bytes << 1) ^ if (high_bytes >> 63) != 0 { 0x87 } else { 0x00 };
let new_high_bytes = (low_bytes >> 63) | (high_bytes << 1);
let mut tweak = [0; 16];
// byteorder used for performance, as it uses std::ptr::copy_nonoverlapping
LittleEndian::write_u64(&mut tweak[0..8], new_low_bytes);
LittleEndian::write_u64(&mut tweak[8..16], new_high_bytes);
tweak
}
| 34.938776 | 242 | 0.632228 |
1caf2f2c62721f1dc423ead9b7b6f36b574a88b0 | 172,449 | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! SQL Parser
#[cfg(not(feature = "std"))]
use alloc::{
boxed::Box,
format,
string::{String, ToString},
vec,
vec::Vec,
};
use core::fmt;
use log::debug;
use crate::ast::*;
use crate::dialect::*;
use crate::keywords::{self, Keyword};
use crate::tokenizer::*;
#[derive(Debug, Clone, PartialEq)]
pub enum ParserError {
TokenizerError(String),
ParserError(String),
}
// Use `Parser::expected` instead, if possible
macro_rules! parser_err {
($MSG:expr) => {
Err(ParserError::ParserError($MSG.to_string()))
};
}
// Returns a successful result if the optional expression is some
macro_rules! return_ok_if_some {
($e:expr) => {{
if let Some(v) = $e {
return Ok(v);
}
}};
}
#[derive(PartialEq)]
pub enum IsOptional {
Optional,
Mandatory,
}
use IsOptional::*;
pub enum IsLateral {
Lateral,
NotLateral,
}
use IsLateral::*;
pub enum WildcardExpr {
Expr(Expr),
QualifiedWildcard(ObjectName),
Wildcard,
}
impl From<WildcardExpr> for FunctionArgExpr {
fn from(wildcard_expr: WildcardExpr) -> Self {
match wildcard_expr {
WildcardExpr::Expr(expr) => Self::Expr(expr),
WildcardExpr::QualifiedWildcard(prefix) => Self::QualifiedWildcard(prefix),
WildcardExpr::Wildcard => Self::Wildcard,
}
}
}
impl From<TokenizerError> for ParserError {
fn from(e: TokenizerError) -> Self {
ParserError::TokenizerError(e.to_string())
}
}
impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"sql parser error: {}",
match self {
ParserError::TokenizerError(s) => s,
ParserError::ParserError(s) => s,
}
)
}
}
#[cfg(feature = "std")]
impl std::error::Error for ParserError {}
pub struct Parser<'a> {
tokens: Vec<Token>,
/// The index of the first unprocessed token in `self.tokens`
index: usize,
dialect: &'a dyn Dialect,
}
impl<'a> Parser<'a> {
/// Parse the specified tokens
pub fn new(tokens: Vec<Token>, dialect: &'a dyn Dialect) -> Self {
Parser {
tokens,
index: 0,
dialect,
}
}
/// Parse a SQL statement and produce an Abstract Syntax Tree (AST)
pub fn parse_sql(dialect: &dyn Dialect, sql: &str) -> Result<Vec<Statement>, ParserError> {
let mut tokenizer = Tokenizer::new(dialect, sql);
let tokens = tokenizer.tokenize()?;
let mut parser = Parser::new(tokens, dialect);
let mut stmts = Vec::new();
let mut expecting_statement_delimiter = false;
debug!("Parsing sql '{}'...", sql);
loop {
// ignore empty statements (between successive statement delimiters)
while parser.consume_token(&Token::SemiColon) {
expecting_statement_delimiter = false;
}
if parser.peek_token() == Token::EOF {
break;
}
if expecting_statement_delimiter {
return parser.expected("end of statement", parser.peek_token());
}
let statement = parser.parse_statement()?;
stmts.push(statement);
expecting_statement_delimiter = true;
}
Ok(stmts)
}
/// Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.),
/// stopping before the statement separator, if any.
pub fn parse_statement(&mut self) -> Result<Statement, ParserError> {
match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::KILL => Ok(self.parse_kill()?),
Keyword::DESCRIBE => Ok(self.parse_explain(true)?),
Keyword::EXPLAIN => Ok(self.parse_explain(false)?),
Keyword::ANALYZE => Ok(self.parse_analyze()?),
Keyword::SELECT | Keyword::WITH | Keyword::VALUES => {
self.prev_token();
Ok(Statement::Query(Box::new(self.parse_query()?)))
}
Keyword::TRUNCATE => Ok(self.parse_truncate()?),
Keyword::MSCK => Ok(self.parse_msck()?),
Keyword::CREATE => Ok(self.parse_create()?),
Keyword::DROP => Ok(self.parse_drop()?),
Keyword::DELETE => Ok(self.parse_delete()?),
Keyword::INSERT => Ok(self.parse_insert()?),
Keyword::UPDATE => Ok(self.parse_update()?),
Keyword::ALTER => Ok(self.parse_alter()?),
Keyword::COPY => Ok(self.parse_copy()?),
Keyword::SET => Ok(self.parse_set()?),
Keyword::SHOW => Ok(self.parse_show()?),
Keyword::GRANT => Ok(self.parse_grant()?),
Keyword::REVOKE => Ok(self.parse_revoke()?),
Keyword::START => Ok(self.parse_start_transaction()?),
// `BEGIN` is a nonstandard but common alias for the
// standard `START TRANSACTION` statement. It is supported
// by at least PostgreSQL and MySQL.
Keyword::BEGIN => Ok(self.parse_begin()?),
Keyword::SAVEPOINT => Ok(self.parse_savepoint()?),
Keyword::COMMIT => Ok(self.parse_commit()?),
Keyword::ROLLBACK => Ok(self.parse_rollback()?),
Keyword::ASSERT => Ok(self.parse_assert()?),
// `PREPARE`, `EXECUTE` and `DEALLOCATE` are Postgres-specific
// syntaxes. They are used for Postgres prepared statement.
Keyword::DEALLOCATE => Ok(self.parse_deallocate()?),
Keyword::EXECUTE => Ok(self.parse_execute()?),
Keyword::PREPARE => Ok(self.parse_prepare()?),
Keyword::MERGE => Ok(self.parse_merge()?),
Keyword::REPLACE if dialect_of!(self is SQLiteDialect ) => {
self.prev_token();
Ok(self.parse_insert()?)
}
Keyword::COMMENT if dialect_of!(self is PostgreSqlDialect) => {
Ok(self.parse_comment()?)
}
_ => self.expected("an SQL statement", Token::Word(w)),
},
Token::LParen => {
self.prev_token();
Ok(Statement::Query(Box::new(self.parse_query()?)))
}
unexpected => self.expected("an SQL statement", unexpected),
}
}
pub fn parse_msck(&mut self) -> Result<Statement, ParserError> {
let repair = self.parse_keyword(Keyword::REPAIR);
self.expect_keyword(Keyword::TABLE)?;
let table_name = self.parse_object_name()?;
let partition_action = self
.maybe_parse(|parser| {
let pa = match parser.parse_one_of_keywords(&[
Keyword::ADD,
Keyword::DROP,
Keyword::SYNC,
]) {
Some(Keyword::ADD) => Some(AddDropSync::ADD),
Some(Keyword::DROP) => Some(AddDropSync::DROP),
Some(Keyword::SYNC) => Some(AddDropSync::SYNC),
_ => None,
};
parser.expect_keyword(Keyword::PARTITIONS)?;
Ok(pa)
})
.unwrap_or_default();
Ok(Statement::Msck {
repair,
table_name,
partition_action,
})
}
pub fn parse_truncate(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::TABLE)?;
let table_name = self.parse_object_name()?;
let mut partitions = None;
if self.parse_keyword(Keyword::PARTITION) {
self.expect_token(&Token::LParen)?;
partitions = Some(self.parse_comma_separated(Parser::parse_expr)?);
self.expect_token(&Token::RParen)?;
}
Ok(Statement::Truncate {
table_name,
partitions,
})
}
pub fn parse_analyze(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::TABLE)?;
let table_name = self.parse_object_name()?;
let mut for_columns = false;
let mut cache_metadata = false;
let mut noscan = false;
let mut partitions = None;
let mut compute_statistics = false;
let mut columns = vec![];
loop {
match self.parse_one_of_keywords(&[
Keyword::PARTITION,
Keyword::FOR,
Keyword::CACHE,
Keyword::NOSCAN,
Keyword::COMPUTE,
]) {
Some(Keyword::PARTITION) => {
self.expect_token(&Token::LParen)?;
partitions = Some(self.parse_comma_separated(Parser::parse_expr)?);
self.expect_token(&Token::RParen)?;
}
Some(Keyword::NOSCAN) => noscan = true,
Some(Keyword::FOR) => {
self.expect_keyword(Keyword::COLUMNS)?;
columns = self
.maybe_parse(|parser| {
parser.parse_comma_separated(Parser::parse_identifier)
})
.unwrap_or_default();
for_columns = true
}
Some(Keyword::CACHE) => {
self.expect_keyword(Keyword::METADATA)?;
cache_metadata = true
}
Some(Keyword::COMPUTE) => {
self.expect_keyword(Keyword::STATISTICS)?;
compute_statistics = true
}
_ => break,
}
}
Ok(Statement::Analyze {
table_name,
for_columns,
columns,
partitions,
cache_metadata,
noscan,
compute_statistics,
})
}
/// Parse a new expression including wildcard & qualified wildcard
pub fn parse_wildcard_expr(&mut self) -> Result<WildcardExpr, ParserError> {
let index = self.index;
match self.next_token() {
Token::Word(w) if self.peek_token() == Token::Period => {
let mut id_parts: Vec<Ident> = vec![w.to_ident()];
while self.consume_token(&Token::Period) {
match self.next_token() {
Token::Word(w) => id_parts.push(w.to_ident()),
Token::Mul => {
return Ok(WildcardExpr::QualifiedWildcard(ObjectName(id_parts)));
}
unexpected => {
return self.expected("an identifier or a '*' after '.'", unexpected);
}
}
}
}
Token::Mul => {
return Ok(WildcardExpr::Wildcard);
}
_ => (),
};
self.index = index;
self.parse_expr().map(WildcardExpr::Expr)
}
/// Parse a new expression
pub fn parse_expr(&mut self) -> Result<Expr, ParserError> {
self.parse_subexpr(0)
}
/// Parse tokens until the precedence changes
pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError> {
debug!("parsing expr");
let mut expr = self.parse_prefix()?;
debug!("prefix: {:?}", expr);
loop {
let next_precedence = self.get_next_precedence()?;
debug!("next precedence: {:?}", next_precedence);
if precedence >= next_precedence {
break;
}
expr = self.parse_infix(expr, next_precedence)?;
}
Ok(expr)
}
pub fn parse_assert(&mut self) -> Result<Statement, ParserError> {
let condition = self.parse_expr()?;
let message = if self.parse_keyword(Keyword::AS) {
Some(self.parse_expr()?)
} else {
None
};
Ok(Statement::Assert { condition, message })
}
pub fn parse_savepoint(&mut self) -> Result<Statement, ParserError> {
let name = self.parse_identifier()?;
Ok(Statement::Savepoint { name })
}
/// Parse an expression prefix
pub fn parse_prefix(&mut self) -> Result<Expr, ParserError> {
// PostgreSQL allows any string literal to be preceded by a type name, indicating that the
// string literal represents a literal of that type. Some examples:
//
// DATE '2020-05-20'
// TIMESTAMP WITH TIME ZONE '2020-05-20 7:43:54'
// BOOL 'true'
//
// The first two are standard SQL, while the latter is a PostgreSQL extension. Complicating
// matters is the fact that INTERVAL string literals may optionally be followed by special
// keywords, e.g.:
//
// INTERVAL '7' DAY
//
// Note also that naively `SELECT date` looks like a syntax error because the `date` type
// name is not followed by a string literal, but in fact in PostgreSQL it is a valid
// expression that should parse as the column name "date".
return_ok_if_some!(self.maybe_parse(|parser| {
match parser.parse_data_type()? {
DataType::Interval => parser.parse_literal_interval(),
// PostgreSQL allows almost any identifier to be used as custom data type name,
// and we support that in `parse_data_type()`. But unlike Postgres we don't
// have a list of globally reserved keywords (since they vary across dialects),
// so given `NOT 'a' LIKE 'b'`, we'd accept `NOT` as a possible custom data type
// name, resulting in `NOT 'a'` being recognized as a `TypedString` instead of
// an unary negation `NOT ('a' LIKE 'b')`. To solve this, we don't accept the
// `type 'string'` syntax for the custom data types at all.
DataType::Custom(..) => parser_err!("dummy"),
data_type => Ok(Expr::TypedString {
data_type,
value: parser.parse_literal_string()?,
}),
}
}));
let expr = match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::TRUE | Keyword::FALSE | Keyword::NULL => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
Keyword::CURRENT_TIMESTAMP | Keyword::CURRENT_TIME | Keyword::CURRENT_DATE => {
self.parse_time_functions(ObjectName(vec![w.to_ident()]))
}
Keyword::CASE => self.parse_case_expr(),
Keyword::CAST => self.parse_cast_expr(),
Keyword::TRY_CAST => self.parse_try_cast_expr(),
Keyword::EXISTS => self.parse_exists_expr(),
Keyword::EXTRACT => self.parse_extract_expr(),
Keyword::POSITION => self.parse_position_expr(),
Keyword::SUBSTRING => self.parse_substring_expr(),
Keyword::TRIM => self.parse_trim_expr(),
Keyword::INTERVAL => self.parse_literal_interval(),
Keyword::LISTAGG => self.parse_listagg_expr(),
// Treat ARRAY[1,2,3] as an array [1,2,3], otherwise try as function call
Keyword::ARRAY if self.peek_token() == Token::LBracket => {
self.expect_token(&Token::LBracket)?;
self.parse_array_expr(true)
}
Keyword::NOT => Ok(Expr::UnaryOp {
op: UnaryOperator::Not,
expr: Box::new(self.parse_subexpr(Self::UNARY_NOT_PREC)?),
}),
// Here `w` is a word, check if it's a part of a multi-part
// identifier, a function call, or a simple identifier:
_ => match self.peek_token() {
Token::LParen | Token::Period => {
let mut id_parts: Vec<Ident> = vec![w.to_ident()];
while self.consume_token(&Token::Period) {
match self.next_token() {
Token::Word(w) => id_parts.push(w.to_ident()),
unexpected => {
return self
.expected("an identifier or a '*' after '.'", unexpected);
}
}
}
if self.consume_token(&Token::LParen) {
self.prev_token();
self.parse_function(ObjectName(id_parts))
} else {
Ok(Expr::CompoundIdentifier(id_parts))
}
}
_ => Ok(Expr::Identifier(w.to_ident())),
},
}, // End of Token::Word
// array `[1, 2, 3]`
Token::LBracket => self.parse_array_expr(false),
tok @ Token::Minus | tok @ Token::Plus => {
let op = if tok == Token::Plus {
UnaryOperator::Plus
} else {
UnaryOperator::Minus
};
Ok(Expr::UnaryOp {
op,
expr: Box::new(self.parse_subexpr(Self::PLUS_MINUS_PREC)?),
})
}
tok @ Token::DoubleExclamationMark
| tok @ Token::PGSquareRoot
| tok @ Token::PGCubeRoot
| tok @ Token::AtSign
| tok @ Token::Tilde
if dialect_of!(self is PostgreSqlDialect) =>
{
let op = match tok {
Token::DoubleExclamationMark => UnaryOperator::PGPrefixFactorial,
Token::PGSquareRoot => UnaryOperator::PGSquareRoot,
Token::PGCubeRoot => UnaryOperator::PGCubeRoot,
Token::AtSign => UnaryOperator::PGAbs,
Token::Tilde => UnaryOperator::PGBitwiseNot,
_ => unreachable!(),
};
Ok(Expr::UnaryOp {
op,
expr: Box::new(self.parse_subexpr(Self::PLUS_MINUS_PREC)?),
})
}
Token::Number(_, _)
| Token::SingleQuotedString(_)
| Token::NationalStringLiteral(_)
| Token::HexStringLiteral(_) => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
Token::LParen => {
let expr =
if self.parse_keyword(Keyword::SELECT) || self.parse_keyword(Keyword::WITH) {
self.prev_token();
Expr::Subquery(Box::new(self.parse_query()?))
} else {
let exprs = self.parse_comma_separated(Parser::parse_expr)?;
match exprs.len() {
0 => unreachable!(), // parse_comma_separated ensures 1 or more
1 => Expr::Nested(Box::new(exprs.into_iter().next().unwrap())),
_ => Expr::Tuple(exprs),
}
};
self.expect_token(&Token::RParen)?;
Ok(expr)
}
Token::Placeholder(_) => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
unexpected => self.expected("an expression:", unexpected),
}?;
if self.parse_keyword(Keyword::COLLATE) {
Ok(Expr::Collate {
expr: Box::new(expr),
collation: self.parse_object_name()?,
})
} else {
Ok(expr)
}
}
pub fn parse_function(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let distinct = self.parse_all_or_distinct()?;
let args = self.parse_optional_args()?;
let over = if self.parse_keyword(Keyword::OVER) {
// TBD: support window names (`OVER mywin`) in place of inline specification
self.expect_token(&Token::LParen)?;
let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
// a list of possibly-qualified column names
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_order_by_expr)?
} else {
vec![]
};
let window_frame = if !self.consume_token(&Token::RParen) {
let window_frame = self.parse_window_frame()?;
self.expect_token(&Token::RParen)?;
Some(window_frame)
} else {
None
};
Some(WindowSpec {
partition_by,
order_by,
window_frame,
})
} else {
None
};
Ok(Expr::Function(Function {
name,
args,
over,
distinct,
}))
}
pub fn parse_time_functions(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
let args = if self.consume_token(&Token::LParen) {
self.parse_optional_args()?
} else {
vec![]
};
Ok(Expr::Function(Function {
name,
args,
over: None,
distinct: false,
}))
}
pub fn parse_window_frame_units(&mut self) -> Result<WindowFrameUnits, ParserError> {
match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::ROWS => Ok(WindowFrameUnits::Rows),
Keyword::RANGE => Ok(WindowFrameUnits::Range),
Keyword::GROUPS => Ok(WindowFrameUnits::Groups),
_ => self.expected("ROWS, RANGE, GROUPS", Token::Word(w))?,
},
unexpected => self.expected("ROWS, RANGE, GROUPS", unexpected),
}
}
pub fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError> {
let units = self.parse_window_frame_units()?;
let (start_bound, end_bound) = if self.parse_keyword(Keyword::BETWEEN) {
let start_bound = self.parse_window_frame_bound()?;
self.expect_keyword(Keyword::AND)?;
let end_bound = Some(self.parse_window_frame_bound()?);
(start_bound, end_bound)
} else {
(self.parse_window_frame_bound()?, None)
};
Ok(WindowFrame {
units,
start_bound,
end_bound,
})
}
/// Parse `CURRENT ROW` or `{ <positive number> | UNBOUNDED } { PRECEDING | FOLLOWING }`
pub fn parse_window_frame_bound(&mut self) -> Result<WindowFrameBound, ParserError> {
if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
Ok(WindowFrameBound::CurrentRow)
} else {
let rows = if self.parse_keyword(Keyword::UNBOUNDED) {
None
} else {
Some(self.parse_literal_uint()?)
};
if self.parse_keyword(Keyword::PRECEDING) {
Ok(WindowFrameBound::Preceding(rows))
} else if self.parse_keyword(Keyword::FOLLOWING) {
Ok(WindowFrameBound::Following(rows))
} else {
self.expected("PRECEDING or FOLLOWING", self.peek_token())
}
}
}
/// parse a group by expr. a group by expr can be one of group sets, roll up, cube, or simple
/// expr.
fn parse_group_by_expr(&mut self) -> Result<Expr, ParserError> {
if dialect_of!(self is PostgreSqlDialect) {
if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
self.expect_token(&Token::LParen)?;
let result = self.parse_comma_separated(|p| p.parse_tuple(false, true))?;
self.expect_token(&Token::RParen)?;
Ok(Expr::GroupingSets(result))
} else if self.parse_keyword(Keyword::CUBE) {
self.expect_token(&Token::LParen)?;
let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Cube(result))
} else if self.parse_keyword(Keyword::ROLLUP) {
self.expect_token(&Token::LParen)?;
let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Rollup(result))
} else {
self.parse_expr()
}
} else {
// TODO parse rollup for other dialects
self.parse_expr()
}
}
/// parse a tuple with `(` and `)`.
/// If `lift_singleton` is true, then a singleton tuple is lifted to a tuple of length 1, otherwise it will fail.
/// If `allow_empty` is true, then an empty tuple is allowed.
fn parse_tuple(
&mut self,
lift_singleton: bool,
allow_empty: bool,
) -> Result<Vec<Expr>, ParserError> {
if lift_singleton {
if self.consume_token(&Token::LParen) {
let result = if allow_empty && self.consume_token(&Token::RParen) {
vec![]
} else {
let result = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
result
};
Ok(result)
} else {
Ok(vec![self.parse_expr()?])
}
} else {
self.expect_token(&Token::LParen)?;
let result = if allow_empty && self.consume_token(&Token::RParen) {
vec![]
} else {
let result = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
result
};
Ok(result)
}
}
pub fn parse_case_expr(&mut self) -> Result<Expr, ParserError> {
let mut operand = None;
if !self.parse_keyword(Keyword::WHEN) {
operand = Some(Box::new(self.parse_expr()?));
self.expect_keyword(Keyword::WHEN)?;
}
let mut conditions = vec![];
let mut results = vec![];
loop {
conditions.push(self.parse_expr()?);
self.expect_keyword(Keyword::THEN)?;
results.push(self.parse_expr()?);
if !self.parse_keyword(Keyword::WHEN) {
break;
}
}
let else_result = if self.parse_keyword(Keyword::ELSE) {
Some(Box::new(self.parse_expr()?))
} else {
None
};
self.expect_keyword(Keyword::END)?;
Ok(Expr::Case {
operand,
conditions,
results,
else_result,
})
}
/// Parse a SQL CAST function e.g. `CAST(expr AS FLOAT)`
pub fn parse_cast_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
self.expect_keyword(Keyword::AS)?;
let data_type = self.parse_data_type()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Cast {
expr: Box::new(expr),
data_type,
})
}
/// Parse a SQL TRY_CAST function e.g. `TRY_CAST(expr AS FLOAT)`
pub fn parse_try_cast_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
self.expect_keyword(Keyword::AS)?;
let data_type = self.parse_data_type()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::TryCast {
expr: Box::new(expr),
data_type,
})
}
/// Parse a SQL EXISTS expression e.g. `WHERE EXISTS(SELECT ...)`.
pub fn parse_exists_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let exists_node = Expr::Exists(Box::new(self.parse_query()?));
self.expect_token(&Token::RParen)?;
Ok(exists_node)
}
pub fn parse_extract_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let field = self.parse_date_time_field()?;
self.expect_keyword(Keyword::FROM)?;
let expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Extract {
field,
expr: Box::new(expr),
})
}
pub fn parse_position_expr(&mut self) -> Result<Expr, ParserError> {
// PARSE SELECT POSITION('@' in field)
self.expect_token(&Token::LParen)?;
// Parse the subexpr till the IN keyword
let expr = self.parse_subexpr(Self::BETWEEN_PREC)?;
if self.parse_keyword(Keyword::IN) {
let from = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Position {
expr: Box::new(expr),
r#in: Box::new(from),
})
} else {
return parser_err!("Position function must include IN keyword".to_string());
}
}
pub fn parse_substring_expr(&mut self) -> Result<Expr, ParserError> {
// PARSE SUBSTRING (EXPR [FROM 1] [FOR 3])
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
let mut from_expr = None;
if self.parse_keyword(Keyword::FROM) || self.consume_token(&Token::Comma) {
from_expr = Some(self.parse_expr()?);
}
let mut to_expr = None;
if self.parse_keyword(Keyword::FOR) || self.consume_token(&Token::Comma) {
to_expr = Some(self.parse_expr()?);
}
self.expect_token(&Token::RParen)?;
Ok(Expr::Substring {
expr: Box::new(expr),
substring_from: from_expr.map(Box::new),
substring_for: to_expr.map(Box::new),
})
}
/// TRIM (WHERE 'text' FROM 'text')\
/// TRIM ('text')
pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let mut where_expr = None;
if let Token::Word(word) = self.peek_token() {
if [Keyword::BOTH, Keyword::LEADING, Keyword::TRAILING]
.iter()
.any(|d| word.keyword == *d)
{
let trim_where = self.parse_trim_where()?;
let sub_expr = self.parse_expr()?;
self.expect_keyword(Keyword::FROM)?;
where_expr = Some((trim_where, Box::new(sub_expr)));
}
}
let expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Trim {
expr: Box::new(expr),
trim_where: where_expr,
})
}
pub fn parse_trim_where(&mut self) -> Result<TrimWhereField, ParserError> {
match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::BOTH => Ok(TrimWhereField::Both),
Keyword::LEADING => Ok(TrimWhereField::Leading),
Keyword::TRAILING => Ok(TrimWhereField::Trailing),
_ => self.expected("trim_where field", Token::Word(w))?,
},
unexpected => self.expected("trim_where field", unexpected),
}
}
/// Parses an array expression `[ex1, ex2, ..]`
/// if `named` is `true`, came from an expression like `ARRAY[ex1, ex2]`
pub fn parse_array_expr(&mut self, named: bool) -> Result<Expr, ParserError> {
let exprs = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RBracket)?;
Ok(Expr::Array(Array { elem: exprs, named }))
}
/// Parse a SQL LISTAGG expression, e.g. `LISTAGG(...) WITHIN GROUP (ORDER BY ...)`.
pub fn parse_listagg_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let distinct = self.parse_all_or_distinct()?;
let expr = Box::new(self.parse_expr()?);
// While ANSI SQL would would require the separator, Redshift makes this optional. Here we
// choose to make the separator optional as this provides the more general implementation.
let separator = if self.consume_token(&Token::Comma) {
Some(Box::new(self.parse_expr()?))
} else {
None
};
let on_overflow = if self.parse_keywords(&[Keyword::ON, Keyword::OVERFLOW]) {
if self.parse_keyword(Keyword::ERROR) {
Some(ListAggOnOverflow::Error)
} else {
self.expect_keyword(Keyword::TRUNCATE)?;
let filler = match self.peek_token() {
Token::Word(w)
if w.keyword == Keyword::WITH || w.keyword == Keyword::WITHOUT =>
{
None
}
Token::SingleQuotedString(_)
| Token::NationalStringLiteral(_)
| Token::HexStringLiteral(_) => Some(Box::new(self.parse_expr()?)),
unexpected => {
self.expected("either filler, WITH, or WITHOUT in LISTAGG", unexpected)?
}
};
let with_count = self.parse_keyword(Keyword::WITH);
if !with_count && !self.parse_keyword(Keyword::WITHOUT) {
self.expected("either WITH or WITHOUT in LISTAGG", self.peek_token())?;
}
self.expect_keyword(Keyword::COUNT)?;
Some(ListAggOnOverflow::Truncate { filler, with_count })
}
} else {
None
};
self.expect_token(&Token::RParen)?;
// Once again ANSI SQL requires WITHIN GROUP, but Redshift does not. Again we choose the
// more general implementation.
let within_group = if self.parse_keywords(&[Keyword::WITHIN, Keyword::GROUP]) {
self.expect_token(&Token::LParen)?;
self.expect_keywords(&[Keyword::ORDER, Keyword::BY])?;
let order_by_expr = self.parse_comma_separated(Parser::parse_order_by_expr)?;
self.expect_token(&Token::RParen)?;
order_by_expr
} else {
vec![]
};
Ok(Expr::ListAgg(ListAgg {
distinct,
expr,
separator,
on_overflow,
within_group,
}))
}
// This function parses date/time fields for both the EXTRACT function-like
// operator and interval qualifiers. EXTRACT supports a wider set of
// date/time fields than interval qualifiers, so this function may need to
// be split in two.
pub fn parse_date_time_field(&mut self) -> Result<DateTimeField, ParserError> {
match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::YEAR => Ok(DateTimeField::Year),
Keyword::MONTH => Ok(DateTimeField::Month),
Keyword::WEEK => Ok(DateTimeField::Week),
Keyword::DAY => Ok(DateTimeField::Day),
Keyword::HOUR => Ok(DateTimeField::Hour),
Keyword::MINUTE => Ok(DateTimeField::Minute),
Keyword::SECOND => Ok(DateTimeField::Second),
Keyword::CENTURY => Ok(DateTimeField::Century),
Keyword::DECADE => Ok(DateTimeField::Decade),
Keyword::DOY => Ok(DateTimeField::Doy),
Keyword::DOW => Ok(DateTimeField::Dow),
Keyword::EPOCH => Ok(DateTimeField::Epoch),
Keyword::ISODOW => Ok(DateTimeField::Isodow),
Keyword::ISOYEAR => Ok(DateTimeField::Isoyear),
Keyword::JULIAN => Ok(DateTimeField::Julian),
Keyword::MICROSECONDS => Ok(DateTimeField::Microseconds),
Keyword::MILLENIUM => Ok(DateTimeField::Millenium),
Keyword::MILLISECONDS => Ok(DateTimeField::Milliseconds),
Keyword::QUARTER => Ok(DateTimeField::Quarter),
Keyword::TIMEZONE => Ok(DateTimeField::Timezone),
Keyword::TIMEZONE_HOUR => Ok(DateTimeField::TimezoneHour),
Keyword::TIMEZONE_MINUTE => Ok(DateTimeField::TimezoneMinute),
_ => self.expected("date/time field", Token::Word(w))?,
},
unexpected => self.expected("date/time field", unexpected),
}
}
/// Parse an INTERVAL literal.
///
/// Some syntactically valid intervals:
///
/// 1. `INTERVAL '1' DAY`
/// 2. `INTERVAL '1-1' YEAR TO MONTH`
/// 3. `INTERVAL '1' SECOND`
/// 4. `INTERVAL '1:1:1.1' HOUR (5) TO SECOND (5)`
/// 5. `INTERVAL '1.1' SECOND (2, 2)`
/// 6. `INTERVAL '1:1' HOUR (5) TO MINUTE (5)`
///
/// Note that we do not currently attempt to parse the quoted value.
pub fn parse_literal_interval(&mut self) -> Result<Expr, ParserError> {
// The SQL standard allows an optional sign before the value string, but
// it is not clear if any implementations support that syntax, so we
// don't currently try to parse it. (The sign can instead be included
// inside the value string.)
// The first token in an interval is a string literal which specifies
// the duration of the interval.
let value = self.parse_literal_string()?;
// Following the string literal is a qualifier which indicates the units
// of the duration specified in the string literal.
//
// Note that PostgreSQL allows omitting the qualifier, so we provide
// this more general implemenation.
let leading_field = match self.peek_token() {
Token::Word(kw)
if [
Keyword::YEAR,
Keyword::MONTH,
Keyword::WEEK,
Keyword::DAY,
Keyword::HOUR,
Keyword::MINUTE,
Keyword::SECOND,
Keyword::CENTURY,
Keyword::DECADE,
Keyword::DOW,
Keyword::DOY,
Keyword::EPOCH,
Keyword::ISODOW,
Keyword::ISOYEAR,
Keyword::JULIAN,
Keyword::MICROSECONDS,
Keyword::MILLENIUM,
Keyword::MILLISECONDS,
Keyword::QUARTER,
Keyword::TIMEZONE,
Keyword::TIMEZONE_HOUR,
Keyword::TIMEZONE_MINUTE,
]
.iter()
.any(|d| kw.keyword == *d) =>
{
Some(self.parse_date_time_field()?)
}
_ => None,
};
let (leading_precision, last_field, fsec_precision) =
if leading_field == Some(DateTimeField::Second) {
// SQL mandates special syntax for `SECOND TO SECOND` literals.
// Instead of
// `SECOND [(<leading precision>)] TO SECOND[(<fractional seconds precision>)]`
// one must use the special format:
// `SECOND [( <leading precision> [ , <fractional seconds precision>] )]`
let last_field = None;
let (leading_precision, fsec_precision) = self.parse_optional_precision_scale()?;
(leading_precision, last_field, fsec_precision)
} else {
let leading_precision = self.parse_optional_precision()?;
if self.parse_keyword(Keyword::TO) {
let last_field = Some(self.parse_date_time_field()?);
let fsec_precision = if last_field == Some(DateTimeField::Second) {
self.parse_optional_precision()?
} else {
None
};
(leading_precision, last_field, fsec_precision)
} else {
(leading_precision, None, None)
}
};
Ok(Expr::Value(Value::Interval {
value,
leading_field,
leading_precision,
last_field,
fractional_seconds_precision: fsec_precision,
}))
}
/// Parse an operator following an expression
pub fn parse_infix(&mut self, expr: Expr, precedence: u8) -> Result<Expr, ParserError> {
let tok = self.next_token();
let regular_binary_operator = match &tok {
Token::Spaceship => Some(BinaryOperator::Spaceship),
Token::DoubleEq => Some(BinaryOperator::Eq),
Token::Eq => Some(BinaryOperator::Eq),
Token::Neq => Some(BinaryOperator::NotEq),
Token::Gt => Some(BinaryOperator::Gt),
Token::GtEq => Some(BinaryOperator::GtEq),
Token::Lt => Some(BinaryOperator::Lt),
Token::LtEq => Some(BinaryOperator::LtEq),
Token::Plus => Some(BinaryOperator::Plus),
Token::Minus => Some(BinaryOperator::Minus),
Token::Mul => Some(BinaryOperator::Multiply),
Token::Mod => Some(BinaryOperator::Modulo),
Token::StringConcat => Some(BinaryOperator::StringConcat),
Token::Pipe => Some(BinaryOperator::BitwiseOr),
Token::Caret => Some(BinaryOperator::BitwiseXor),
Token::Ampersand => Some(BinaryOperator::BitwiseAnd),
Token::Div => Some(BinaryOperator::Divide),
Token::ShiftLeft if dialect_of!(self is PostgreSqlDialect) => {
Some(BinaryOperator::PGBitwiseShiftLeft)
}
Token::ShiftRight if dialect_of!(self is PostgreSqlDialect) => {
Some(BinaryOperator::PGBitwiseShiftRight)
}
Token::Sharp if dialect_of!(self is PostgreSqlDialect) => {
Some(BinaryOperator::PGBitwiseXor)
}
Token::Tilde => Some(BinaryOperator::PGRegexMatch),
Token::TildeAsterisk => Some(BinaryOperator::PGRegexIMatch),
Token::ExclamationMarkTilde => Some(BinaryOperator::PGRegexNotMatch),
Token::ExclamationMarkTildeAsterisk => Some(BinaryOperator::PGRegexNotIMatch),
Token::Word(w) => match w.keyword {
Keyword::AND => Some(BinaryOperator::And),
Keyword::OR => Some(BinaryOperator::Or),
Keyword::LIKE => Some(BinaryOperator::Like),
Keyword::ILIKE => Some(BinaryOperator::ILike),
Keyword::NOT => {
if self.parse_keyword(Keyword::LIKE) {
Some(BinaryOperator::NotLike)
} else if self.parse_keyword(Keyword::ILIKE) {
Some(BinaryOperator::NotILike)
} else {
None
}
}
Keyword::XOR => Some(BinaryOperator::Xor),
_ => None,
},
_ => None,
};
if let Some(op) = regular_binary_operator {
if let Some(keyword) = self.parse_one_of_keywords(&[Keyword::ANY, Keyword::ALL]) {
self.expect_token(&Token::LParen)?;
let right = self.parse_subexpr(precedence)?;
self.expect_token(&Token::RParen)?;
let right = match keyword {
Keyword::ALL => Box::new(Expr::AllOp(Box::new(right))),
Keyword::ANY => Box::new(Expr::AnyOp(Box::new(right))),
_ => unreachable!(),
};
Ok(Expr::BinaryOp {
left: Box::new(expr),
op,
right,
})
} else {
Ok(Expr::BinaryOp {
left: Box::new(expr),
op,
right: Box::new(self.parse_subexpr(precedence)?),
})
}
} else if let Token::Word(w) = &tok {
match w.keyword {
Keyword::IS => {
if self.parse_keyword(Keyword::NULL) {
Ok(Expr::IsNull(Box::new(expr)))
} else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
Ok(Expr::IsNotNull(Box::new(expr)))
} else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::FROM]) {
let expr2 = self.parse_expr()?;
Ok(Expr::IsDistinctFrom(Box::new(expr), Box::new(expr2)))
} else if self.parse_keywords(&[Keyword::NOT, Keyword::DISTINCT, Keyword::FROM])
{
let expr2 = self.parse_expr()?;
Ok(Expr::IsNotDistinctFrom(Box::new(expr), Box::new(expr2)))
} else if let Some(right) =
self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE])
{
let mut val = Value::Boolean(true);
if right == Keyword::FALSE {
val = Value::Boolean(false);
}
Ok(Expr::BinaryOp {
left: Box::new(expr),
op: BinaryOperator::Eq,
right: Box::new(Expr::Value(val)),
})
} else {
self.expected(
"[NOT] NULL or [NOT] DISTINCT FROM TRUE FALSE after IS",
self.peek_token(),
)
}
}
Keyword::NOT | Keyword::IN | Keyword::BETWEEN => {
self.prev_token();
let negated = self.parse_keyword(Keyword::NOT);
if self.parse_keyword(Keyword::IN) {
self.parse_in(expr, negated)
} else if self.parse_keyword(Keyword::BETWEEN) {
self.parse_between(expr, negated)
} else {
self.expected("IN or BETWEEN after NOT", self.peek_token())
}
}
// Can only happen if `get_next_precedence` got out of sync with this function
_ => parser_err!(format!("No infix parser for token {:?}", tok)),
}
} else if Token::DoubleColon == tok {
self.parse_pg_cast(expr)
} else if Token::ExclamationMark == tok {
// PostgreSQL factorial operation
Ok(Expr::UnaryOp {
op: UnaryOperator::PGPostfixFactorial,
expr: Box::new(expr),
})
} else if Token::LBracket == tok {
if dialect_of!(self is PostgreSqlDialect | GenericDialect) {
// parse index
return self.parse_array_index(expr);
}
self.parse_map_access(expr)
} else if Token::Arrow == tok
|| Token::LongArrow == tok
|| Token::HashArrow == tok
|| Token::HashLongArrow == tok
{
let operator = match tok {
Token::Arrow => JsonOperator::Arrow,
Token::LongArrow => JsonOperator::LongArrow,
Token::HashArrow => JsonOperator::HashArrow,
Token::HashLongArrow => JsonOperator::HashLongArrow,
_ => unreachable!(),
};
Ok(Expr::JsonAccess {
left: Box::new(expr),
operator,
right: Box::new(self.parse_expr()?),
})
} else {
// Can only happen if `get_next_precedence` got out of sync with this function
parser_err!(format!("No infix parser for token {:?}", tok))
}
}
pub fn parse_array_index(&mut self, expr: Expr) -> Result<Expr, ParserError> {
let index = self.parse_expr()?;
self.expect_token(&Token::RBracket)?;
let mut indexs: Vec<Expr> = vec![index];
while self.consume_token(&Token::LBracket) {
let index = self.parse_expr()?;
self.expect_token(&Token::RBracket)?;
indexs.push(index);
}
Ok(Expr::ArrayIndex {
obj: Box::new(expr),
indexs,
})
}
pub fn parse_map_access(&mut self, expr: Expr) -> Result<Expr, ParserError> {
let key = self.parse_map_key()?;
let tok = self.consume_token(&Token::RBracket);
debug!("Tok: {}", tok);
let mut key_parts: Vec<Expr> = vec![key];
while self.consume_token(&Token::LBracket) {
let key = self.parse_map_key()?;
let tok = self.consume_token(&Token::RBracket);
debug!("Tok: {}", tok);
key_parts.push(key);
}
match expr {
e @ Expr::Identifier(_) | e @ Expr::CompoundIdentifier(_) => Ok(Expr::MapAccess {
column: Box::new(e),
keys: key_parts,
}),
_ => Ok(expr),
}
}
/// Parses the parens following the `[ NOT ] IN` operator
pub fn parse_in(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
// BigQuery allows `IN UNNEST(array_expression)`
// https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#in_operators
if self.parse_keyword(Keyword::UNNEST) {
self.expect_token(&Token::LParen)?;
let array_expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
return Ok(Expr::InUnnest {
expr: Box::new(expr),
array_expr: Box::new(array_expr),
negated,
});
}
self.expect_token(&Token::LParen)?;
let in_op = if self.parse_keyword(Keyword::SELECT) || self.parse_keyword(Keyword::WITH) {
self.prev_token();
Expr::InSubquery {
expr: Box::new(expr),
subquery: Box::new(self.parse_query()?),
negated,
}
} else {
Expr::InList {
expr: Box::new(expr),
list: self.parse_comma_separated(Parser::parse_expr)?,
negated,
}
};
self.expect_token(&Token::RParen)?;
Ok(in_op)
}
/// Parses `BETWEEN <low> AND <high>`, assuming the `BETWEEN` keyword was already consumed
pub fn parse_between(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
// Stop parsing subexpressions for <low> and <high> on tokens with
// precedence lower than that of `BETWEEN`, such as `AND`, `IS`, etc.
let low = self.parse_subexpr(Self::BETWEEN_PREC)?;
self.expect_keyword(Keyword::AND)?;
let high = self.parse_subexpr(Self::BETWEEN_PREC)?;
Ok(Expr::Between {
expr: Box::new(expr),
negated,
low: Box::new(low),
high: Box::new(high),
})
}
/// Parse a postgresql casting style which is in the form of `expr::datatype`
pub fn parse_pg_cast(&mut self, expr: Expr) -> Result<Expr, ParserError> {
Ok(Expr::Cast {
expr: Box::new(expr),
data_type: self.parse_data_type()?,
})
}
const UNARY_NOT_PREC: u8 = 15;
const BETWEEN_PREC: u8 = 20;
const PLUS_MINUS_PREC: u8 = 30;
/// Get the precedence of the next token
pub fn get_next_precedence(&self) -> Result<u8, ParserError> {
let token = self.peek_token();
debug!("get_next_precedence() {:?}", token);
match token {
Token::Word(w) if w.keyword == Keyword::OR => Ok(5),
Token::Word(w) if w.keyword == Keyword::AND => Ok(10),
Token::Word(w) if w.keyword == Keyword::XOR => Ok(24),
Token::Word(w) if w.keyword == Keyword::NOT => match self.peek_nth_token(1) {
// The precedence of NOT varies depending on keyword that
// follows it. If it is followed by IN, BETWEEN, or LIKE,
// it takes on the precedence of those tokens. Otherwise it
// is not an infix operator, and therefore has zero
// precedence.
Token::Word(w) if w.keyword == Keyword::IN => Ok(Self::BETWEEN_PREC),
Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(Self::BETWEEN_PREC),
Token::Word(w) if w.keyword == Keyword::LIKE => Ok(Self::BETWEEN_PREC),
Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(Self::BETWEEN_PREC),
_ => Ok(0),
},
Token::Word(w) if w.keyword == Keyword::IS => Ok(17),
Token::Word(w) if w.keyword == Keyword::IN => Ok(Self::BETWEEN_PREC),
Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(Self::BETWEEN_PREC),
Token::Word(w) if w.keyword == Keyword::LIKE => Ok(Self::BETWEEN_PREC),
Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(Self::BETWEEN_PREC),
Token::Eq
| Token::Lt
| Token::LtEq
| Token::Neq
| Token::Gt
| Token::GtEq
| Token::DoubleEq
| Token::Tilde
| Token::TildeAsterisk
| Token::ExclamationMarkTilde
| Token::ExclamationMarkTildeAsterisk
| Token::Spaceship => Ok(20),
Token::Pipe => Ok(21),
Token::Caret | Token::Sharp | Token::ShiftRight | Token::ShiftLeft => Ok(22),
Token::Ampersand => Ok(23),
Token::Plus | Token::Minus => Ok(Self::PLUS_MINUS_PREC),
Token::Mul | Token::Div | Token::Mod | Token::StringConcat => Ok(40),
Token::DoubleColon => Ok(50),
Token::ExclamationMark => Ok(50),
Token::LBracket
| Token::LongArrow
| Token::Arrow
| Token::HashArrow
| Token::HashLongArrow => Ok(50),
_ => Ok(0),
}
}
/// Return the first non-whitespace token that has not yet been processed
/// (or None if reached end-of-file)
pub fn peek_token(&self) -> Token {
self.peek_nth_token(0)
}
/// Return nth non-whitespace token that has not yet been processed
pub fn peek_nth_token(&self, mut n: usize) -> Token {
let mut index = self.index;
loop {
index += 1;
match self.tokens.get(index - 1) {
Some(Token::Whitespace(_)) => continue,
non_whitespace => {
if n == 0 {
return non_whitespace.cloned().unwrap_or(Token::EOF);
}
n -= 1;
}
}
}
}
/// Return the first non-whitespace token that has not yet been processed
/// (or None if reached end-of-file) and mark it as processed. OK to call
/// repeatedly after reaching EOF.
pub fn next_token(&mut self) -> Token {
loop {
self.index += 1;
match self.tokens.get(self.index - 1) {
Some(Token::Whitespace(_)) => continue,
token => return token.cloned().unwrap_or(Token::EOF),
}
}
}
/// Return the first unprocessed token, possibly whitespace.
pub fn next_token_no_skip(&mut self) -> Option<&Token> {
self.index += 1;
self.tokens.get(self.index - 1)
}
/// Push back the last one non-whitespace token. Must be called after
/// `next_token()`, otherwise might panic. OK to call after
/// `next_token()` indicates an EOF.
pub fn prev_token(&mut self) {
loop {
assert!(self.index > 0);
self.index -= 1;
if let Some(Token::Whitespace(_)) = self.tokens.get(self.index) {
continue;
}
return;
}
}
/// Report unexpected token
fn expected<T>(&self, expected: &str, found: Token) -> Result<T, ParserError> {
parser_err!(format!("Expected {}, found: {}", expected, found))
}
/// Look for an expected keyword and consume it if it exists
#[must_use]
pub fn parse_keyword(&mut self, expected: Keyword) -> bool {
match self.peek_token() {
Token::Word(w) if expected == w.keyword => {
self.next_token();
true
}
_ => false,
}
}
/// Look for an expected sequence of keywords and consume them if they exist
#[must_use]
pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool {
let index = self.index;
for &keyword in keywords {
if !self.parse_keyword(keyword) {
// println!("parse_keywords aborting .. did not find {:?}", keyword);
// reset index and return immediately
self.index = index;
return false;
}
}
true
}
/// Look for one of the given keywords and return the one that matches.
#[must_use]
pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword> {
match self.peek_token() {
Token::Word(w) => {
keywords
.iter()
.find(|keyword| **keyword == w.keyword)
.map(|keyword| {
self.next_token();
*keyword
})
}
_ => None,
}
}
/// Bail out if the current token is not one of the expected keywords, or consume it if it is
pub fn expect_one_of_keywords(&mut self, keywords: &[Keyword]) -> Result<Keyword, ParserError> {
if let Some(keyword) = self.parse_one_of_keywords(keywords) {
Ok(keyword)
} else {
let keywords: Vec<String> = keywords.iter().map(|x| format!("{:?}", x)).collect();
self.expected(
&format!("one of {}", keywords.join(" or ")),
self.peek_token(),
)
}
}
/// Bail out if the current token is not an expected keyword, or consume it if it is
pub fn expect_keyword(&mut self, expected: Keyword) -> Result<(), ParserError> {
if self.parse_keyword(expected) {
Ok(())
} else {
self.expected(format!("{:?}", &expected).as_str(), self.peek_token())
}
}
/// Bail out if the following tokens are not the expected sequence of
/// keywords, or consume them if they are.
pub fn expect_keywords(&mut self, expected: &[Keyword]) -> Result<(), ParserError> {
for &kw in expected {
self.expect_keyword(kw)?;
}
Ok(())
}
/// Consume the next token if it matches the expected token, otherwise return false
#[must_use]
pub fn consume_token(&mut self, expected: &Token) -> bool {
if self.peek_token() == *expected {
self.next_token();
true
} else {
false
}
}
/// Bail out if the current token is not an expected keyword, or consume it if it is
pub fn expect_token(&mut self, expected: &Token) -> Result<(), ParserError> {
if self.consume_token(expected) {
Ok(())
} else {
self.expected(&expected.to_string(), self.peek_token())
}
}
/// Parse a comma-separated list of 1+ items accepted by `F`
pub fn parse_comma_separated<T, F>(&mut self, mut f: F) -> Result<Vec<T>, ParserError>
where
F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
{
let mut values = vec![];
loop {
values.push(f(self)?);
if !self.consume_token(&Token::Comma) {
break;
}
}
Ok(values)
}
/// Run a parser method `f`, reverting back to the current position
/// if unsuccessful.
#[must_use]
fn maybe_parse<T, F>(&mut self, mut f: F) -> Option<T>
where
F: FnMut(&mut Parser) -> Result<T, ParserError>,
{
let index = self.index;
if let Ok(t) = f(self) {
Some(t)
} else {
self.index = index;
None
}
}
/// Parse either `ALL` or `DISTINCT`. Returns `true` if `DISTINCT` is parsed and results in a
/// `ParserError` if both `ALL` and `DISTINCT` are fround.
pub fn parse_all_or_distinct(&mut self) -> Result<bool, ParserError> {
let all = self.parse_keyword(Keyword::ALL);
let distinct = self.parse_keyword(Keyword::DISTINCT);
if all && distinct {
return parser_err!("Cannot specify both ALL and DISTINCT".to_string());
} else {
Ok(distinct)
}
}
/// Parse a SQL CREATE statement
pub fn parse_create(&mut self) -> Result<Statement, ParserError> {
let or_replace = self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]);
let local = self.parse_one_of_keywords(&[Keyword::LOCAL]).is_some();
let global = self.parse_one_of_keywords(&[Keyword::GLOBAL]).is_some();
let global: Option<bool> = if global {
Some(true)
} else if local {
Some(false)
} else {
None
};
let temporary = self
.parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
.is_some();
if self.parse_keyword(Keyword::TABLE) {
self.parse_create_table(or_replace, temporary, global)
} else if self.parse_keyword(Keyword::MATERIALIZED) || self.parse_keyword(Keyword::VIEW) {
self.prev_token();
self.parse_create_view(or_replace)
} else if self.parse_keyword(Keyword::EXTERNAL) {
self.parse_create_external_table(or_replace)
} else if or_replace {
self.expected(
"[EXTERNAL] TABLE or [MATERIALIZED] VIEW after CREATE OR REPLACE",
self.peek_token(),
)
} else if self.parse_keyword(Keyword::INDEX) {
self.parse_create_index(false)
} else if self.parse_keywords(&[Keyword::UNIQUE, Keyword::INDEX]) {
self.parse_create_index(true)
} else if self.parse_keyword(Keyword::VIRTUAL) {
self.parse_create_virtual_table()
} else if self.parse_keyword(Keyword::SCHEMA) {
self.parse_create_schema()
} else if self.parse_keyword(Keyword::DATABASE) {
self.parse_create_database()
} else {
self.expected("an object type after CREATE", self.peek_token())
}
}
/// SQLite-specific `CREATE VIRTUAL TABLE`
pub fn parse_create_virtual_table(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::TABLE)?;
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let table_name = self.parse_object_name()?;
self.expect_keyword(Keyword::USING)?;
let module_name = self.parse_identifier()?;
// SQLite docs note that module "arguments syntax is sufficiently
// general that the arguments can be made to appear as column
// definitions in a traditional CREATE TABLE statement", but
// we don't implement that.
let module_args = self.parse_parenthesized_column_list(Optional)?;
Ok(Statement::CreateVirtualTable {
name: table_name,
if_not_exists,
module_name,
module_args,
})
}
pub fn parse_create_schema(&mut self) -> Result<Statement, ParserError> {
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let schema_name = self.parse_object_name()?;
Ok(Statement::CreateSchema {
schema_name,
if_not_exists,
})
}
pub fn parse_create_database(&mut self) -> Result<Statement, ParserError> {
let ine = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let db_name = self.parse_object_name()?;
let mut location = None;
let mut managed_location = None;
loop {
match self.parse_one_of_keywords(&[Keyword::LOCATION, Keyword::MANAGEDLOCATION]) {
Some(Keyword::LOCATION) => location = Some(self.parse_literal_string()?),
Some(Keyword::MANAGEDLOCATION) => {
managed_location = Some(self.parse_literal_string()?)
}
_ => break,
}
}
Ok(Statement::CreateDatabase {
db_name,
if_not_exists: ine,
location,
managed_location,
})
}
pub fn parse_create_external_table(
&mut self,
or_replace: bool,
) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::TABLE)?;
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let table_name = self.parse_object_name()?;
let (columns, constraints) = self.parse_columns()?;
let hive_distribution = self.parse_hive_distribution()?;
let hive_formats = self.parse_hive_formats()?;
let file_format = if let Some(ff) = &hive_formats.storage {
match ff {
HiveIOFormat::FileFormat { format } => Some(format.clone()),
_ => None,
}
} else {
None
};
let location = hive_formats.location.clone();
let table_properties = self.parse_options(Keyword::TBLPROPERTIES)?;
Ok(Statement::CreateTable {
name: table_name,
columns,
constraints,
hive_distribution,
hive_formats: Some(hive_formats),
with_options: vec![],
table_properties,
or_replace,
if_not_exists,
external: true,
global: None,
temporary: false,
file_format,
location,
query: None,
without_rowid: false,
like: None,
default_charset: None,
engine: None,
collation: None,
on_commit: None,
})
}
pub fn parse_file_format(&mut self) -> Result<FileFormat, ParserError> {
match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::AVRO => Ok(FileFormat::AVRO),
Keyword::JSONFILE => Ok(FileFormat::JSONFILE),
Keyword::ORC => Ok(FileFormat::ORC),
Keyword::PARQUET => Ok(FileFormat::PARQUET),
Keyword::RCFILE => Ok(FileFormat::RCFILE),
Keyword::SEQUENCEFILE => Ok(FileFormat::SEQUENCEFILE),
Keyword::TEXTFILE => Ok(FileFormat::TEXTFILE),
_ => self.expected("fileformat", Token::Word(w)),
},
unexpected => self.expected("fileformat", unexpected),
}
}
pub fn parse_create_view(&mut self, or_replace: bool) -> Result<Statement, ParserError> {
let materialized = self.parse_keyword(Keyword::MATERIALIZED);
self.expect_keyword(Keyword::VIEW)?;
// Many dialects support `OR ALTER` right after `CREATE`, but we don't (yet).
// ANSI SQL and Postgres support RECURSIVE here, but we don't support it either.
let name = self.parse_object_name()?;
let columns = self.parse_parenthesized_column_list(Optional)?;
let with_options = self.parse_options(Keyword::WITH)?;
self.expect_keyword(Keyword::AS)?;
let query = Box::new(self.parse_query()?);
// Optional `WITH [ CASCADED | LOCAL ] CHECK OPTION` is widely supported here.
Ok(Statement::CreateView {
name,
columns,
query,
materialized,
or_replace,
with_options,
})
}
pub fn parse_drop(&mut self) -> Result<Statement, ParserError> {
let object_type = if self.parse_keyword(Keyword::TABLE) {
ObjectType::Table
} else if self.parse_keyword(Keyword::VIEW) {
ObjectType::View
} else if self.parse_keyword(Keyword::INDEX) {
ObjectType::Index
} else if self.parse_keyword(Keyword::SCHEMA) {
ObjectType::Schema
} else {
return self.expected("TABLE, VIEW, INDEX or SCHEMA after DROP", self.peek_token());
};
// Many dialects support the non standard `IF EXISTS` clause and allow
// specifying multiple objects to delete in a single statement
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
let names = self.parse_comma_separated(Parser::parse_object_name)?;
let cascade = self.parse_keyword(Keyword::CASCADE);
let restrict = self.parse_keyword(Keyword::RESTRICT);
let purge = self.parse_keyword(Keyword::PURGE);
if cascade && restrict {
return parser_err!("Cannot specify both CASCADE and RESTRICT in DROP");
}
Ok(Statement::Drop {
object_type,
if_exists,
names,
cascade,
purge,
})
}
pub fn parse_create_index(&mut self, unique: bool) -> Result<Statement, ParserError> {
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let index_name = self.parse_object_name()?;
self.expect_keyword(Keyword::ON)?;
let table_name = self.parse_object_name()?;
self.expect_token(&Token::LParen)?;
let columns = self.parse_comma_separated(Parser::parse_order_by_expr)?;
self.expect_token(&Token::RParen)?;
Ok(Statement::CreateIndex {
name: index_name,
table_name,
columns,
unique,
if_not_exists,
})
}
//TODO: Implement parsing for Skewed and Clustered
pub fn parse_hive_distribution(&mut self) -> Result<HiveDistributionStyle, ParserError> {
if self.parse_keywords(&[Keyword::PARTITIONED, Keyword::BY]) {
self.expect_token(&Token::LParen)?;
let columns = self.parse_comma_separated(Parser::parse_column_def)?;
self.expect_token(&Token::RParen)?;
Ok(HiveDistributionStyle::PARTITIONED { columns })
} else {
Ok(HiveDistributionStyle::NONE)
}
}
pub fn parse_hive_formats(&mut self) -> Result<HiveFormat, ParserError> {
let mut hive_format = HiveFormat::default();
loop {
match self.parse_one_of_keywords(&[Keyword::ROW, Keyword::STORED, Keyword::LOCATION]) {
Some(Keyword::ROW) => {
hive_format.row_format = Some(self.parse_row_format()?);
}
Some(Keyword::STORED) => {
self.expect_keyword(Keyword::AS)?;
if self.parse_keyword(Keyword::INPUTFORMAT) {
let input_format = self.parse_expr()?;
self.expect_keyword(Keyword::OUTPUTFORMAT)?;
let output_format = self.parse_expr()?;
hive_format.storage = Some(HiveIOFormat::IOF {
input_format,
output_format,
});
} else {
let format = self.parse_file_format()?;
hive_format.storage = Some(HiveIOFormat::FileFormat { format });
}
}
Some(Keyword::LOCATION) => {
hive_format.location = Some(self.parse_literal_string()?);
}
None => break,
_ => break,
}
}
Ok(hive_format)
}
pub fn parse_row_format(&mut self) -> Result<HiveRowFormat, ParserError> {
self.expect_keyword(Keyword::FORMAT)?;
match self.parse_one_of_keywords(&[Keyword::SERDE, Keyword::DELIMITED]) {
Some(Keyword::SERDE) => {
let class = self.parse_literal_string()?;
Ok(HiveRowFormat::SERDE { class })
}
_ => Ok(HiveRowFormat::DELIMITED),
}
}
pub fn parse_create_table(
&mut self,
or_replace: bool,
temporary: bool,
global: Option<bool>,
) -> Result<Statement, ParserError> {
let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
let table_name = self.parse_object_name()?;
let like = if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
self.parse_object_name().ok()
} else {
None
};
// parse optional column list (schema)
let (columns, constraints) = self.parse_columns()?;
// SQLite supports `WITHOUT ROWID` at the end of `CREATE TABLE`
let without_rowid = self.parse_keywords(&[Keyword::WITHOUT, Keyword::ROWID]);
let hive_distribution = self.parse_hive_distribution()?;
let hive_formats = self.parse_hive_formats()?;
// PostgreSQL supports `WITH ( options )`, before `AS`
let with_options = self.parse_options(Keyword::WITH)?;
let table_properties = self.parse_options(Keyword::TBLPROPERTIES)?;
// Parse optional `AS ( query )`
let query = if self.parse_keyword(Keyword::AS) {
Some(Box::new(self.parse_query()?))
} else {
None
};
let engine = if self.parse_keyword(Keyword::ENGINE) {
self.expect_token(&Token::Eq)?;
match self.next_token() {
Token::Word(w) => Some(w.value),
unexpected => self.expected("identifier", unexpected)?,
}
} else {
None
};
let default_charset = if self.parse_keywords(&[Keyword::DEFAULT, Keyword::CHARSET]) {
self.expect_token(&Token::Eq)?;
match self.next_token() {
Token::Word(w) => Some(w.value),
unexpected => self.expected("identifier", unexpected)?,
}
} else {
None
};
let collation = if self.parse_keywords(&[Keyword::COLLATE]) {
self.expect_token(&Token::Eq)?;
match self.next_token() {
Token::Word(w) => Some(w.value),
unexpected => self.expected("identifier", unexpected)?,
}
} else {
None
};
let on_commit: Option<OnCommit> =
if self.parse_keywords(&[Keyword::ON, Keyword::COMMIT, Keyword::DELETE, Keyword::ROWS])
{
Some(OnCommit::DeleteRows)
} else if self.parse_keywords(&[
Keyword::ON,
Keyword::COMMIT,
Keyword::PRESERVE,
Keyword::ROWS,
]) {
Some(OnCommit::PreserveRows)
} else if self.parse_keywords(&[Keyword::ON, Keyword::COMMIT, Keyword::DROP]) {
Some(OnCommit::Drop)
} else {
None
};
Ok(Statement::CreateTable {
name: table_name,
temporary,
columns,
constraints,
with_options,
table_properties,
or_replace,
if_not_exists,
hive_distribution,
hive_formats: Some(hive_formats),
external: false,
global,
file_format: None,
location: None,
query,
without_rowid,
like,
engine,
default_charset,
collation,
on_commit,
})
}
pub fn parse_columns(&mut self) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError> {
let mut columns = vec![];
let mut constraints = vec![];
if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
return Ok((columns, constraints));
}
loop {
if let Some(constraint) = self.parse_optional_table_constraint()? {
constraints.push(constraint);
} else if let Token::Word(_) = self.peek_token() {
columns.push(self.parse_column_def()?);
} else {
return self.expected("column name or constraint definition", self.peek_token());
}
let comma = self.consume_token(&Token::Comma);
if self.consume_token(&Token::RParen) {
// allow a trailing comma, even though it's not in standard
break;
} else if !comma {
return self.expected("',' or ')' after column definition", self.peek_token());
}
}
Ok((columns, constraints))
}
pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError> {
let name = self.parse_identifier()?;
let data_type = self.parse_data_type()?;
let collation = if self.parse_keyword(Keyword::COLLATE) {
Some(self.parse_object_name()?)
} else {
None
};
let mut options = vec![];
loop {
if self.parse_keyword(Keyword::CONSTRAINT) {
let name = Some(self.parse_identifier()?);
if let Some(option) = self.parse_optional_column_option()? {
options.push(ColumnOptionDef { name, option });
} else {
return self.expected(
"constraint details after CONSTRAINT <name>",
self.peek_token(),
);
}
} else if let Some(option) = self.parse_optional_column_option()? {
options.push(ColumnOptionDef { name: None, option });
} else {
break;
};
}
Ok(ColumnDef {
name,
data_type,
collation,
options,
})
}
pub fn parse_optional_column_option(&mut self) -> Result<Option<ColumnOption>, ParserError> {
if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
Ok(Some(ColumnOption::CharacterSet(self.parse_object_name()?)))
} else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
Ok(Some(ColumnOption::NotNull))
} else if self.parse_keywords(&[Keyword::COMMENT]) {
match self.next_token() {
Token::SingleQuotedString(value, ..) => Ok(Some(ColumnOption::Comment(value))),
unexpected => self.expected("string", unexpected),
}
} else if self.parse_keyword(Keyword::NULL) {
Ok(Some(ColumnOption::Null))
} else if self.parse_keyword(Keyword::DEFAULT) {
Ok(Some(ColumnOption::Default(self.parse_expr()?)))
} else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
Ok(Some(ColumnOption::Unique { is_primary: true }))
} else if self.parse_keyword(Keyword::UNIQUE) {
Ok(Some(ColumnOption::Unique { is_primary: false }))
} else if self.parse_keyword(Keyword::REFERENCES) {
let foreign_table = self.parse_object_name()?;
// PostgreSQL allows omitting the column list and
// uses the primary key column of the foreign table by default
let referred_columns = self.parse_parenthesized_column_list(Optional)?;
let mut on_delete = None;
let mut on_update = None;
loop {
if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
on_delete = Some(self.parse_referential_action()?);
} else if on_update.is_none()
&& self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
{
on_update = Some(self.parse_referential_action()?);
} else {
break;
}
}
Ok(Some(ColumnOption::ForeignKey {
foreign_table,
referred_columns,
on_delete,
on_update,
}))
} else if self.parse_keyword(Keyword::CHECK) {
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
Ok(Some(ColumnOption::Check(expr)))
} else if self.parse_keyword(Keyword::AUTO_INCREMENT)
&& dialect_of!(self is MySqlDialect | GenericDialect)
{
// Support AUTO_INCREMENT for MySQL
Ok(Some(ColumnOption::DialectSpecific(vec![
Token::make_keyword("AUTO_INCREMENT"),
])))
} else if self.parse_keyword(Keyword::AUTOINCREMENT)
&& dialect_of!(self is SQLiteDialect | GenericDialect)
{
// Support AUTOINCREMENT for SQLite
Ok(Some(ColumnOption::DialectSpecific(vec![
Token::make_keyword("AUTOINCREMENT"),
])))
} else {
Ok(None)
}
}
pub fn parse_referential_action(&mut self) -> Result<ReferentialAction, ParserError> {
if self.parse_keyword(Keyword::RESTRICT) {
Ok(ReferentialAction::Restrict)
} else if self.parse_keyword(Keyword::CASCADE) {
Ok(ReferentialAction::Cascade)
} else if self.parse_keywords(&[Keyword::SET, Keyword::NULL]) {
Ok(ReferentialAction::SetNull)
} else if self.parse_keywords(&[Keyword::NO, Keyword::ACTION]) {
Ok(ReferentialAction::NoAction)
} else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
Ok(ReferentialAction::SetDefault)
} else {
self.expected(
"one of RESTRICT, CASCADE, SET NULL, NO ACTION or SET DEFAULT",
self.peek_token(),
)
}
}
pub fn parse_optional_table_constraint(
&mut self,
) -> Result<Option<TableConstraint>, ParserError> {
let name = if self.parse_keyword(Keyword::CONSTRAINT) {
Some(self.parse_identifier()?)
} else {
None
};
match self.next_token() {
Token::Word(w) if w.keyword == Keyword::PRIMARY || w.keyword == Keyword::UNIQUE => {
let is_primary = w.keyword == Keyword::PRIMARY;
if is_primary {
self.expect_keyword(Keyword::KEY)?;
}
let columns = self.parse_parenthesized_column_list(Mandatory)?;
Ok(Some(TableConstraint::Unique {
name,
columns,
is_primary,
}))
}
Token::Word(w) if w.keyword == Keyword::FOREIGN => {
self.expect_keyword(Keyword::KEY)?;
let columns = self.parse_parenthesized_column_list(Mandatory)?;
self.expect_keyword(Keyword::REFERENCES)?;
let foreign_table = self.parse_object_name()?;
let referred_columns = self.parse_parenthesized_column_list(Mandatory)?;
let mut on_delete = None;
let mut on_update = None;
loop {
if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
on_delete = Some(self.parse_referential_action()?);
} else if on_update.is_none()
&& self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
{
on_update = Some(self.parse_referential_action()?);
} else {
break;
}
}
Ok(Some(TableConstraint::ForeignKey {
name,
columns,
foreign_table,
referred_columns,
on_delete,
on_update,
}))
}
Token::Word(w) if w.keyword == Keyword::CHECK => {
self.expect_token(&Token::LParen)?;
let expr = Box::new(self.parse_expr()?);
self.expect_token(&Token::RParen)?;
Ok(Some(TableConstraint::Check { name, expr }))
}
unexpected => {
if name.is_some() {
self.expected("PRIMARY, UNIQUE, FOREIGN, or CHECK", unexpected)
} else {
self.prev_token();
Ok(None)
}
}
}
}
pub fn parse_options(&mut self, keyword: Keyword) -> Result<Vec<SqlOption>, ParserError> {
if self.parse_keyword(keyword) {
self.expect_token(&Token::LParen)?;
let options = self.parse_comma_separated(Parser::parse_sql_option)?;
self.expect_token(&Token::RParen)?;
Ok(options)
} else {
Ok(vec![])
}
}
pub fn parse_sql_option(&mut self) -> Result<SqlOption, ParserError> {
let name = self.parse_identifier()?;
self.expect_token(&Token::Eq)?;
let value = self.parse_value()?;
Ok(SqlOption { name, value })
}
pub fn parse_alter(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::TABLE)?;
let _ = self.parse_keyword(Keyword::ONLY);
let table_name = self.parse_object_name()?;
let operation = if self.parse_keyword(Keyword::ADD) {
if let Some(constraint) = self.parse_optional_table_constraint()? {
AlterTableOperation::AddConstraint(constraint)
} else {
let if_not_exists =
self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
if self.parse_keyword(Keyword::PARTITION) {
self.expect_token(&Token::LParen)?;
let partitions = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
AlterTableOperation::AddPartitions {
if_not_exists,
new_partitions: partitions,
}
} else {
let _ = self.parse_keyword(Keyword::COLUMN);
let column_def = self.parse_column_def()?;
AlterTableOperation::AddColumn { column_def }
}
}
} else if self.parse_keyword(Keyword::RENAME) {
if dialect_of!(self is PostgreSqlDialect) && self.parse_keyword(Keyword::CONSTRAINT) {
let old_name = self.parse_identifier()?;
self.expect_keyword(Keyword::TO)?;
let new_name = self.parse_identifier()?;
AlterTableOperation::RenameConstraint { old_name, new_name }
} else if self.parse_keyword(Keyword::TO) {
let table_name = self.parse_object_name()?;
AlterTableOperation::RenameTable { table_name }
} else {
let _ = self.parse_keyword(Keyword::COLUMN);
let old_column_name = self.parse_identifier()?;
self.expect_keyword(Keyword::TO)?;
let new_column_name = self.parse_identifier()?;
AlterTableOperation::RenameColumn {
old_column_name,
new_column_name,
}
}
} else if self.parse_keyword(Keyword::DROP) {
if self.parse_keywords(&[Keyword::IF, Keyword::EXISTS, Keyword::PARTITION]) {
self.expect_token(&Token::LParen)?;
let partitions = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
AlterTableOperation::DropPartitions {
partitions,
if_exists: true,
}
} else if self.parse_keyword(Keyword::PARTITION) {
self.expect_token(&Token::LParen)?;
let partitions = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
AlterTableOperation::DropPartitions {
partitions,
if_exists: false,
}
} else if self.parse_keyword(Keyword::CONSTRAINT) {
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
let name = self.parse_identifier()?;
let cascade = self.parse_keyword(Keyword::CASCADE);
AlterTableOperation::DropConstraint {
if_exists,
name,
cascade,
}
} else {
let _ = self.parse_keyword(Keyword::COLUMN);
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
let column_name = self.parse_identifier()?;
let cascade = self.parse_keyword(Keyword::CASCADE);
AlterTableOperation::DropColumn {
column_name,
if_exists,
cascade,
}
}
} else if self.parse_keyword(Keyword::PARTITION) {
self.expect_token(&Token::LParen)?;
let before = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
self.expect_keyword(Keyword::RENAME)?;
self.expect_keywords(&[Keyword::TO, Keyword::PARTITION])?;
self.expect_token(&Token::LParen)?;
let renames = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
AlterTableOperation::RenamePartitions {
old_partitions: before,
new_partitions: renames,
}
} else if self.parse_keyword(Keyword::CHANGE) {
let _ = self.parse_keyword(Keyword::COLUMN);
let old_name = self.parse_identifier()?;
let new_name = self.parse_identifier()?;
let data_type = self.parse_data_type()?;
let mut options = vec![];
while let Some(option) = self.parse_optional_column_option()? {
options.push(option);
}
AlterTableOperation::ChangeColumn {
old_name,
new_name,
data_type,
options,
}
} else if self.parse_keyword(Keyword::ALTER) {
let _ = self.parse_keyword(Keyword::COLUMN);
let column_name = self.parse_identifier()?;
let is_postgresql = dialect_of!(self is PostgreSqlDialect);
let op = if self.parse_keywords(&[Keyword::SET, Keyword::NOT, Keyword::NULL]) {
AlterColumnOperation::SetNotNull {}
} else if self.parse_keywords(&[Keyword::DROP, Keyword::NOT, Keyword::NULL]) {
AlterColumnOperation::DropNotNull {}
} else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
AlterColumnOperation::SetDefault {
value: self.parse_expr()?,
}
} else if self.parse_keywords(&[Keyword::DROP, Keyword::DEFAULT]) {
AlterColumnOperation::DropDefault {}
} else if self.parse_keywords(&[Keyword::SET, Keyword::DATA, Keyword::TYPE])
|| (is_postgresql && self.parse_keyword(Keyword::TYPE))
{
let data_type = self.parse_data_type()?;
let using = if is_postgresql && self.parse_keyword(Keyword::USING) {
Some(self.parse_expr()?)
} else {
None
};
AlterColumnOperation::SetDataType { data_type, using }
} else {
return self.expected(
"SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE after ALTER COLUMN",
self.peek_token(),
);
};
AlterTableOperation::AlterColumn { column_name, op }
} else {
return self.expected(
"ADD, RENAME, PARTITION or DROP after ALTER TABLE",
self.peek_token(),
);
};
Ok(Statement::AlterTable {
name: table_name,
operation,
})
}
/// Parse a copy statement
pub fn parse_copy(&mut self) -> Result<Statement, ParserError> {
let table_name = self.parse_object_name()?;
let columns = self.parse_parenthesized_column_list(Optional)?;
let to = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::TO]) {
Some(Keyword::FROM) => false,
Some(Keyword::TO) => true,
_ => self.expected("FROM or TO", self.peek_token())?,
};
let target = if self.parse_keyword(Keyword::STDIN) {
CopyTarget::Stdin
} else if self.parse_keyword(Keyword::STDOUT) {
CopyTarget::Stdout
} else if self.parse_keyword(Keyword::PROGRAM) {
CopyTarget::Program {
command: self.parse_literal_string()?,
}
} else {
CopyTarget::File {
filename: self.parse_literal_string()?,
}
};
let _ = self.parse_keyword(Keyword::WITH);
let mut options = vec![];
if self.consume_token(&Token::LParen) {
options = self.parse_comma_separated(Parser::parse_copy_option)?;
self.expect_token(&Token::RParen)?;
}
let mut legacy_options = vec![];
while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option()) {
legacy_options.push(opt);
}
let values = if let CopyTarget::Stdin = target {
self.expect_token(&Token::SemiColon)?;
self.parse_tsv()
} else {
vec![]
};
Ok(Statement::Copy {
table_name,
columns,
to,
target,
options,
legacy_options,
values,
})
}
fn parse_copy_option(&mut self) -> Result<CopyOption, ParserError> {
let ret = match self.parse_one_of_keywords(&[
Keyword::FORMAT,
Keyword::FREEZE,
Keyword::DELIMITER,
Keyword::NULL,
Keyword::HEADER,
Keyword::QUOTE,
Keyword::ESCAPE,
Keyword::FORCE_QUOTE,
Keyword::FORCE_NOT_NULL,
Keyword::FORCE_NULL,
Keyword::ENCODING,
]) {
Some(Keyword::FORMAT) => CopyOption::Format(self.parse_identifier()?),
Some(Keyword::FREEZE) => CopyOption::Freeze(!matches!(
self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
Some(Keyword::FALSE)
)),
Some(Keyword::DELIMITER) => CopyOption::Delimiter(self.parse_literal_char()?),
Some(Keyword::NULL) => CopyOption::Null(self.parse_literal_string()?),
Some(Keyword::HEADER) => CopyOption::Header(!matches!(
self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
Some(Keyword::FALSE)
)),
Some(Keyword::QUOTE) => CopyOption::Quote(self.parse_literal_char()?),
Some(Keyword::ESCAPE) => CopyOption::Escape(self.parse_literal_char()?),
Some(Keyword::FORCE_QUOTE) => {
CopyOption::ForceQuote(self.parse_parenthesized_column_list(Mandatory)?)
}
Some(Keyword::FORCE_NOT_NULL) => {
CopyOption::ForceNotNull(self.parse_parenthesized_column_list(Mandatory)?)
}
Some(Keyword::FORCE_NULL) => {
CopyOption::ForceNull(self.parse_parenthesized_column_list(Mandatory)?)
}
Some(Keyword::ENCODING) => CopyOption::Encoding(self.parse_literal_string()?),
_ => self.expected("option", self.peek_token())?,
};
Ok(ret)
}
fn parse_copy_legacy_option(&mut self) -> Result<CopyLegacyOption, ParserError> {
let ret = match self.parse_one_of_keywords(&[
Keyword::BINARY,
Keyword::DELIMITER,
Keyword::NULL,
Keyword::CSV,
]) {
Some(Keyword::BINARY) => CopyLegacyOption::Binary,
Some(Keyword::DELIMITER) => {
let _ = self.parse_keyword(Keyword::AS); // [ AS ]
CopyLegacyOption::Delimiter(self.parse_literal_char()?)
}
Some(Keyword::NULL) => {
let _ = self.parse_keyword(Keyword::AS); // [ AS ]
CopyLegacyOption::Null(self.parse_literal_string()?)
}
Some(Keyword::CSV) => CopyLegacyOption::Csv({
let mut opts = vec![];
while let Some(opt) =
self.maybe_parse(|parser| parser.parse_copy_legacy_csv_option())
{
opts.push(opt);
}
opts
}),
_ => self.expected("option", self.peek_token())?,
};
Ok(ret)
}
fn parse_copy_legacy_csv_option(&mut self) -> Result<CopyLegacyCsvOption, ParserError> {
let ret = match self.parse_one_of_keywords(&[
Keyword::HEADER,
Keyword::QUOTE,
Keyword::ESCAPE,
Keyword::FORCE,
]) {
Some(Keyword::HEADER) => CopyLegacyCsvOption::Header,
Some(Keyword::QUOTE) => {
let _ = self.parse_keyword(Keyword::AS); // [ AS ]
CopyLegacyCsvOption::Quote(self.parse_literal_char()?)
}
Some(Keyword::ESCAPE) => {
let _ = self.parse_keyword(Keyword::AS); // [ AS ]
CopyLegacyCsvOption::Escape(self.parse_literal_char()?)
}
Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) => {
CopyLegacyCsvOption::ForceNotNull(
self.parse_comma_separated(Parser::parse_identifier)?,
)
}
Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::QUOTE]) => {
CopyLegacyCsvOption::ForceQuote(
self.parse_comma_separated(Parser::parse_identifier)?,
)
}
_ => self.expected("csv option", self.peek_token())?,
};
Ok(ret)
}
fn parse_literal_char(&mut self) -> Result<char, ParserError> {
let s = self.parse_literal_string()?;
if s.len() != 1 {
return parser_err!(format!("Expect a char, found {:?}", s));
}
Ok(s.chars().next().unwrap())
}
/// Parse a tab separated values in
/// COPY payload
pub fn parse_tsv(&mut self) -> Vec<Option<String>> {
self.parse_tab_value()
}
pub fn parse_tab_value(&mut self) -> Vec<Option<String>> {
let mut values = vec![];
let mut content = String::from("");
while let Some(t) = self.next_token_no_skip() {
match t {
Token::Whitespace(Whitespace::Tab) => {
values.push(Some(content.to_string()));
content.clear();
}
Token::Whitespace(Whitespace::Newline) => {
values.push(Some(content.to_string()));
content.clear();
}
Token::Backslash => {
if self.consume_token(&Token::Period) {
return values;
}
if let Token::Word(w) = self.next_token() {
if w.value == "N" {
values.push(None);
}
}
}
_ => {
content.push_str(&t.to_string());
}
}
}
values
}
/// Parse a literal value (numbers, strings, date/time, booleans)
pub fn parse_value(&mut self) -> Result<Value, ParserError> {
match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::TRUE => Ok(Value::Boolean(true)),
Keyword::FALSE => Ok(Value::Boolean(false)),
Keyword::NULL => Ok(Value::Null),
Keyword::NoKeyword if w.quote_style.is_some() => match w.quote_style {
Some('"') => Ok(Value::DoubleQuotedString(w.value)),
Some('\'') => Ok(Value::SingleQuotedString(w.value)),
_ => self.expected("A value?", Token::Word(w))?,
},
_ => self.expected("a concrete value", Token::Word(w)),
},
// The call to n.parse() returns a bigdecimal when the
// bigdecimal feature is enabled, and is otherwise a no-op
// (i.e., it returns the input string).
Token::Number(ref n, l) => match n.parse() {
Ok(n) => Ok(Value::Number(n, l)),
Err(e) => parser_err!(format!("Could not parse '{}' as number: {}", n, e)),
},
Token::SingleQuotedString(ref s) => Ok(Value::SingleQuotedString(s.to_string())),
Token::NationalStringLiteral(ref s) => Ok(Value::NationalStringLiteral(s.to_string())),
Token::HexStringLiteral(ref s) => Ok(Value::HexStringLiteral(s.to_string())),
Token::Placeholder(ref s) => Ok(Value::Placeholder(s.to_string())),
unexpected => self.expected("a value", unexpected),
}
}
pub fn parse_number_value(&mut self) -> Result<Value, ParserError> {
match self.parse_value()? {
v @ Value::Number(_, _) => Ok(v),
_ => {
self.prev_token();
self.expected("literal number", self.peek_token())
}
}
}
/// Parse an unsigned literal integer/long
pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError> {
match self.next_token() {
Token::Number(s, _) => s.parse::<u64>().map_err(|e| {
ParserError::ParserError(format!("Could not parse '{}' as u64: {}", s, e))
}),
unexpected => self.expected("literal int", unexpected),
}
}
/// Parse a literal string
pub fn parse_literal_string(&mut self) -> Result<String, ParserError> {
match self.next_token() {
Token::Word(Word { value, keyword, .. }) if keyword == Keyword::NoKeyword => Ok(value),
Token::SingleQuotedString(s) => Ok(s),
unexpected => self.expected("literal string", unexpected),
}
}
/// Parse a map key string
pub fn parse_map_key(&mut self) -> Result<Expr, ParserError> {
match self.next_token() {
Token::Word(Word { value, keyword, .. }) if keyword == Keyword::NoKeyword => {
if self.peek_token() == Token::LParen {
return self.parse_function(ObjectName(vec![Ident::new(value)]));
}
Ok(Expr::Value(Value::SingleQuotedString(value)))
}
Token::SingleQuotedString(s) => Ok(Expr::Value(Value::SingleQuotedString(s))),
#[cfg(not(feature = "bigdecimal"))]
Token::Number(s, _) => Ok(Expr::Value(Value::Number(s, false))),
#[cfg(feature = "bigdecimal")]
Token::Number(s, _) => Ok(Expr::Value(Value::Number(s.parse().unwrap(), false))),
unexpected => self.expected("literal string, number or function", unexpected),
}
}
/// Parse a SQL datatype (in the context of a CREATE TABLE statement for example)
pub fn parse_data_type(&mut self) -> Result<DataType, ParserError> {
let mut data = match self.next_token() {
Token::Word(w) => match w.keyword {
Keyword::BOOLEAN => Ok(DataType::Boolean),
Keyword::FLOAT => Ok(DataType::Float(self.parse_optional_precision()?)),
Keyword::REAL => Ok(DataType::Real),
Keyword::DOUBLE => {
let _ = self.parse_keyword(Keyword::PRECISION);
Ok(DataType::Double)
}
Keyword::TINYINT => {
let optional_precision = self.parse_optional_precision();
if self.parse_keyword(Keyword::UNSIGNED) {
Ok(DataType::UnsignedTinyInt(optional_precision?))
} else {
Ok(DataType::TinyInt(optional_precision?))
}
}
Keyword::SMALLINT => {
let optional_precision = self.parse_optional_precision();
if self.parse_keyword(Keyword::UNSIGNED) {
Ok(DataType::UnsignedSmallInt(optional_precision?))
} else {
Ok(DataType::SmallInt(optional_precision?))
}
}
Keyword::INT | Keyword::INTEGER => {
let optional_precision = self.parse_optional_precision();
if self.parse_keyword(Keyword::UNSIGNED) {
Ok(DataType::UnsignedInt(optional_precision?))
} else {
Ok(DataType::Int(optional_precision?))
}
}
Keyword::BIGINT => {
let optional_precision = self.parse_optional_precision();
if self.parse_keyword(Keyword::UNSIGNED) {
Ok(DataType::UnsignedBigInt(optional_precision?))
} else {
Ok(DataType::BigInt(optional_precision?))
}
}
Keyword::VARCHAR => Ok(DataType::Varchar(self.parse_optional_precision()?)),
Keyword::NVARCHAR => Ok(DataType::Nvarchar(self.parse_optional_precision()?)),
Keyword::CHAR | Keyword::CHARACTER => {
if self.parse_keyword(Keyword::VARYING) {
Ok(DataType::Varchar(self.parse_optional_precision()?))
} else {
Ok(DataType::Char(self.parse_optional_precision()?))
}
}
Keyword::UUID => Ok(DataType::Uuid),
Keyword::DATE => Ok(DataType::Date),
Keyword::TIMESTAMP => {
// TBD: we throw away "with/without timezone" information
if self.parse_keyword(Keyword::WITH) || self.parse_keyword(Keyword::WITHOUT) {
self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
}
Ok(DataType::Timestamp)
}
Keyword::TIME => {
// TBD: we throw away "with/without timezone" information
if self.parse_keyword(Keyword::WITH) || self.parse_keyword(Keyword::WITHOUT) {
self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
}
Ok(DataType::Time)
}
// Interval types can be followed by a complicated interval
// qualifier that we don't currently support. See
// parse_interval_literal for a taste.
Keyword::INTERVAL => Ok(DataType::Interval),
Keyword::REGCLASS => Ok(DataType::Regclass),
Keyword::STRING => Ok(DataType::String),
Keyword::TEXT => Ok(DataType::Text),
Keyword::BYTEA => Ok(DataType::Bytea),
Keyword::NUMERIC | Keyword::DECIMAL | Keyword::DEC => {
let (precision, scale) = self.parse_optional_precision_scale()?;
Ok(DataType::Decimal(precision, scale))
}
Keyword::ENUM => Ok(DataType::Enum(self.parse_string_values()?)),
Keyword::SET => Ok(DataType::Set(self.parse_string_values()?)),
_ => {
self.prev_token();
let type_name = self.parse_object_name()?;
Ok(DataType::Custom(type_name))
}
},
unexpected => self.expected("a data type name", unexpected),
}?;
// Parse array data types. Note: this is postgresql-specific
while self.consume_token(&Token::LBracket) {
self.expect_token(&Token::RBracket)?;
data = DataType::Array(Box::new(data))
}
Ok(data)
}
pub fn parse_string_values(&mut self) -> Result<Vec<String>, ParserError> {
self.expect_token(&Token::LParen)?;
let mut values = Vec::new();
loop {
match self.next_token() {
Token::SingleQuotedString(value) => values.push(value),
unexpected => self.expected("a string", unexpected)?,
}
match self.next_token() {
Token::Comma => (),
Token::RParen => break,
unexpected => self.expected(", or }", unexpected)?,
}
}
Ok(values)
}
/// Parse `AS identifier` (or simply `identifier` if it's not a reserved keyword)
/// Some examples with aliases: `SELECT 1 foo`, `SELECT COUNT(*) AS cnt`,
/// `SELECT ... FROM t1 foo, t2 bar`, `SELECT ... FROM (...) AS bar`
pub fn parse_optional_alias(
&mut self,
reserved_kwds: &[Keyword],
) -> Result<Option<Ident>, ParserError> {
let after_as = self.parse_keyword(Keyword::AS);
match self.next_token() {
// Accept any identifier after `AS` (though many dialects have restrictions on
// keywords that may appear here). If there's no `AS`: don't parse keywords,
// which may start a construct allowed in this position, to be parsed as aliases.
// (For example, in `FROM t1 JOIN` the `JOIN` will always be parsed as a keyword,
// not an alias.)
Token::Word(w) if after_as || !reserved_kwds.contains(&w.keyword) => {
Ok(Some(w.to_ident()))
}
// MSSQL supports single-quoted strings as aliases for columns
// We accept them as table aliases too, although MSSQL does not.
//
// Note, that this conflicts with an obscure rule from the SQL
// standard, which we don't implement:
// https://crate.io/docs/sql-99/en/latest/chapters/07.html#character-string-literal-s
// "[Obscure Rule] SQL allows you to break a long <character
// string literal> up into two or more smaller <character string
// literal>s, split by a <separator> that includes a newline
// character. When it sees such a <literal>, your DBMS will
// ignore the <separator> and treat the multiple strings as
// a single <literal>."
Token::SingleQuotedString(s) => Ok(Some(Ident::with_quote('\'', s))),
not_an_ident => {
if after_as {
return self.expected("an identifier after AS", not_an_ident);
}
self.prev_token();
Ok(None) // no alias found
}
}
}
/// Parse `AS identifier` when the AS is describing a table-valued object,
/// like in `... FROM generate_series(1, 10) AS t (col)`. In this case
/// the alias is allowed to optionally name the columns in the table, in
/// addition to the table itself.
pub fn parse_optional_table_alias(
&mut self,
reserved_kwds: &[Keyword],
) -> Result<Option<TableAlias>, ParserError> {
match self.parse_optional_alias(reserved_kwds)? {
Some(name) => {
let columns = self.parse_parenthesized_column_list(Optional)?;
Ok(Some(TableAlias { name, columns }))
}
None => Ok(None),
}
}
/// Parse a possibly qualified, possibly quoted identifier, e.g.
/// `foo` or `myschema."table"
pub fn parse_object_name(&mut self) -> Result<ObjectName, ParserError> {
let mut idents = vec![];
loop {
idents.push(self.parse_identifier()?);
if !self.consume_token(&Token::Period) {
break;
}
}
Ok(ObjectName(idents))
}
/// Parse identifiers strictly i.e. don't parse keywords
pub fn parse_identifiers_non_keywords(&mut self) -> Result<Vec<Ident>, ParserError> {
let mut idents = vec![];
loop {
match self.peek_token() {
Token::Word(w) => {
if w.keyword != Keyword::NoKeyword {
break;
}
idents.push(w.to_ident());
}
Token::EOF | Token::Eq => break,
_ => {}
}
self.next_token();
}
Ok(idents)
}
/// Parse identifiers
pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
let mut idents = vec![];
loop {
match self.next_token() {
Token::Word(w) => {
idents.push(w.to_ident());
}
Token::EOF => break,
_ => {}
}
}
Ok(idents)
}
/// Parse a simple one-word identifier (possibly quoted, possibly a keyword)
pub fn parse_identifier(&mut self) -> Result<Ident, ParserError> {
match self.next_token() {
Token::Word(w) => Ok(w.to_ident()),
Token::SingleQuotedString(s) => Ok(Ident::with_quote('\'', s)),
unexpected => self.expected("identifier", unexpected),
}
}
/// Parse a parenthesized comma-separated list of unqualified, possibly quoted identifiers
pub fn parse_parenthesized_column_list(
&mut self,
optional: IsOptional,
) -> Result<Vec<Ident>, ParserError> {
if self.consume_token(&Token::LParen) {
let cols = self.parse_comma_separated(Parser::parse_identifier)?;
self.expect_token(&Token::RParen)?;
Ok(cols)
} else if optional == Optional {
Ok(vec![])
} else {
self.expected("a list of columns in parentheses", self.peek_token())
}
}
pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError> {
if self.consume_token(&Token::LParen) {
let n = self.parse_literal_uint()?;
self.expect_token(&Token::RParen)?;
Ok(Some(n))
} else {
Ok(None)
}
}
pub fn parse_optional_precision_scale(
&mut self,
) -> Result<(Option<u64>, Option<u64>), ParserError> {
if self.consume_token(&Token::LParen) {
let n = self.parse_literal_uint()?;
let scale = if self.consume_token(&Token::Comma) {
Some(self.parse_literal_uint()?)
} else {
None
};
self.expect_token(&Token::RParen)?;
Ok((Some(n), scale))
} else {
Ok((None, None))
}
}
pub fn parse_delete(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::FROM)?;
let table_name = self.parse_object_name()?;
let selection = if self.parse_keyword(Keyword::WHERE) {
Some(self.parse_expr()?)
} else {
None
};
Ok(Statement::Delete {
table_name,
selection,
})
}
// KILL [CONNECTION | QUERY | MUTATION] processlist_id
pub fn parse_kill(&mut self) -> Result<Statement, ParserError> {
let modifier_keyword =
self.parse_one_of_keywords(&[Keyword::CONNECTION, Keyword::QUERY, Keyword::MUTATION]);
let id = self.parse_literal_uint()?;
let modifier = match modifier_keyword {
Some(Keyword::CONNECTION) => Some(KillType::Connection),
Some(Keyword::QUERY) => Some(KillType::Query),
Some(Keyword::MUTATION) => {
if dialect_of!(self is ClickHouseDialect | GenericDialect) {
Some(KillType::Mutation)
} else {
self.expected(
"Unsupported type for KILL, allowed: CONNECTION | QUERY",
self.peek_token(),
)?
}
}
_ => None,
};
Ok(Statement::Kill { modifier, id })
}
pub fn parse_explain(&mut self, describe_alias: bool) -> Result<Statement, ParserError> {
let analyze = self.parse_keyword(Keyword::ANALYZE);
let verbose = self.parse_keyword(Keyword::VERBOSE);
if let Some(statement) = self.maybe_parse(|parser| parser.parse_statement()) {
Ok(Statement::Explain {
describe_alias,
analyze,
verbose,
statement: Box::new(statement),
})
} else {
let table_name = self.parse_object_name()?;
Ok(Statement::ExplainTable {
describe_alias,
table_name,
})
}
}
/// Parse a query expression, i.e. a `SELECT` statement optionally
/// preceeded with some `WITH` CTE declarations and optionally followed
/// by `ORDER BY`. Unlike some other parse_... methods, this one doesn't
/// expect the initial keyword to be already consumed
pub fn parse_query(&mut self) -> Result<Query, ParserError> {
let with = if self.parse_keyword(Keyword::WITH) {
Some(With {
recursive: self.parse_keyword(Keyword::RECURSIVE),
cte_tables: self.parse_comma_separated(Parser::parse_cte)?,
})
} else {
None
};
if !self.parse_keyword(Keyword::INSERT) {
let body = self.parse_query_body(0)?;
let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_order_by_expr)?
} else {
vec![]
};
let mut limit = None;
let mut offset = None;
for _x in 0..2 {
if limit.is_none() && self.parse_keyword(Keyword::LIMIT) {
limit = self.parse_limit()?
}
if offset.is_none() && self.parse_keyword(Keyword::OFFSET) {
offset = Some(self.parse_offset()?)
}
if offset.is_none() && self.consume_token(&Token::Comma) {
// mysql style LIMIT 10, offset 5
offset = Some(self.parse_offset()?)
}
}
let fetch = if self.parse_keyword(Keyword::FETCH) {
Some(self.parse_fetch()?)
} else {
None
};
let lock = if self.parse_keyword(Keyword::FOR) {
Some(self.parse_lock()?)
} else {
None
};
Ok(Query {
with,
body,
order_by,
limit,
offset,
fetch,
lock,
})
} else {
let insert = self.parse_insert()?;
Ok(Query {
with,
body: SetExpr::Insert(insert),
limit: None,
order_by: vec![],
offset: None,
fetch: None,
lock: None,
})
}
}
/// Parse a CTE (`alias [( col1, col2, ... )] AS (subquery)`)
pub fn parse_cte(&mut self) -> Result<Cte, ParserError> {
let name = self.parse_identifier()?;
let mut cte = if self.parse_keyword(Keyword::AS) {
self.expect_token(&Token::LParen)?;
let query = self.parse_query()?;
self.expect_token(&Token::RParen)?;
let alias = TableAlias {
name,
columns: vec![],
};
Cte {
alias,
query,
from: None,
}
} else {
let columns = self.parse_parenthesized_column_list(Optional)?;
self.expect_keyword(Keyword::AS)?;
self.expect_token(&Token::LParen)?;
let query = self.parse_query()?;
self.expect_token(&Token::RParen)?;
let alias = TableAlias { name, columns };
Cte {
alias,
query,
from: None,
}
};
if self.parse_keyword(Keyword::FROM) {
cte.from = Some(self.parse_identifier()?);
}
Ok(cte)
}
/// Parse a "query body", which is an expression with roughly the
/// following grammar:
/// ```text
/// query_body ::= restricted_select | '(' subquery ')' | set_operation
/// restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ]
/// subquery ::= query_body [ order_by_limit ]
/// set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_body
/// ```
pub fn parse_query_body(&mut self, precedence: u8) -> Result<SetExpr, ParserError> {
// We parse the expression using a Pratt parser, as in `parse_expr()`.
// Start by parsing a restricted SELECT or a `(subquery)`:
let mut expr = if self.parse_keyword(Keyword::SELECT) {
SetExpr::Select(Box::new(self.parse_select()?))
} else if self.consume_token(&Token::LParen) {
// CTEs are not allowed here, but the parser currently accepts them
let subquery = self.parse_query()?;
self.expect_token(&Token::RParen)?;
SetExpr::Query(Box::new(subquery))
} else if self.parse_keyword(Keyword::VALUES) {
SetExpr::Values(self.parse_values()?)
} else {
return self.expected(
"SELECT, VALUES, or a subquery in the query body",
self.peek_token(),
);
};
loop {
// The query can be optionally followed by a set operator:
let op = self.parse_set_operator(&self.peek_token());
let next_precedence = match op {
// UNION and EXCEPT have the same binding power and evaluate left-to-right
Some(SetOperator::Union) | Some(SetOperator::Except) => 10,
// INTERSECT has higher precedence than UNION/EXCEPT
Some(SetOperator::Intersect) => 20,
// Unexpected token or EOF => stop parsing the query body
None => break,
};
if precedence >= next_precedence {
break;
}
self.next_token(); // skip past the set operator
expr = SetExpr::SetOperation {
left: Box::new(expr),
op: op.unwrap(),
all: self.parse_keyword(Keyword::ALL),
right: Box::new(self.parse_query_body(next_precedence)?),
};
}
Ok(expr)
}
pub fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator> {
match token {
Token::Word(w) if w.keyword == Keyword::UNION => Some(SetOperator::Union),
Token::Word(w) if w.keyword == Keyword::EXCEPT => Some(SetOperator::Except),
Token::Word(w) if w.keyword == Keyword::INTERSECT => Some(SetOperator::Intersect),
_ => None,
}
}
/// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`),
/// assuming the initial `SELECT` was already consumed
pub fn parse_select(&mut self) -> Result<Select, ParserError> {
let distinct = self.parse_all_or_distinct()?;
let top = if self.parse_keyword(Keyword::TOP) {
Some(self.parse_top()?)
} else {
None
};
let projection = self.parse_comma_separated(Parser::parse_select_item)?;
let into = if self.parse_keyword(Keyword::INTO) {
let temporary = self
.parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
.is_some();
let unlogged = self.parse_keyword(Keyword::UNLOGGED);
let name = self.parse_object_name()?;
Some(SelectInto {
temporary,
unlogged,
name,
})
} else {
None
};
// Note that for keywords to be properly handled here, they need to be
// added to `RESERVED_FOR_COLUMN_ALIAS` / `RESERVED_FOR_TABLE_ALIAS`,
// otherwise they may be parsed as an alias as part of the `projection`
// or `from`.
let from = if self.parse_keyword(Keyword::FROM) {
self.parse_comma_separated(Parser::parse_table_and_joins)?
} else {
vec![]
};
let mut lateral_views = vec![];
loop {
if self.parse_keywords(&[Keyword::LATERAL, Keyword::VIEW]) {
let outer = self.parse_keyword(Keyword::OUTER);
let lateral_view = self.parse_expr()?;
let lateral_view_name = self.parse_object_name()?;
let lateral_col_alias = self
.parse_comma_separated(|parser| {
parser.parse_optional_alias(&[
Keyword::WHERE,
Keyword::GROUP,
Keyword::CLUSTER,
Keyword::HAVING,
Keyword::LATERAL,
]) // This couldn't possibly be a bad idea
})?
.into_iter()
.flatten()
.collect();
lateral_views.push(LateralView {
lateral_view,
lateral_view_name,
lateral_col_alias,
outer,
});
} else {
break;
}
}
let selection = if self.parse_keyword(Keyword::WHERE) {
Some(self.parse_expr()?)
} else {
None
};
let group_by = if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_group_by_expr)?
} else {
vec![]
};
let cluster_by = if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let distribute_by = if self.parse_keywords(&[Keyword::DISTRIBUTE, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let sort_by = if self.parse_keywords(&[Keyword::SORT, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let having = if self.parse_keyword(Keyword::HAVING) {
Some(self.parse_expr()?)
} else {
None
};
let qualify = if self.parse_keyword(Keyword::QUALIFY) {
Some(self.parse_expr()?)
} else {
None
};
Ok(Select {
distinct,
top,
projection,
into,
from,
lateral_views,
selection,
group_by,
cluster_by,
distribute_by,
sort_by,
having,
qualify,
})
}
pub fn parse_set(&mut self) -> Result<Statement, ParserError> {
let modifier =
self.parse_one_of_keywords(&[Keyword::SESSION, Keyword::LOCAL, Keyword::HIVEVAR]);
if let Some(Keyword::HIVEVAR) = modifier {
self.expect_token(&Token::Colon)?;
} else if self.parse_keyword(Keyword::ROLE) {
let role_name = if self.parse_keyword(Keyword::NONE) {
None
} else {
Some(self.parse_identifier()?)
};
return Ok(Statement::SetRole {
local: modifier == Some(Keyword::LOCAL),
session: modifier == Some(Keyword::SESSION),
role_name,
});
}
let variable = self.parse_identifier()?;
if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
let mut values = vec![];
loop {
let token = self.peek_token();
let value = match (self.parse_value(), token) {
(Ok(value), _) => SetVariableValue::Literal(value),
(Err(_), Token::Word(ident)) => SetVariableValue::Ident(ident.to_ident()),
(Err(_), unexpected) => self.expected("variable value", unexpected)?,
};
values.push(value);
if self.consume_token(&Token::Comma) {
continue;
}
return Ok(Statement::SetVariable {
local: modifier == Some(Keyword::LOCAL),
hivevar: Some(Keyword::HIVEVAR) == modifier,
variable,
value: values,
});
}
} else if variable.value == "CHARACTERISTICS" {
self.expect_keywords(&[Keyword::AS, Keyword::TRANSACTION])?;
Ok(Statement::SetTransaction {
modes: self.parse_transaction_modes()?,
snapshot: None,
session: true,
})
} else if variable.value == "TRANSACTION" && modifier.is_none() {
if self.parse_keyword(Keyword::SNAPSHOT) {
let snaphot_id = self.parse_value()?;
return Ok(Statement::SetTransaction {
modes: vec![],
snapshot: Some(snaphot_id),
session: false,
});
}
Ok(Statement::SetTransaction {
modes: self.parse_transaction_modes()?,
snapshot: None,
session: false,
})
} else {
self.expected("equals sign or TO", self.peek_token())
}
}
pub fn parse_show(&mut self) -> Result<Statement, ParserError> {
if self
.parse_one_of_keywords(&[
Keyword::EXTENDED,
Keyword::FULL,
Keyword::COLUMNS,
Keyword::FIELDS,
])
.is_some()
{
self.prev_token();
Ok(self.parse_show_columns()?)
} else if self.parse_one_of_keywords(&[Keyword::CREATE]).is_some() {
Ok(self.parse_show_create()?)
} else {
Ok(Statement::ShowVariable {
variable: self.parse_identifiers()?,
})
}
}
pub fn parse_show_create(&mut self) -> Result<Statement, ParserError> {
let obj_type = match self.expect_one_of_keywords(&[
Keyword::TABLE,
Keyword::TRIGGER,
Keyword::FUNCTION,
Keyword::PROCEDURE,
Keyword::EVENT,
])? {
Keyword::TABLE => Ok(ShowCreateObject::Table),
Keyword::TRIGGER => Ok(ShowCreateObject::Trigger),
Keyword::FUNCTION => Ok(ShowCreateObject::Function),
Keyword::PROCEDURE => Ok(ShowCreateObject::Procedure),
Keyword::EVENT => Ok(ShowCreateObject::Event),
keyword => Err(ParserError::ParserError(format!(
"Unable to map keyword to ShowCreateObject: {:?}",
keyword
))),
}?;
let obj_name = self.parse_object_name()?;
Ok(Statement::ShowCreate { obj_type, obj_name })
}
pub fn parse_show_columns(&mut self) -> Result<Statement, ParserError> {
let extended = self.parse_keyword(Keyword::EXTENDED);
let full = self.parse_keyword(Keyword::FULL);
self.expect_one_of_keywords(&[Keyword::COLUMNS, Keyword::FIELDS])?;
self.expect_one_of_keywords(&[Keyword::FROM, Keyword::IN])?;
let table_name = self.parse_object_name()?;
// MySQL also supports FROM <database> here. In other words, MySQL
// allows both FROM <table> FROM <database> and FROM <database>.<table>,
// while we only support the latter for now.
let filter = self.parse_show_statement_filter()?;
Ok(Statement::ShowColumns {
extended,
full,
table_name,
filter,
})
}
pub fn parse_show_statement_filter(
&mut self,
) -> Result<Option<ShowStatementFilter>, ParserError> {
if self.parse_keyword(Keyword::LIKE) {
Ok(Some(ShowStatementFilter::Like(
self.parse_literal_string()?,
)))
} else if self.parse_keyword(Keyword::ILIKE) {
Ok(Some(ShowStatementFilter::ILike(
self.parse_literal_string()?,
)))
} else if self.parse_keyword(Keyword::WHERE) {
Ok(Some(ShowStatementFilter::Where(self.parse_expr()?)))
} else {
Ok(None)
}
}
pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError> {
let relation = self.parse_table_factor()?;
// Note that for keywords to be properly handled here, they need to be
// added to `RESERVED_FOR_TABLE_ALIAS`, otherwise they may be parsed as
// a table alias.
let mut joins = vec![];
loop {
let join = if self.parse_keyword(Keyword::CROSS) {
let join_operator = if self.parse_keyword(Keyword::JOIN) {
JoinOperator::CrossJoin
} else if self.parse_keyword(Keyword::APPLY) {
// MSSQL extension, similar to CROSS JOIN LATERAL
JoinOperator::CrossApply
} else {
return self.expected("JOIN or APPLY after CROSS", self.peek_token());
};
Join {
relation: self.parse_table_factor()?,
join_operator,
}
} else if self.parse_keyword(Keyword::OUTER) {
// MSSQL extension, similar to LEFT JOIN LATERAL .. ON 1=1
self.expect_keyword(Keyword::APPLY)?;
Join {
relation: self.parse_table_factor()?,
join_operator: JoinOperator::OuterApply,
}
} else {
let natural = self.parse_keyword(Keyword::NATURAL);
let peek_keyword = if let Token::Word(w) = self.peek_token() {
w.keyword
} else {
Keyword::NoKeyword
};
let join_operator_type = match peek_keyword {
Keyword::INNER | Keyword::JOIN => {
let _ = self.parse_keyword(Keyword::INNER);
self.expect_keyword(Keyword::JOIN)?;
JoinOperator::Inner
}
kw @ Keyword::LEFT | kw @ Keyword::RIGHT | kw @ Keyword::FULL => {
let _ = self.next_token();
let _ = self.parse_keyword(Keyword::OUTER);
self.expect_keyword(Keyword::JOIN)?;
match kw {
Keyword::LEFT => JoinOperator::LeftOuter,
Keyword::RIGHT => JoinOperator::RightOuter,
Keyword::FULL => JoinOperator::FullOuter,
_ => unreachable!(),
}
}
Keyword::OUTER => {
return self.expected("LEFT, RIGHT, or FULL", self.peek_token());
}
_ if natural => {
return self.expected("a join type after NATURAL", self.peek_token());
}
_ => break,
};
let relation = self.parse_table_factor()?;
let join_constraint = self.parse_join_constraint(natural)?;
Join {
relation,
join_operator: join_operator_type(join_constraint),
}
};
joins.push(join);
}
Ok(TableWithJoins { relation, joins })
}
/// A table name or a parenthesized subquery, followed by optional `[AS] alias`
pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError> {
if self.parse_keyword(Keyword::LATERAL) {
// LATERAL must always be followed by a subquery.
if !self.consume_token(&Token::LParen) {
self.expected("subquery after LATERAL", self.peek_token())?;
}
self.parse_derived_table_factor(Lateral)
} else if self.parse_keyword(Keyword::TABLE) {
// parse table function (SELECT * FROM TABLE (<expr>) [ AS <alias> ])
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
Ok(TableFactor::TableFunction { expr, alias })
} else if self.consume_token(&Token::LParen) {
// A left paren introduces either a derived table (i.e., a subquery)
// or a nested join. It's nearly impossible to determine ahead of
// time which it is... so we just try to parse both.
//
// Here's an example that demonstrates the complexity:
// /-------------------------------------------------------\
// | /-----------------------------------\ |
// SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) )
// ^ ^ ^ ^
// | | | |
// | | | |
// | | | (4) belongs to a SetExpr::Query inside the subquery
// | | (3) starts a derived table (subquery)
// | (2) starts a nested join
// (1) an additional set of parens around a nested join
//
// If the recently consumed '(' starts a derived table, the call to
// `parse_derived_table_factor` below will return success after parsing the
// subquery, followed by the closing ')', and the alias of the derived table.
// In the example above this is case (3).
return_ok_if_some!(
self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))
);
// A parsing error from `parse_derived_table_factor` indicates that the '(' we've
// recently consumed does not start a derived table (cases 1, 2, or 4).
// `maybe_parse` will ignore such an error and rewind to be after the opening '('.
// Inside the parentheses we expect to find an (A) table factor
// followed by some joins or (B) another level of nesting.
let mut table_and_joins = self.parse_table_and_joins()?;
#[allow(clippy::if_same_then_else)]
if !table_and_joins.joins.is_empty() {
self.expect_token(&Token::RParen)?;
Ok(TableFactor::NestedJoin(Box::new(table_and_joins))) // (A)
} else if let TableFactor::NestedJoin(_) = &table_and_joins.relation {
// (B): `table_and_joins` (what we found inside the parentheses)
// is a nested join `(foo JOIN bar)`, not followed by other joins.
self.expect_token(&Token::RParen)?;
Ok(TableFactor::NestedJoin(Box::new(table_and_joins)))
} else if dialect_of!(self is SnowflakeDialect | GenericDialect) {
// Dialect-specific behavior: Snowflake diverges from the
// standard and from most of the other implementations by
// allowing extra parentheses not only around a join (B), but
// around lone table names (e.g. `FROM (mytable [AS alias])`)
// and around derived tables (e.g. `FROM ((SELECT ...)
// [AS alias])`) as well.
self.expect_token(&Token::RParen)?;
if let Some(outer_alias) =
self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?
{
// Snowflake also allows specifying an alias *after* parens
// e.g. `FROM (mytable) AS alias`
match &mut table_and_joins.relation {
TableFactor::Derived { alias, .. }
| TableFactor::Table { alias, .. }
| TableFactor::TableFunction { alias, .. } => {
// but not `FROM (mytable AS alias1) AS alias2`.
if let Some(inner_alias) = alias {
return Err(ParserError::ParserError(format!(
"duplicate alias {}",
inner_alias
)));
}
// Act as if the alias was specified normally next
// to the table name: `(mytable) AS alias` ->
// `(mytable AS alias)`
alias.replace(outer_alias);
}
TableFactor::NestedJoin(_) => unreachable!(),
};
}
// Do not store the extra set of parens in the AST
Ok(table_and_joins.relation)
} else {
// The SQL spec prohibits derived tables and bare tables from
// appearing alone in parentheses (e.g. `FROM (mytable)`)
self.expected("joined table", self.peek_token())
}
} else {
let name = self.parse_object_name()?;
// Postgres, MSSQL: table-valued functions:
let args = if self.consume_token(&Token::LParen) {
self.parse_optional_args()?
} else {
vec![]
};
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
// MSSQL-specific table hints:
let mut with_hints = vec![];
if self.parse_keyword(Keyword::WITH) {
if self.consume_token(&Token::LParen) {
with_hints = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
} else {
// rewind, as WITH may belong to the next statement's CTE
self.prev_token();
}
};
Ok(TableFactor::Table {
name,
alias,
args,
with_hints,
})
}
}
pub fn parse_derived_table_factor(
&mut self,
lateral: IsLateral,
) -> Result<TableFactor, ParserError> {
let subquery = Box::new(self.parse_query()?);
self.expect_token(&Token::RParen)?;
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
Ok(TableFactor::Derived {
lateral: match lateral {
Lateral => true,
NotLateral => false,
},
subquery,
alias,
})
}
pub fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint, ParserError> {
if natural {
Ok(JoinConstraint::Natural)
} else if self.parse_keyword(Keyword::ON) {
let constraint = self.parse_expr()?;
Ok(JoinConstraint::On(constraint))
} else if self.parse_keyword(Keyword::USING) {
let columns = self.parse_parenthesized_column_list(Mandatory)?;
Ok(JoinConstraint::Using(columns))
} else {
Ok(JoinConstraint::None)
//self.expected("ON, or USING after JOIN", self.peek_token())
}
}
/// Parse a GRANT statement.
pub fn parse_grant(&mut self) -> Result<Statement, ParserError> {
let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
self.expect_keyword(Keyword::TO)?;
let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
let with_grant_option =
self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
let granted_by = self
.parse_keywords(&[Keyword::GRANTED, Keyword::BY])
.then(|| self.parse_identifier().unwrap());
Ok(Statement::Grant {
privileges,
objects,
grantees,
with_grant_option,
granted_by,
})
}
pub fn parse_grant_revoke_privileges_objects(
&mut self,
) -> Result<(Privileges, GrantObjects), ParserError> {
let privileges = if self.parse_keyword(Keyword::ALL) {
Privileges::All {
with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
}
} else {
let (actions, err): (Vec<_>, Vec<_>) = self
.parse_comma_separated(Parser::parse_grant_permission)?
.into_iter()
.map(|(kw, columns)| match kw {
Keyword::DELETE => Ok(Action::Delete),
Keyword::INSERT => Ok(Action::Insert { columns }),
Keyword::REFERENCES => Ok(Action::References { columns }),
Keyword::SELECT => Ok(Action::Select { columns }),
Keyword::TRIGGER => Ok(Action::Trigger),
Keyword::TRUNCATE => Ok(Action::Truncate),
Keyword::UPDATE => Ok(Action::Update { columns }),
Keyword::USAGE => Ok(Action::Usage),
Keyword::CONNECT => Ok(Action::Connect),
Keyword::CREATE => Ok(Action::Create),
Keyword::EXECUTE => Ok(Action::Execute),
Keyword::TEMPORARY => Ok(Action::Temporary),
// This will cover all future added keywords to
// parse_grant_permission and unhandled in this
// match
_ => Err(kw),
})
.partition(Result::is_ok);
if !err.is_empty() {
let errors: Vec<Keyword> = err.into_iter().filter_map(|x| x.err()).collect();
return Err(ParserError::ParserError(format!(
"INTERNAL ERROR: GRANT/REVOKE unexpected keyword(s) - {:?}",
errors
)));
}
let act = actions.into_iter().filter_map(|x| x.ok()).collect();
Privileges::Actions(act)
};
self.expect_keyword(Keyword::ON)?;
let objects = if self.parse_keywords(&[
Keyword::ALL,
Keyword::TABLES,
Keyword::IN,
Keyword::SCHEMA,
]) {
GrantObjects::AllTablesInSchema {
schemas: self.parse_comma_separated(Parser::parse_object_name)?,
}
} else if self.parse_keywords(&[
Keyword::ALL,
Keyword::SEQUENCES,
Keyword::IN,
Keyword::SCHEMA,
]) {
GrantObjects::AllSequencesInSchema {
schemas: self.parse_comma_separated(Parser::parse_object_name)?,
}
} else {
let object_type =
self.parse_one_of_keywords(&[Keyword::SEQUENCE, Keyword::SCHEMA, Keyword::TABLE]);
let objects = self.parse_comma_separated(Parser::parse_object_name);
match object_type {
Some(Keyword::SCHEMA) => GrantObjects::Schemas(objects?),
Some(Keyword::SEQUENCE) => GrantObjects::Sequences(objects?),
Some(Keyword::TABLE) | None => GrantObjects::Tables(objects?),
_ => unreachable!(),
}
};
Ok((privileges, objects))
}
pub fn parse_grant_permission(&mut self) -> Result<(Keyword, Option<Vec<Ident>>), ParserError> {
if let Some(kw) = self.parse_one_of_keywords(&[
Keyword::CONNECT,
Keyword::CREATE,
Keyword::DELETE,
Keyword::EXECUTE,
Keyword::INSERT,
Keyword::REFERENCES,
Keyword::SELECT,
Keyword::TEMPORARY,
Keyword::TRIGGER,
Keyword::TRUNCATE,
Keyword::UPDATE,
Keyword::USAGE,
]) {
let columns = match kw {
Keyword::INSERT | Keyword::REFERENCES | Keyword::SELECT | Keyword::UPDATE => {
let columns = self.parse_parenthesized_column_list(Optional)?;
if columns.is_empty() {
None
} else {
Some(columns)
}
}
_ => None,
};
Ok((kw, columns))
} else {
self.expected("a privilege keyword", self.peek_token())?
}
}
/// Parse a REVOKE statement
pub fn parse_revoke(&mut self) -> Result<Statement, ParserError> {
let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
self.expect_keyword(Keyword::FROM)?;
let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
let granted_by = self
.parse_keywords(&[Keyword::GRANTED, Keyword::BY])
.then(|| self.parse_identifier().unwrap());
let cascade = self.parse_keyword(Keyword::CASCADE);
let restrict = self.parse_keyword(Keyword::RESTRICT);
if cascade && restrict {
return parser_err!("Cannot specify both CASCADE and RESTRICT in REVOKE");
}
Ok(Statement::Revoke {
privileges,
objects,
grantees,
granted_by,
cascade,
})
}
/// Parse an INSERT statement
pub fn parse_insert(&mut self) -> Result<Statement, ParserError> {
let or = if !dialect_of!(self is SQLiteDialect) {
None
} else if self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]) {
Some(SqliteOnConflict::Replace)
} else if self.parse_keywords(&[Keyword::OR, Keyword::ROLLBACK]) {
Some(SqliteOnConflict::Rollback)
} else if self.parse_keywords(&[Keyword::OR, Keyword::ABORT]) {
Some(SqliteOnConflict::Abort)
} else if self.parse_keywords(&[Keyword::OR, Keyword::FAIL]) {
Some(SqliteOnConflict::Fail)
} else if self.parse_keywords(&[Keyword::OR, Keyword::IGNORE]) {
Some(SqliteOnConflict::Ignore)
} else if self.parse_keyword(Keyword::REPLACE) {
Some(SqliteOnConflict::Replace)
} else {
None
};
let action = self.expect_one_of_keywords(&[Keyword::INTO, Keyword::OVERWRITE])?;
let overwrite = action == Keyword::OVERWRITE;
let local = self.parse_keyword(Keyword::LOCAL);
if self.parse_keyword(Keyword::DIRECTORY) {
let path = self.parse_literal_string()?;
let file_format = if self.parse_keywords(&[Keyword::STORED, Keyword::AS]) {
Some(self.parse_file_format()?)
} else {
None
};
let source = Box::new(self.parse_query()?);
Ok(Statement::Directory {
local,
path,
overwrite,
file_format,
source,
})
} else {
// Hive lets you put table here regardless
let table = self.parse_keyword(Keyword::TABLE);
let table_name = self.parse_object_name()?;
let columns = self.parse_parenthesized_column_list(Optional)?;
let partitioned = if self.parse_keyword(Keyword::PARTITION) {
self.expect_token(&Token::LParen)?;
let r = Some(self.parse_comma_separated(Parser::parse_expr)?);
self.expect_token(&Token::RParen)?;
r
} else {
None
};
// Hive allows you to specify columns after partitions as well if you want.
let after_columns = self.parse_parenthesized_column_list(Optional)?;
let source = Box::new(self.parse_query()?);
let on = if self.parse_keyword(Keyword::ON) {
self.expect_keyword(Keyword::DUPLICATE)?;
self.expect_keyword(Keyword::KEY)?;
self.expect_keyword(Keyword::UPDATE)?;
let l = self.parse_comma_separated(Parser::parse_assignment)?;
Some(OnInsert::DuplicateKeyUpdate(l))
} else {
None
};
Ok(Statement::Insert {
or,
table_name,
overwrite,
partitioned,
columns,
after_columns,
source,
table,
on,
})
}
}
pub fn parse_update(&mut self) -> Result<Statement, ParserError> {
let table = self.parse_table_and_joins()?;
self.expect_keyword(Keyword::SET)?;
let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
let from = if self.parse_keyword(Keyword::FROM) && dialect_of!(self is PostgreSqlDialect) {
Some(self.parse_table_and_joins()?)
} else {
None
};
let selection = if self.parse_keyword(Keyword::WHERE) {
Some(self.parse_expr()?)
} else {
None
};
Ok(Statement::Update {
table,
assignments,
from,
selection,
})
}
/// Parse a `var = expr` assignment, used in an UPDATE statement
pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError> {
let id = self.parse_identifiers_non_keywords()?;
self.expect_token(&Token::Eq)?;
let value = self.parse_expr()?;
Ok(Assignment { id, value })
}
pub fn parse_function_args(&mut self) -> Result<FunctionArg, ParserError> {
if self.peek_nth_token(1) == Token::RArrow {
let name = self.parse_identifier()?;
self.expect_token(&Token::RArrow)?;
let arg = self.parse_wildcard_expr()?.into();
Ok(FunctionArg::Named { name, arg })
} else {
Ok(FunctionArg::Unnamed(self.parse_wildcard_expr()?.into()))
}
}
pub fn parse_optional_args(&mut self) -> Result<Vec<FunctionArg>, ParserError> {
if self.consume_token(&Token::RParen) {
Ok(vec![])
} else {
let args = self.parse_comma_separated(Parser::parse_function_args)?;
self.expect_token(&Token::RParen)?;
Ok(args)
}
}
/// Parse a comma-delimited list of projections after SELECT
pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError> {
match self.parse_wildcard_expr()? {
WildcardExpr::Expr(expr) => self
.parse_optional_alias(keywords::RESERVED_FOR_COLUMN_ALIAS)
.map(|alias| match alias {
Some(alias) => SelectItem::ExprWithAlias { expr, alias },
None => SelectItem::UnnamedExpr(expr),
}),
WildcardExpr::QualifiedWildcard(prefix) => Ok(SelectItem::QualifiedWildcard(prefix)),
WildcardExpr::Wildcard => Ok(SelectItem::Wildcard),
}
}
/// Parse an expression, optionally followed by ASC or DESC (used in ORDER BY)
pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError> {
let expr = self.parse_expr()?;
let asc = if self.parse_keyword(Keyword::ASC) {
Some(true)
} else if self.parse_keyword(Keyword::DESC) {
Some(false)
} else {
None
};
let nulls_first = if self.parse_keywords(&[Keyword::NULLS, Keyword::FIRST]) {
Some(true)
} else if self.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
Some(false)
} else {
None
};
Ok(OrderByExpr {
expr,
asc,
nulls_first,
})
}
/// Parse a TOP clause, MSSQL equivalent of LIMIT,
/// that follows after SELECT [DISTINCT].
pub fn parse_top(&mut self) -> Result<Top, ParserError> {
let quantity = if self.consume_token(&Token::LParen) {
let quantity = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
Some(quantity)
} else {
Some(Expr::Value(self.parse_number_value()?))
};
let percent = self.parse_keyword(Keyword::PERCENT);
let with_ties = self.parse_keywords(&[Keyword::WITH, Keyword::TIES]);
Ok(Top {
with_ties,
percent,
quantity,
})
}
/// Parse a LIMIT clause
pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError> {
if self.parse_keyword(Keyword::ALL) {
Ok(None)
} else {
Ok(Some(Expr::Value(self.parse_number_value()?)))
}
}
/// Parse an OFFSET clause
pub fn parse_offset(&mut self) -> Result<Offset, ParserError> {
let value = Expr::Value(self.parse_number_value()?);
let rows = if self.parse_keyword(Keyword::ROW) {
OffsetRows::Row
} else if self.parse_keyword(Keyword::ROWS) {
OffsetRows::Rows
} else {
OffsetRows::None
};
Ok(Offset { value, rows })
}
/// Parse a FETCH clause
pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError> {
self.expect_one_of_keywords(&[Keyword::FIRST, Keyword::NEXT])?;
let (quantity, percent) = if self
.parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])
.is_some()
{
(None, false)
} else {
let quantity = Expr::Value(self.parse_value()?);
let percent = self.parse_keyword(Keyword::PERCENT);
self.expect_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])?;
(Some(quantity), percent)
};
let with_ties = if self.parse_keyword(Keyword::ONLY) {
false
} else if self.parse_keywords(&[Keyword::WITH, Keyword::TIES]) {
true
} else {
return self.expected("one of ONLY or WITH TIES", self.peek_token());
};
Ok(Fetch {
with_ties,
percent,
quantity,
})
}
/// Parse a FOR UPDATE/FOR SHARE clause
pub fn parse_lock(&mut self) -> Result<LockType, ParserError> {
match self.expect_one_of_keywords(&[Keyword::UPDATE, Keyword::SHARE])? {
Keyword::UPDATE => Ok(LockType::Update),
Keyword::SHARE => Ok(LockType::Share),
_ => unreachable!(),
}
}
pub fn parse_values(&mut self) -> Result<Values, ParserError> {
let values = self.parse_comma_separated(|parser| {
parser.expect_token(&Token::LParen)?;
let exprs = parser.parse_comma_separated(Parser::parse_expr)?;
parser.expect_token(&Token::RParen)?;
Ok(exprs)
})?;
Ok(Values(values))
}
pub fn parse_start_transaction(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::TRANSACTION)?;
Ok(Statement::StartTransaction {
modes: self.parse_transaction_modes()?,
})
}
pub fn parse_begin(&mut self) -> Result<Statement, ParserError> {
let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
Ok(Statement::StartTransaction {
modes: self.parse_transaction_modes()?,
})
}
pub fn parse_transaction_modes(&mut self) -> Result<Vec<TransactionMode>, ParserError> {
let mut modes = vec![];
let mut required = false;
loop {
let mode = if self.parse_keywords(&[Keyword::ISOLATION, Keyword::LEVEL]) {
let iso_level = if self.parse_keywords(&[Keyword::READ, Keyword::UNCOMMITTED]) {
TransactionIsolationLevel::ReadUncommitted
} else if self.parse_keywords(&[Keyword::READ, Keyword::COMMITTED]) {
TransactionIsolationLevel::ReadCommitted
} else if self.parse_keywords(&[Keyword::REPEATABLE, Keyword::READ]) {
TransactionIsolationLevel::RepeatableRead
} else if self.parse_keyword(Keyword::SERIALIZABLE) {
TransactionIsolationLevel::Serializable
} else {
self.expected("isolation level", self.peek_token())?
};
TransactionMode::IsolationLevel(iso_level)
} else if self.parse_keywords(&[Keyword::READ, Keyword::ONLY]) {
TransactionMode::AccessMode(TransactionAccessMode::ReadOnly)
} else if self.parse_keywords(&[Keyword::READ, Keyword::WRITE]) {
TransactionMode::AccessMode(TransactionAccessMode::ReadWrite)
} else if required {
self.expected("transaction mode", self.peek_token())?
} else {
break;
};
modes.push(mode);
// ANSI requires a comma after each transaction mode, but
// PostgreSQL, for historical reasons, does not. We follow
// PostgreSQL in making the comma optional, since that is strictly
// more general.
required = self.consume_token(&Token::Comma);
}
Ok(modes)
}
pub fn parse_commit(&mut self) -> Result<Statement, ParserError> {
Ok(Statement::Commit {
chain: self.parse_commit_rollback_chain()?,
})
}
pub fn parse_rollback(&mut self) -> Result<Statement, ParserError> {
Ok(Statement::Rollback {
chain: self.parse_commit_rollback_chain()?,
})
}
pub fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError> {
let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
if self.parse_keyword(Keyword::AND) {
let chain = !self.parse_keyword(Keyword::NO);
self.expect_keyword(Keyword::CHAIN)?;
Ok(chain)
} else {
Ok(false)
}
}
pub fn parse_deallocate(&mut self) -> Result<Statement, ParserError> {
let prepare = self.parse_keyword(Keyword::PREPARE);
let name = self.parse_identifier()?;
Ok(Statement::Deallocate { name, prepare })
}
pub fn parse_execute(&mut self) -> Result<Statement, ParserError> {
let name = self.parse_identifier()?;
let mut parameters = vec![];
if self.consume_token(&Token::LParen) {
parameters = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
}
Ok(Statement::Execute { name, parameters })
}
pub fn parse_prepare(&mut self) -> Result<Statement, ParserError> {
let name = self.parse_identifier()?;
let mut data_types = vec![];
if self.consume_token(&Token::LParen) {
data_types = self.parse_comma_separated(Parser::parse_data_type)?;
self.expect_token(&Token::RParen)?;
}
self.expect_keyword(Keyword::AS)?;
let statement = Box::new(self.parse_statement()?);
Ok(Statement::Prepare {
name,
data_types,
statement,
})
}
pub fn parse_comment(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::ON)?;
let token = self.next_token();
let (object_type, object_name) = match token {
Token::Word(w) if w.keyword == Keyword::COLUMN => {
let object_name = self.parse_object_name()?;
(CommentObject::Column, object_name)
}
Token::Word(w) if w.keyword == Keyword::TABLE => {
let object_name = self.parse_object_name()?;
(CommentObject::Table, object_name)
}
_ => self.expected("comment object_type", token)?,
};
self.expect_keyword(Keyword::IS)?;
let comment = if self.parse_keyword(Keyword::NULL) {
None
} else {
Some(self.parse_literal_string()?)
};
Ok(Statement::Comment {
object_type,
object_name,
comment,
})
}
pub fn parse_merge_clauses(&mut self) -> Result<Vec<MergeClause>, ParserError> {
let mut clauses: Vec<MergeClause> = vec![];
loop {
if self.peek_token() == Token::EOF {
break;
}
self.expect_keyword(Keyword::WHEN)?;
let is_not_matched = self.parse_keyword(Keyword::NOT);
self.expect_keyword(Keyword::MATCHED)?;
let predicate = if self.parse_keyword(Keyword::AND) {
Some(self.parse_expr()?)
} else {
None
};
self.expect_keyword(Keyword::THEN)?;
clauses.push(
match self.parse_one_of_keywords(&[
Keyword::UPDATE,
Keyword::INSERT,
Keyword::DELETE,
]) {
Some(Keyword::UPDATE) => {
if is_not_matched {
return Err(ParserError::ParserError(
"UPDATE in NOT MATCHED merge clause".to_string(),
));
}
self.expect_keyword(Keyword::SET)?;
let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
MergeClause::MatchedUpdate {
predicate,
assignments,
}
}
Some(Keyword::DELETE) => {
if is_not_matched {
return Err(ParserError::ParserError(
"DELETE in NOT MATCHED merge clause".to_string(),
));
}
MergeClause::MatchedDelete(predicate)
}
Some(Keyword::INSERT) => {
if !is_not_matched {
return Err(ParserError::ParserError(
"INSERT in MATCHED merge clause".to_string(),
));
}
let columns = self.parse_parenthesized_column_list(Optional)?;
self.expect_keyword(Keyword::VALUES)?;
let values = self.parse_values()?;
MergeClause::NotMatched {
predicate,
columns,
values,
}
}
Some(_) => {
return Err(ParserError::ParserError(
"expected UPDATE, DELETE or INSERT in merge clause".to_string(),
))
}
None => {
return Err(ParserError::ParserError(
"expected UPDATE, DELETE or INSERT in merge clause".to_string(),
))
}
},
);
}
Ok(clauses)
}
pub fn parse_merge(&mut self) -> Result<Statement, ParserError> {
self.expect_keyword(Keyword::INTO)?;
let table = self.parse_table_factor()?;
self.expect_keyword(Keyword::USING)?;
let source = self.parse_query_body(0)?;
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
self.expect_keyword(Keyword::ON)?;
let on = self.parse_expr()?;
let clauses = self.parse_merge_clauses()?;
Ok(Statement::Merge {
table,
source: Box::new(source),
alias,
on: Box::new(on),
clauses,
})
}
}
impl Word {
pub fn to_ident(&self) -> Ident {
Ident {
value: self.value.clone(),
quote_style: self.quote_style,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::all_dialects;
#[test]
fn test_prev_index() {
let sql = "SELECT version";
all_dialects().run_parser_method(sql, |parser| {
assert_eq!(parser.peek_token(), Token::make_keyword("SELECT"));
assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
parser.prev_token();
assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
assert_eq!(parser.next_token(), Token::make_word("version", None));
parser.prev_token();
assert_eq!(parser.peek_token(), Token::make_word("version", None));
assert_eq!(parser.next_token(), Token::make_word("version", None));
assert_eq!(parser.peek_token(), Token::EOF);
parser.prev_token();
assert_eq!(parser.next_token(), Token::make_word("version", None));
assert_eq!(parser.next_token(), Token::EOF);
assert_eq!(parser.next_token(), Token::EOF);
parser.prev_token();
});
}
}
| 39.872601 | 117 | 0.521795 |
f7bcabca392fc242519647e90a5055ffcd3e956f | 1,709 | #[cfg(test)]
mod kdf_tests {
extern crate wasm_bindgen_test;
use std::str::from_utf8;
use anyhow::*;
use bsv_wasm::{hash::Hash, KDF};
use pbkdf2::{
password_hash::{Ident, PasswordHasher, Salt, SaltString},
Params, Pbkdf2,
};
use wasm_bindgen_test::*;
wasm_bindgen_test::wasm_bindgen_test_configure!();
#[test]
#[wasm_bindgen_test]
fn pbkdf2_sha256_hash_test() {
let password = "stronk-password".as_bytes();
let salt = "snails".as_bytes();
let rounds: u32 = 10000;
let kdf = KDF::pbkdf2(
password.into(),
Some(salt.into()),
bsv_wasm::PBKDF2Hashes::SHA256,
rounds,
32,
);
// validated against twetch/sycamore-pro and https://neurotechnics.com/tools/pbkdf2-test
assert_eq!(
kdf.get_hash().to_hex(),
"ffb5bb1b78211b1d275f32c4ba426f0875e80640fbf313eac06ba6e79225b237"
);
}
#[test]
#[wasm_bindgen_test]
fn pbkdf2_sha256_hash_test_2() {
let password = "stronk-password".as_bytes();
let salt = "1ae0ee429ffca864413b59edd5612c1a86b097411280a6dfa376d91c6eba5a20".as_bytes(); // sha256 of [email protected]
let rounds: u32 = 10000;
let kdf = KDF::pbkdf2(
password.into(),
Some(salt.into()),
bsv_wasm::PBKDF2Hashes::SHA256,
rounds,
32,
);
// validated against twetch/sycamore-pro and https://neurotechnics.com/tools/pbkdf2-test
assert_eq!(
kdf.get_hash().to_hex(),
"f064d740b65941152755829e2b48578b259bc9bfc8c3af7b0d93a5ca677f259d"
);
}
}
| 28.966102 | 127 | 0.592744 |
75fd545060c4aed955db27056c1bae7c02d99503 | 96,120 | //! ### Inferring borrow kinds for upvars
//!
//! Whenever there is a closure expression, we need to determine how each
//! upvar is used. We do this by initially assigning each upvar an
//! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
//! "escalating" the kind as needed. The borrow kind proceeds according to
//! the following lattice:
//!
//! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
//!
//! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
//! will promote its borrow kind to mutable borrow. If we see an `&mut x`
//! we'll do the same. Naturally, this applies not just to the upvar, but
//! to everything owned by `x`, so the result is the same for something
//! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
//! struct). These adjustments are performed in
//! `adjust_upvar_borrow_kind()` (you can trace backwards through the code
//! from there).
//!
//! The fact that we are inferring borrow kinds as we go results in a
//! semi-hacky interaction with mem-categorization. In particular,
//! mem-categorization will query the current borrow kind as it
//! categorizes, and we'll return the *current* value, but this may get
//! adjusted later. Therefore, in this module, we generally ignore the
//! borrow kind (and derived mutabilities) that are returned from
//! mem-categorization, since they may be inaccurate. (Another option
//! would be to use a unification scheme, where instead of returning a
//! concrete borrow kind like `ty::ImmBorrow`, we return a
//! `ty::InferBorrow(upvar_id)` or something like that, but this would
//! then mean that all later passes would have to check for these figments
//! and report an error, and it just seems like more mess in the end.)
use super::FnCtxt;
use crate::expr_use_visitor as euv;
use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_infer::infer::UpvarRegion;
use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
use rustc_middle::mir::FakeReadCause;
use rustc_middle::ty::{
self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarCapture, UpvarSubsts,
};
use rustc_session::lint;
use rustc_span::sym;
use rustc_span::{BytePos, MultiSpan, Pos, Span, Symbol, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
use rustc_data_structures::stable_map::FxHashMap;
use rustc_data_structures::stable_set::FxHashSet;
use rustc_index::vec::Idx;
use rustc_target::abi::VariantIdx;
use std::iter;
/// Describe the relationship between the paths of two places
/// eg:
/// - `foo` is ancestor of `foo.bar.baz`
/// - `foo.bar.baz` is an descendant of `foo.bar`
/// - `foo.bar` and `foo.baz` are divergent
enum PlaceAncestryRelation {
Ancestor,
Descendant,
Divergent,
}
/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
/// during capture analysis. Information in this map feeds into the minimum capture
/// analysis pass.
type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
InferBorrowKindVisitor { fcx: self }.visit_body(body);
// it's our job to process these.
assert!(self.deferred_call_resolutions.borrow().is_empty());
}
}
/// Intermediate format to store the hir_id pointing to the use that resulted in the
/// corresponding place being captured and a String which contains the captured value's
/// name (i.e: a.b.c)
type CapturesInfo = (Option<hir::HirId>, String);
/// Intermediate format to store information needed to generate migration lint. The tuple
/// contains the hir_id pointing to the use that resulted in the
/// corresponding place being captured, a String which contains the captured value's
/// name (i.e: a.b.c) and a String which contains the reason why migration is needed for that
/// capture
type MigrationNeededForCapture = (Option<hir::HirId>, String, String);
/// Intermediate format to store the hir id of the root variable and a HashSet containing
/// information on why the root variable should be fully captured
type MigrationDiagnosticInfo = (hir::HirId, Vec<MigrationNeededForCapture>);
struct InferBorrowKindVisitor<'a, 'tcx> {
fcx: &'a FnCtxt<'a, 'tcx>,
}
impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
type Map = intravisit::ErasedMap<'tcx>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
let body = self.fcx.tcx.hir().body(body_id);
self.visit_body(body);
self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, cc);
}
intravisit::walk_expr(self, expr);
}
}
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Analysis starting point.
fn analyze_closure(
&self,
closure_hir_id: hir::HirId,
span: Span,
body_id: hir::BodyId,
body: &'tcx hir::Body<'tcx>,
capture_clause: hir::CaptureBy,
) {
debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
// Extract the type of the closure.
let ty = self.node_ty(closure_hir_id);
let (closure_def_id, substs) = match *ty.kind() {
ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
ty::Error(_) => {
// #51714: skip analysis when we have already encountered type errors
return;
}
_ => {
span_bug!(
span,
"type of closure expr {:?} is not a closure {:?}",
closure_hir_id,
ty
);
}
};
let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
self.closure_kind(closure_substs).is_none().then_some(closure_substs)
} else {
None
};
let local_def_id = closure_def_id.expect_local();
let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
let mut delegate = InferBorrowKind {
fcx: self,
closure_def_id,
closure_span: span,
capture_information: Default::default(),
fake_reads: Default::default(),
};
euv::ExprUseVisitor::new(
&mut delegate,
&self.infcx,
body_owner_def_id,
self.param_env,
&self.typeck_results.borrow(),
)
.consume_body(body);
debug!(
"For closure={:?}, capture_information={:#?}",
closure_def_id, delegate.capture_information
);
self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
let (capture_information, closure_kind, origin) = self
.process_collected_capture_information(capture_clause, delegate.capture_information);
self.compute_min_captures(closure_def_id, capture_information);
let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
}
let after_feature_tys = self.final_upvar_tys(closure_def_id);
// We now fake capture information for all variables that are mentioned within the closure
// We do this after handling migrations so that min_captures computes before
if !enable_precise_capture(self.tcx, span) {
let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
for var_hir_id in upvars.keys() {
let place = self.place_for_root_variable(local_def_id, *var_hir_id);
debug!("seed place {:?}", place);
let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
let capture_kind =
self.init_capture_kind_for_place(&place, capture_clause, upvar_id, span);
let fake_info = ty::CaptureInfo {
capture_kind_expr_id: None,
path_expr_id: None,
capture_kind,
};
capture_information.insert(place, fake_info);
}
}
// This will update the min captures based on this new fake information.
self.compute_min_captures(closure_def_id, capture_information);
}
let before_feature_tys = self.final_upvar_tys(closure_def_id);
if let Some(closure_substs) = infer_kind {
// Unify the (as yet unbound) type variable in the closure
// substs with the kind we inferred.
let closure_kind_ty = closure_substs.as_closure().kind_ty();
self.demand_eqtype(span, closure_kind.to_ty(self.tcx), closure_kind_ty);
// If we have an origin, store it.
if let Some(origin) = origin {
let origin = if enable_precise_capture(self.tcx, span) {
(origin.0, origin.1)
} else {
(origin.0, Place { projections: vec![], ..origin.1 })
};
self.typeck_results
.borrow_mut()
.closure_kind_origins_mut()
.insert(closure_hir_id, origin);
}
}
self.log_closure_min_capture_info(closure_def_id, span);
// Now that we've analyzed the closure, we know how each
// variable is borrowed, and we know what traits the closure
// implements (Fn vs FnMut etc). We now have some updates to do
// with that information.
//
// Note that no closure type C may have an upvar of type C
// (though it may reference itself via a trait object). This
// results from the desugaring of closures to a struct like
// `Foo<..., UV0...UVn>`. If one of those upvars referenced
// C, then the type would have infinite size (and the
// inference algorithm will reject it).
// Equate the type variables for the upvars with the actual types.
let final_upvar_tys = self.final_upvar_tys(closure_def_id);
debug!(
"analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
closure_hir_id, substs, final_upvar_tys
);
// Build a tuple (U0..Un) of the final upvar types U0..Un
// and unify the upvar tupe type in the closure with it:
let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
let fake_reads = delegate
.fake_reads
.into_iter()
.map(|(place, cause, hir_id)| (place, cause, hir_id))
.collect();
self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
if self.tcx.sess.opts.debugging_opts.profile_closures {
self.typeck_results.borrow_mut().closure_size_eval.insert(
closure_def_id,
ClosureSizeProfileData {
before_feature_tys: self.tcx.mk_tup(before_feature_tys.into_iter()),
after_feature_tys: self.tcx.mk_tup(after_feature_tys.into_iter()),
},
);
}
// If we are also inferred the closure kind here,
// process any deferred resolutions.
let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
for deferred_call_resolution in deferred_call_resolutions {
deferred_call_resolution.resolve(self);
}
}
// Returns a list of `Ty`s for each upvar.
fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
// Presently an unboxed closure type cannot "escape" out of a
// function, so we will only encounter ones that originated in the
// local crate or were inlined into it along with some function.
// This may change if abstract return types of some sort are
// implemented.
self.typeck_results
.borrow()
.closure_min_captures_flattened(closure_id)
.map(|captured_place| {
let upvar_ty = captured_place.place.ty();
let capture = captured_place.info.capture_kind;
debug!(
"final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
captured_place.place, upvar_ty, capture, captured_place.mutability,
);
apply_capture_kind_on_capture_ty(self.tcx, upvar_ty, capture)
})
.collect()
}
/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
/// and that the path can be captured with required capture kind (depending on use in closure,
/// move closure etc.)
///
/// Returns the set of of adjusted information along with the inferred closure kind and span
/// associated with the closure kind inference.
///
/// Note that we *always* infer a minimal kind, even if
/// we don't always *use* that in the final result (i.e., sometimes
/// we've taken the closure kind from the expectations instead, and
/// for generators we don't even implement the closure traits
/// really).
///
/// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
/// contains a `Some()` with the `Place` that caused us to do so.
fn process_collected_capture_information(
&self,
capture_clause: hir::CaptureBy,
capture_information: InferredCaptureInformation<'tcx>,
) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
let mut processed: InferredCaptureInformation<'tcx> = Default::default();
let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
let mut origin: Option<(Span, Place<'tcx>)> = None;
for (place, mut capture_info) in capture_information {
// Apply rules for safety before inferring closure kind
let (place, capture_kind) =
restrict_capture_precision(place, capture_info.capture_kind);
capture_info.capture_kind = capture_kind;
let (place, capture_kind) =
truncate_capture_for_optimization(place, capture_info.capture_kind);
capture_info.capture_kind = capture_kind;
let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
self.tcx.hir().span(usage_expr)
} else {
unreachable!()
};
let updated = match capture_info.capture_kind {
ty::UpvarCapture::ByValue(..) => match closure_kind {
ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
(ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
}
// If closure is already FnOnce, don't update
ty::ClosureKind::FnOnce => (closure_kind, origin),
},
ty::UpvarCapture::ByRef(ty::UpvarBorrow {
kind: ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow,
..
}) => {
match closure_kind {
ty::ClosureKind::Fn => {
(ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
}
// Don't update the origin
ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => (closure_kind, origin),
}
}
_ => (closure_kind, origin),
};
closure_kind = updated.0;
origin = updated.1;
let (place, capture_kind) = match capture_clause {
hir::CaptureBy::Value => adjust_for_move_closure(place, capture_info.capture_kind),
hir::CaptureBy::Ref => {
adjust_for_non_move_closure(place, capture_info.capture_kind)
}
};
capture_info.capture_kind = capture_kind;
let capture_info = if let Some(existing) = processed.get(&place) {
determine_capture_info(*existing, capture_info)
} else {
capture_info
};
processed.insert(place, capture_info);
}
(processed, closure_kind, origin)
}
/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
/// Places (and corresponding capture kind) that we need to keep track of to support all
/// the required captured paths.
///
///
/// Note: If this function is called multiple times for the same closure, it will update
/// the existing min_capture map that is stored in TypeckResults.
///
/// Eg:
/// ```rust,no_run
/// struct Point { x: i32, y: i32 }
///
/// let s: String; // hir_id_s
/// let mut p: Point; // his_id_p
/// let c = || {
/// println!("{}", s); // L1
/// p.x += 10; // L2
/// println!("{}" , p.y) // L3
/// println!("{}", p) // L4
/// drop(s); // L5
/// };
/// ```
/// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
/// the lines L1..5 respectively.
///
/// InferBorrowKind results in a structure like this:
///
/// ```text
/// {
/// Place(base: hir_id_s, projections: [], ....) -> {
/// capture_kind_expr: hir_id_L5,
/// path_expr_id: hir_id_L5,
/// capture_kind: ByValue
/// },
/// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
/// capture_kind_expr: hir_id_L2,
/// path_expr_id: hir_id_L2,
/// capture_kind: ByValue
/// },
/// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
/// capture_kind_expr: hir_id_L3,
/// path_expr_id: hir_id_L3,
/// capture_kind: ByValue
/// },
/// Place(base: hir_id_p, projections: [], ...) -> {
/// capture_kind_expr: hir_id_L4,
/// path_expr_id: hir_id_L4,
/// capture_kind: ByValue
/// },
/// ```
///
/// After the min capture analysis, we get:
/// ```text
/// {
/// hir_id_s -> [
/// Place(base: hir_id_s, projections: [], ....) -> {
/// capture_kind_expr: hir_id_L5,
/// path_expr_id: hir_id_L5,
/// capture_kind: ByValue
/// },
/// ],
/// hir_id_p -> [
/// Place(base: hir_id_p, projections: [], ...) -> {
/// capture_kind_expr: hir_id_L2,
/// path_expr_id: hir_id_L4,
/// capture_kind: ByValue
/// },
/// ],
/// ```
fn compute_min_captures(
&self,
closure_def_id: DefId,
capture_information: InferredCaptureInformation<'tcx>,
) {
if capture_information.is_empty() {
return;
}
let mut typeck_results = self.typeck_results.borrow_mut();
let mut root_var_min_capture_list =
typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
for (mut place, capture_info) in capture_information.into_iter() {
let var_hir_id = match place.base {
PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
base => bug!("Expected upvar, found={:?}", base),
};
let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
None => {
let mutability = self.determine_capture_mutability(&typeck_results, &place);
let min_cap_list =
vec![ty::CapturedPlace { place, info: capture_info, mutability }];
root_var_min_capture_list.insert(var_hir_id, min_cap_list);
continue;
}
Some(min_cap_list) => min_cap_list,
};
// Go through each entry in the current list of min_captures
// - if ancestor is found, update it's capture kind to account for current place's
// capture information.
//
// - if descendant is found, remove it from the list, and update the current place's
// capture information to account for the descendants's capture kind.
//
// We can never be in a case where the list contains both an ancestor and a descendant
// Also there can only be ancestor but in case of descendants there might be
// multiple.
let mut descendant_found = false;
let mut updated_capture_info = capture_info;
min_cap_list.retain(|possible_descendant| {
match determine_place_ancestry_relation(&place, &possible_descendant.place) {
// current place is ancestor of possible_descendant
PlaceAncestryRelation::Ancestor => {
descendant_found = true;
let mut possible_descendant = possible_descendant.clone();
let backup_path_expr_id = updated_capture_info.path_expr_id;
// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
// possible change in capture mode.
truncate_place_to_len_and_update_capture_kind(
&mut possible_descendant.place,
&mut possible_descendant.info.capture_kind,
place.projections.len(),
);
updated_capture_info =
determine_capture_info(updated_capture_info, possible_descendant.info);
// we need to keep the ancestor's `path_expr_id`
updated_capture_info.path_expr_id = backup_path_expr_id;
false
}
_ => true,
}
});
let mut ancestor_found = false;
if !descendant_found {
for possible_ancestor in min_cap_list.iter_mut() {
match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
// current place is descendant of possible_ancestor
PlaceAncestryRelation::Descendant => {
ancestor_found = true;
let backup_path_expr_id = possible_ancestor.info.path_expr_id;
// Truncate the descendant (current place) to be same as the ancestor to handle any
// possible change in capture mode.
truncate_place_to_len_and_update_capture_kind(
&mut place,
&mut updated_capture_info.capture_kind,
possible_ancestor.place.projections.len(),
);
possible_ancestor.info = determine_capture_info(
possible_ancestor.info,
updated_capture_info,
);
// we need to keep the ancestor's `path_expr_id`
possible_ancestor.info.path_expr_id = backup_path_expr_id;
// Only one ancestor of the current place will be in the list.
break;
}
_ => {}
}
}
}
// Only need to insert when we don't have an ancestor in the existing min capture list
if !ancestor_found {
let mutability = self.determine_capture_mutability(&typeck_results, &place);
let captured_place =
ty::CapturedPlace { place, info: updated_capture_info, mutability };
min_cap_list.push(captured_place);
}
}
debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
}
/// Perform the migration analysis for RFC 2229, and emit lint
/// `disjoint_capture_drop_reorder` if needed.
fn perform_2229_migration_anaysis(
&self,
closure_def_id: DefId,
body_id: hir::BodyId,
capture_clause: hir::CaptureBy,
span: Span,
) {
let (need_migrations, reasons) = self.compute_2229_migrations(
closure_def_id,
span,
capture_clause,
self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
);
if !need_migrations.is_empty() {
let (migration_string, migrated_variables_concat) =
migration_suggestion_for_2229(self.tcx, &need_migrations);
let local_def_id = closure_def_id.expect_local();
let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
let closure_span = self.tcx.hir().span(closure_hir_id);
let closure_head_span = self.tcx.sess.source_map().guess_head_span(closure_span);
self.tcx.struct_span_lint_hir(
lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
closure_hir_id,
closure_head_span,
|lint| {
let mut diagnostics_builder = lint.build(
format!(
"changes to closure capture in Rust 2021 will affect {}",
reasons
)
.as_str(),
);
for (var_hir_id, diagnostics_info) in need_migrations.iter() {
// Labels all the usage of the captured variable and why they are responsible
// for migration being needed
for (captured_hir_id, captured_name, reasons) in diagnostics_info.iter() {
if let Some(captured_hir_id) = captured_hir_id {
let cause_span = self.tcx.hir().span(*captured_hir_id);
diagnostics_builder.span_label(cause_span, format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
self.tcx.hir().name(*var_hir_id),
captured_name,
));
}
// Add a label pointing to where a captured variable affected by drop order
// is dropped
if reasons.contains("drop order") {
let drop_location_span = drop_location_span(self.tcx, &closure_hir_id);
diagnostics_builder.span_label(drop_location_span, format!("in Rust 2018, `{}` is dropped here, but in Rust 2021, only `{}` will be dropped here as part of the closure",
self.tcx.hir().name(*var_hir_id),
captured_name,
));
}
// Add a label explaining why a closure no longer implements a trait
if reasons.contains("trait implementation") {
let missing_trait = &reasons[..reasons.find("trait implementation").unwrap() - 1];
diagnostics_builder.span_label(closure_head_span, format!("in Rust 2018, this closure implements {} as `{}` implements {}, but in Rust 2021, this closure will no longer implement {} as `{}` does not implement {}",
missing_trait,
self.tcx.hir().name(*var_hir_id),
missing_trait,
missing_trait,
captured_name,
missing_trait,
));
}
}
}
diagnostics_builder.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>");
let diagnostic_msg = format!(
"add a dummy let to cause {} to be fully captured",
migrated_variables_concat
);
let mut closure_body_span = self.tcx.hir().span(body_id.hir_id);
// If the body was entirely expanded from a macro
// invocation, i.e. the body is not contained inside the
// closure span, then we walk up the expansion until we
// find the span before the expansion.
while !closure_body_span.is_dummy() && !closure_span.contains(closure_body_span) {
closure_body_span = closure_body_span.parent().unwrap_or(DUMMY_SP);
}
if let Ok(s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
let mut lines = s.lines();
let line1 = lines.next().unwrap_or_default();
if line1.trim_end() == "{" {
// This is a multi-line closure with just a `{` on the first line,
// so we put the `let` on its own line.
// We take the indentation from the next non-empty line.
let line2 = lines.filter(|line| !line.is_empty()).next().unwrap_or_default();
let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
diagnostics_builder.span_suggestion(
closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
&diagnostic_msg,
format!("\n{}{};", indent, migration_string),
Applicability::MachineApplicable,
);
} else if line1.starts_with('{') {
// This is a closure with its body wrapped in
// braces, but with more than just the opening
// brace on the first line. We put the `let`
// directly after the `{`.
diagnostics_builder.span_suggestion(
closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
&diagnostic_msg,
format!(" {};", migration_string),
Applicability::MachineApplicable,
);
} else {
// This is a closure without braces around the body.
// We add braces to add the `let` before the body.
diagnostics_builder.multipart_suggestion(
&diagnostic_msg,
vec![
(closure_body_span.shrink_to_lo(), format!("{{ {}; ", migration_string)),
(closure_body_span.shrink_to_hi(), " }".to_string()),
],
Applicability::MachineApplicable
);
}
} else {
diagnostics_builder.span_suggestion(
closure_span,
&diagnostic_msg,
migration_string,
Applicability::HasPlaceholders
);
}
diagnostics_builder.emit();
},
);
}
}
/// Combines all the reasons for 2229 migrations
fn compute_2229_migrations_reasons(
&self,
auto_trait_reasons: FxHashSet<&str>,
drop_reason: bool,
) -> String {
let mut reasons = String::new();
if auto_trait_reasons.len() > 0 {
reasons = format!(
"{} trait implementation for closure",
auto_trait_reasons.clone().into_iter().collect::<Vec<&str>>().join(", ")
);
}
if auto_trait_reasons.len() > 0 && drop_reason {
reasons = format!("{} and ", reasons);
}
if drop_reason {
reasons = format!("{}drop order", reasons);
}
reasons
}
/// Figures out the list of root variables (and their types) that aren't completely
/// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
/// differ between the root variable and the captured paths.
///
/// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
/// if migration is needed for traits for the provided var_hir_id, otherwise returns None
fn compute_2229_migrations_for_trait(
&self,
min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
var_hir_id: hir::HirId,
closure_clause: hir::CaptureBy,
) -> Option<FxHashMap<CapturesInfo, FxHashSet<&str>>> {
let auto_traits_def_id = vec![
self.tcx.lang_items().clone_trait(),
self.tcx.lang_items().sync_trait(),
self.tcx.get_diagnostic_item(sym::send_trait),
self.tcx.lang_items().unpin_trait(),
self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
];
let auto_traits =
vec!["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
min_captures.and_then(|m| m.get(&var_hir_id))
{
root_var_min_capture_list
} else {
return None;
};
let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
let ty = match closure_clause {
hir::CaptureBy::Value => ty, // For move closure the capture kind should be by value
hir::CaptureBy::Ref => {
// For non move closure the capture kind is the max capture kind of all captures
// according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
for capture in root_var_min_capture_list.iter() {
max_capture_info = determine_capture_info(max_capture_info, capture.info);
}
apply_capture_kind_on_capture_ty(self.tcx, ty, max_capture_info.capture_kind)
}
};
let mut obligations_should_hold = Vec::new();
// Checks if a root variable implements any of the auto traits
for check_trait in auto_traits_def_id.iter() {
obligations_should_hold.push(
check_trait
.map(|check_trait| {
self.infcx
.type_implements_trait(
check_trait,
ty,
self.tcx.mk_substs_trait(ty, &[]),
self.param_env,
)
.must_apply_modulo_regions()
})
.unwrap_or(false),
);
}
let mut problematic_captures = FxHashMap::default();
// Check whether captured fields also implement the trait
for capture in root_var_min_capture_list.iter() {
let ty = apply_capture_kind_on_capture_ty(
self.tcx,
capture.place.ty(),
capture.info.capture_kind,
);
// Checks if a capture implements any of the auto traits
let mut obligations_holds_for_capture = Vec::new();
for check_trait in auto_traits_def_id.iter() {
obligations_holds_for_capture.push(
check_trait
.map(|check_trait| {
self.infcx
.type_implements_trait(
check_trait,
ty,
self.tcx.mk_substs_trait(ty, &[]),
self.param_env,
)
.must_apply_modulo_regions()
})
.unwrap_or(false),
);
}
let mut capture_problems = FxHashSet::default();
// Checks if for any of the auto traits, one or more trait is implemented
// by the root variable but not by the capture
for (idx, _) in obligations_should_hold.iter().enumerate() {
if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
capture_problems.insert(auto_traits[idx]);
}
}
if capture_problems.len() > 0 {
problematic_captures.insert(
(capture.info.path_expr_id, capture.to_string(self.tcx)),
capture_problems,
);
}
}
if problematic_captures.len() > 0 {
return Some(problematic_captures);
}
None
}
/// Figures out the list of root variables (and their types) that aren't completely
/// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
/// some path starting at that root variable **might** be affected.
///
/// The output list would include a root variable if:
/// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
/// enabled, **and**
/// - It wasn't completely captured by the closure, **and**
/// - One of the paths starting at this root variable, that is not captured needs Drop.
///
/// This function only returns a HashSet of CapturesInfo for significant drops. If there
/// are no significant drops than None is returned
fn compute_2229_migrations_for_drop(
&self,
closure_def_id: DefId,
closure_span: Span,
min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
closure_clause: hir::CaptureBy,
var_hir_id: hir::HirId,
) -> Option<FxHashSet<CapturesInfo>> {
let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
return None;
}
let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
min_captures.and_then(|m| m.get(&var_hir_id))
{
root_var_min_capture_list
} else {
// The upvar is mentioned within the closure but no path starting from it is
// used.
match closure_clause {
// Only migrate if closure is a move closure
hir::CaptureBy::Value => return Some(FxHashSet::default()),
hir::CaptureBy::Ref => {}
}
return None;
};
let mut projections_list = Vec::new();
let mut diagnostics_info = FxHashSet::default();
for captured_place in root_var_min_capture_list.iter() {
match captured_place.info.capture_kind {
// Only care about captures that are moved into the closure
ty::UpvarCapture::ByValue(..) => {
projections_list.push(captured_place.place.projections.as_slice());
diagnostics_info.insert((
captured_place.info.path_expr_id,
captured_place.to_string(self.tcx),
));
}
ty::UpvarCapture::ByRef(..) => {}
}
}
let is_moved = !projections_list.is_empty();
let is_not_completely_captured =
root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
if is_moved
&& is_not_completely_captured
&& self.has_significant_drop_outside_of_captures(
closure_def_id,
closure_span,
ty,
projections_list,
)
{
return Some(diagnostics_info);
}
return None;
}
/// Figures out the list of root variables (and their types) that aren't completely
/// captured by the closure when `capture_disjoint_fields` is enabled and either drop
/// order of some path starting at that root variable **might** be affected or auto-traits
/// differ between the root variable and the captured paths.
///
/// The output list would include a root variable if:
/// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
/// enabled, **and**
/// - It wasn't completely captured by the closure, **and**
/// - One of the paths starting at this root variable, that is not captured needs Drop **or**
/// - One of the paths captured does not implement all the auto-traits its root variable
/// implements.
///
/// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
/// containing the reason why root variables whose HirId is contained in the vector should
/// be captured
fn compute_2229_migrations(
&self,
closure_def_id: DefId,
closure_span: Span,
closure_clause: hir::CaptureBy,
min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
) -> (Vec<MigrationDiagnosticInfo>, String) {
let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
upvars
} else {
return (Vec::new(), format!(""));
};
let mut need_migrations = Vec::new();
let mut auto_trait_migration_reasons = FxHashSet::default();
let mut drop_migration_needed = false;
// Perform auto-trait analysis
for (&var_hir_id, _) in upvars.iter() {
let mut responsible_captured_hir_ids = Vec::new();
let auto_trait_diagnostic = if let Some(diagnostics_info) =
self.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
{
diagnostics_info
} else {
FxHashMap::default()
};
let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
.compute_2229_migrations_for_drop(
closure_def_id,
closure_span,
min_captures,
closure_clause,
var_hir_id,
) {
drop_migration_needed = true;
diagnostics_info
} else {
FxHashSet::default()
};
// Combine all the captures responsible for needing migrations into one HashSet
let mut capture_diagnostic = drop_reorder_diagnostic.clone();
for key in auto_trait_diagnostic.keys() {
capture_diagnostic.insert(key.clone());
}
let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
capture_diagnostic.sort();
for captured_info in capture_diagnostic.iter() {
// Get the auto trait reasons of why migration is needed because of that capture, if there are any
let capture_trait_reasons =
if let Some(reasons) = auto_trait_diagnostic.get(captured_info) {
reasons.clone()
} else {
FxHashSet::default()
};
// Check if migration is needed because of drop reorder as a result of that capture
let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(captured_info);
// Combine all the reasons of why the root variable should be captured as a result of
// auto trait implementation issues
auto_trait_migration_reasons.extend(capture_trait_reasons.clone());
responsible_captured_hir_ids.push((
captured_info.0,
captured_info.1.clone(),
self.compute_2229_migrations_reasons(
capture_trait_reasons,
capture_drop_reorder_reason,
),
));
}
if capture_diagnostic.len() > 0 {
need_migrations.push((var_hir_id, responsible_captured_hir_ids));
}
}
(
need_migrations,
self.compute_2229_migrations_reasons(
auto_trait_migration_reasons,
drop_migration_needed,
),
)
}
/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
/// of a root variable and a list of captured paths starting at this root variable (expressed
/// using list of `Projection` slices), it returns true if there is a path that is not
/// captured starting at this root variable that implements Drop.
///
/// The way this function works is at a given call it looks at type `base_path_ty` of some base
/// path say P and then list of projection slices which represent the different captures moved
/// into the closure starting off of P.
///
/// This will make more sense with an example:
///
/// ```rust
/// #![feature(capture_disjoint_fields)]
///
/// struct FancyInteger(i32); // This implements Drop
///
/// struct Point { x: FancyInteger, y: FancyInteger }
/// struct Color;
///
/// struct Wrapper { p: Point, c: Color }
///
/// fn f(w: Wrapper) {
/// let c = || {
/// // Closure captures w.p.x and w.c by move.
/// };
///
/// c();
/// }
/// ```
///
/// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
/// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
/// therefore Drop ordering would change and we want this function to return true.
///
/// Call stack to figure out if we need to migrate for `w` would look as follows:
///
/// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
/// `w[c]`.
/// Notation:
/// - Ty(place): Type of place
/// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
/// respectively.
/// ```
/// (Ty(w), [ &[p, x], &[c] ])
/// |
/// ----------------------------
/// | |
/// v v
/// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
/// | |
/// v v
/// (Ty(w.p), [ &[x] ]) false
/// |
/// |
/// -------------------------------
/// | |
/// v v
/// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
/// | |
/// v v
/// false NeedsSignificantDrop(Ty(w.p.y))
/// |
/// v
/// true
/// ```
///
/// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
/// This implies that the `w.c` is completely captured by the closure.
/// Since drop for this path will be called when the closure is
/// dropped we don't need to migrate for it.
///
/// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
/// path wasn't captured by the closure. Also note that even
/// though we didn't capture this path, the function visits it,
/// which is kind of the point of this function. We then return
/// if the type of `w.p.y` implements Drop, which in this case is
/// true.
///
/// Consider another example:
///
/// ```rust
/// struct X;
/// impl Drop for X {}
///
/// struct Y(X);
/// impl Drop for Y {}
///
/// fn foo() {
/// let y = Y(X);
/// let c = || move(y.0);
/// }
/// ```
///
/// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
/// return true, because even though all paths starting at `y` are captured, `y` itself
/// implements Drop which will be affected since `y` isn't completely captured.
fn has_significant_drop_outside_of_captures(
&self,
closure_def_id: DefId,
closure_span: Span,
base_path_ty: Ty<'tcx>,
captured_by_move_projs: Vec<&[Projection<'tcx>]>,
) -> bool {
let needs_drop = |ty: Ty<'tcx>| {
ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
};
let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
self.infcx
.type_implements_trait(
drop_trait,
ty,
ty_params,
self.tcx.param_env(closure_def_id.expect_local()),
)
.must_apply_modulo_regions()
};
let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
// If there is a case where no projection is applied on top of current place
// then there must be exactly one capture corresponding to such a case. Note that this
// represents the case of the path being completely captured by the variable.
//
// eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
// capture `a.b.c`, because that voilates min capture.
let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
if is_completely_captured {
// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
// when the closure is dropped.
return false;
}
if captured_by_move_projs.is_empty() {
return needs_drop(base_path_ty);
}
if is_drop_defined_for_ty {
// If drop is implemented for this type then we need it to be fully captured,
// and we know it is not completely captured because of the previous checks.
// Note that this is a bug in the user code that will be reported by the
// borrow checker, since we can't move out of drop types.
// The bug exists in the user's code pre-migration, and we don't migrate here.
return false;
}
match base_path_ty.kind() {
// Observations:
// - `captured_by_move_projs` is not empty. Therefore we can call
// `captured_by_move_projs.first().unwrap()` safely.
// - All entries in `captured_by_move_projs` have atleast one projection.
// Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
// We don't capture derefs in case of move captures, which would have be applied to
// access any further paths.
ty::Adt(def, _) if def.is_box() => unreachable!(),
ty::Ref(..) => unreachable!(),
ty::RawPtr(..) => unreachable!(),
ty::Adt(def, substs) => {
// Multi-varaint enums are captured in entirety,
// which would've been handled in the case of single empty slice in `captured_by_move_projs`.
assert_eq!(def.variants.len(), 1);
// Only Field projections can be applied to a non-box Adt.
assert!(
captured_by_move_projs.iter().all(|projs| matches!(
projs.first().unwrap().kind,
ProjectionKind::Field(..)
))
);
def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
|(i, field)| {
let paths_using_field = captured_by_move_projs
.iter()
.filter_map(|projs| {
if let ProjectionKind::Field(field_idx, _) =
projs.first().unwrap().kind
{
if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
} else {
unreachable!();
}
})
.collect();
let after_field_ty = field.ty(self.tcx, substs);
self.has_significant_drop_outside_of_captures(
closure_def_id,
closure_span,
after_field_ty,
paths_using_field,
)
},
)
}
ty::Tuple(..) => {
// Only Field projections can be applied to a tuple.
assert!(
captured_by_move_projs.iter().all(|projs| matches!(
projs.first().unwrap().kind,
ProjectionKind::Field(..)
))
);
base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
let paths_using_field = captured_by_move_projs
.iter()
.filter_map(|projs| {
if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
{
if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
} else {
unreachable!();
}
})
.collect();
self.has_significant_drop_outside_of_captures(
closure_def_id,
closure_span,
element_ty,
paths_using_field,
)
})
}
// Anything else would be completely captured and therefore handled already.
_ => unreachable!(),
}
}
fn init_capture_kind_for_place(
&self,
place: &Place<'tcx>,
capture_clause: hir::CaptureBy,
upvar_id: ty::UpvarId,
closure_span: Span,
) -> ty::UpvarCapture<'tcx> {
match capture_clause {
// In case of a move closure if the data is accessed through a reference we
// want to capture by ref to allow precise capture using reborrows.
//
// If the data will be moved out of this place, then the place will be truncated
// at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
// the closure.
hir::CaptureBy::Value if !place.deref_tys().any(ty::TyS::is_ref) => {
ty::UpvarCapture::ByValue(None)
}
hir::CaptureBy::Value | hir::CaptureBy::Ref => {
let origin = UpvarRegion(upvar_id, closure_span);
let upvar_region = self.next_region_var(origin);
let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
ty::UpvarCapture::ByRef(upvar_borrow)
}
}
}
fn place_for_root_variable(
&self,
closure_def_id: LocalDefId,
var_hir_id: hir::HirId,
) -> Place<'tcx> {
let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
Place {
base_ty: self.node_ty(var_hir_id),
base: PlaceBase::Upvar(upvar_id),
projections: Default::default(),
}
}
fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
}
fn log_capture_analysis_first_pass(
&self,
closure_def_id: rustc_hir::def_id::DefId,
capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
closure_span: Span,
) {
if self.should_log_capture_analysis(closure_def_id) {
let mut diag =
self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
for (place, capture_info) in capture_information {
let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
let output_str = format!("Capturing {}", capture_str);
let span =
capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
diag.span_note(span, &output_str);
}
diag.emit();
}
}
fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
if self.should_log_capture_analysis(closure_def_id) {
if let Some(min_captures) =
self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
{
let mut diag =
self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
for (_, min_captures_for_var) in min_captures {
for capture in min_captures_for_var {
let place = &capture.place;
let capture_info = &capture.info;
let capture_str =
construct_capture_info_string(self.tcx, place, capture_info);
let output_str = format!("Min Capture {}", capture_str);
if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
let path_span = capture_info
.path_expr_id
.map_or(closure_span, |e| self.tcx.hir().span(e));
let capture_kind_span = capture_info
.capture_kind_expr_id
.map_or(closure_span, |e| self.tcx.hir().span(e));
let mut multi_span: MultiSpan =
MultiSpan::from_spans(vec![path_span, capture_kind_span]);
let capture_kind_label =
construct_capture_kind_reason_string(self.tcx, place, capture_info);
let path_label = construct_path_string(self.tcx, place);
multi_span.push_span_label(path_span, path_label);
multi_span.push_span_label(capture_kind_span, capture_kind_label);
diag.span_note(multi_span, &output_str);
} else {
let span = capture_info
.path_expr_id
.map_or(closure_span, |e| self.tcx.hir().span(e));
diag.span_note(span, &output_str);
};
}
}
diag.emit();
}
}
}
/// A captured place is mutable if
/// 1. Projections don't include a Deref of an immut-borrow, **and**
/// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
fn determine_capture_mutability(
&self,
typeck_results: &'a TypeckResults<'tcx>,
place: &Place<'tcx>,
) -> hir::Mutability {
let var_hir_id = match place.base {
PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
_ => unreachable!(),
};
let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
let mut is_mutbl = match bm {
ty::BindByValue(mutability) => mutability,
ty::BindByReference(_) => hir::Mutability::Not,
};
for pointer_ty in place.deref_tys() {
match pointer_ty.kind() {
// We don't capture derefs of raw ptrs
ty::RawPtr(_) => unreachable!(),
// Derefencing a mut-ref allows us to mut the Place if we don't deref
// an immut-ref after on top of this.
ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
// The place isn't mutable once we dereference an immutable reference.
ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
// Dereferencing a box doesn't change mutability
ty::Adt(def, ..) if def.is_box() => {}
unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
}
}
is_mutbl
}
}
/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
fn restrict_repr_packed_field_ref_capture<'tcx>(
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
place: &Place<'tcx>,
mut curr_borrow_kind: ty::UpvarCapture<'tcx>,
) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
let pos = place.projections.iter().enumerate().position(|(i, p)| {
let ty = place.ty_before_projection(i);
// Return true for fields of packed structs, unless those fields have alignment 1.
match p.kind {
ProjectionKind::Field(..) => match ty.kind() {
ty::Adt(def, _) if def.repr.packed() => {
match tcx.layout_of(param_env.and(p.ty)) {
Ok(layout) if layout.align.abi.bytes() == 1 => {
// if the alignment is 1, the type can't be further
// disaligned.
debug!(
"restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
place
);
false
}
_ => {
debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
true
}
}
}
_ => false,
},
_ => false,
}
});
let mut place = place.clone();
if let Some(pos) = pos {
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
}
(place, curr_borrow_kind)
}
/// Returns a Ty that applies the specified capture kind on the provided capture Ty
fn apply_capture_kind_on_capture_ty(
tcx: TyCtxt<'tcx>,
ty: Ty<'tcx>,
capture_kind: UpvarCapture<'tcx>,
) -> Ty<'tcx> {
match capture_kind {
ty::UpvarCapture::ByValue(_) => ty,
ty::UpvarCapture::ByRef(borrow) => tcx
.mk_ref(borrow.region, ty::TypeAndMut { ty: ty, mutbl: borrow.kind.to_mutbl_lossy() }),
}
}
/// Returns the Span of where the value with the provided HirId would be dropped
fn drop_location_span(tcx: TyCtxt<'tcx>, hir_id: &hir::HirId) -> Span {
let owner_id = tcx.hir().get_enclosing_scope(*hir_id).unwrap();
let owner_node = tcx.hir().get(owner_id);
let owner_span = match owner_node {
hir::Node::Item(item) => match item.kind {
hir::ItemKind::Fn(_, _, owner_id) => tcx.hir().span(owner_id.hir_id),
_ => {
bug!("Drop location span error: need to handle more ItemKind {:?}", item.kind);
}
},
hir::Node::Block(block) => tcx.hir().span(block.hir_id),
_ => {
bug!("Drop location span error: need to handle more Node {:?}", owner_node);
}
};
tcx.sess.source_map().end_point(owner_span)
}
struct InferBorrowKind<'a, 'tcx> {
fcx: &'a FnCtxt<'a, 'tcx>,
// The def-id of the closure whose kind and upvar accesses are being inferred.
closure_def_id: DefId,
closure_span: Span,
/// For each Place that is captured by the closure, we track the minimal kind of
/// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
///
/// Consider closure where s.str1 is captured via an ImmutableBorrow and
/// s.str2 via a MutableBorrow
///
/// ```rust,no_run
/// struct SomeStruct { str1: String, str2: String }
///
/// // Assume that the HirId for the variable definition is `V1`
/// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
///
/// let fix_s = |new_s2| {
/// // Assume that the HirId for the expression `s.str1` is `E1`
/// println!("Updating SomeStruct with str1=", s.str1);
/// // Assume that the HirId for the expression `*s.str2` is `E2`
/// s.str2 = new_s2;
/// };
/// ```
///
/// For closure `fix_s`, (at a high level) the map contains
///
/// ```
/// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
/// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
/// ```
capture_information: InferredCaptureInformation<'tcx>,
fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
}
impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
fn adjust_upvar_borrow_kind_for_consume(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
) {
debug!(
"adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?})",
place_with_id, diag_expr_id
);
let tcx = self.fcx.tcx;
let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
upvar_id
} else {
return;
};
debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
let usage_span = tcx.hir().span(diag_expr_id);
let capture_info = ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
};
let curr_info = self.capture_information[&place_with_id.place];
let updated_info = determine_capture_info(curr_info, capture_info);
self.capture_information[&place_with_id.place] = updated_info;
}
/// Indicates that `place_with_id` is being directly mutated (e.g., assigned
/// to). If the place is based on a by-ref upvar, this implies that
/// the upvar must be borrowed using an `&mut` borrow.
fn adjust_upvar_borrow_kind_for_mut(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
) {
debug!(
"adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
place_with_id, diag_expr_id
);
if let PlaceBase::Upvar(_) = place_with_id.place.base {
// Raw pointers don't inherit mutability
if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
return;
}
self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::MutBorrow);
}
}
fn adjust_upvar_borrow_kind_for_unique(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
) {
debug!(
"adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
place_with_id, diag_expr_id
);
if let PlaceBase::Upvar(_) = place_with_id.place.base {
if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
// Raw pointers don't inherit mutability.
return;
}
// for a borrowed pointer to be unique, its base must be unique
self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
}
}
fn adjust_upvar_deref(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
borrow_kind: ty::BorrowKind,
) {
assert!(match borrow_kind {
ty::MutBorrow => true,
ty::UniqueImmBorrow => true,
// imm borrows never require adjusting any kinds, so we don't wind up here
ty::ImmBorrow => false,
});
// if this is an implicit deref of an
// upvar, then we need to modify the
// borrow_kind of the upvar to make sure it
// is inferred to mutable if necessary
self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
}
/// We infer the borrow_kind with which to borrow upvars in a stack closure.
/// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
/// moving from left to right as needed (but never right to left).
/// Here the argument `mutbl` is the borrow_kind that is required by
/// some particular use.
fn adjust_upvar_borrow_kind(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
kind: ty::BorrowKind,
) {
let curr_capture_info = self.capture_information[&place_with_id.place];
debug!(
"adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
place_with_id, diag_expr_id, curr_capture_info, kind
);
if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
// It's already captured by value, we don't need to do anything here
return;
} else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
// Use the same region as the current capture information
// Doesn't matter since only one of the UpvarBorrow will be used.
let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
let capture_info = ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
};
let updated_info = determine_capture_info(curr_capture_info, capture_info);
self.capture_information[&place_with_id.place] = updated_info;
};
}
fn init_capture_info_for_place(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
) {
if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
// Initialize to ImmBorrow
// We will escalate the CaptureKind based on any uses we see or in `process_collected_capture_information`.
let origin = UpvarRegion(upvar_id, self.closure_span);
let upvar_region = self.fcx.next_region_var(origin);
let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
let capture_kind = ty::UpvarCapture::ByRef(upvar_borrow);
let expr_id = Some(diag_expr_id);
let capture_info = ty::CaptureInfo {
capture_kind_expr_id: expr_id,
path_expr_id: expr_id,
capture_kind,
};
debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
self.capture_information.insert(place_with_id.place.clone(), capture_info);
} else {
debug!("Not upvar: {:?}", place_with_id);
}
}
}
impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId) {
if let PlaceBase::Upvar(_) = place.base {
// We need to restrict Fake Read precision to avoid fake reading unsafe code,
// such as deref of a raw pointer.
let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::UpvarBorrow {
kind: ty::BorrowKind::ImmBorrow,
region: &ty::ReErased,
});
let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
let (place, _) = restrict_repr_packed_field_ref_capture(
self.fcx.tcx,
self.fcx.param_env,
&place,
dummy_capture_kind,
);
self.fake_reads.push((place, cause, diag_expr_id));
}
}
fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
debug!("consume(place_with_id={:?}, diag_expr_id={:?})", place_with_id, diag_expr_id);
if !self.capture_information.contains_key(&place_with_id.place) {
self.init_capture_info_for_place(&place_with_id, diag_expr_id);
}
self.adjust_upvar_borrow_kind_for_consume(&place_with_id, diag_expr_id);
}
fn borrow(
&mut self,
place_with_id: &PlaceWithHirId<'tcx>,
diag_expr_id: hir::HirId,
bk: ty::BorrowKind,
) {
debug!(
"borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
place_with_id, diag_expr_id, bk
);
// The region here will get discarded/ignored
let dummy_capture_kind =
ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: bk, region: &ty::ReErased });
// We only want repr packed restriction to be applied to reading references into a packed
// struct, and not when the data is being moved. Therefore we call this method here instead
// of in `restrict_capture_precision`.
let (place, updated_kind) = restrict_repr_packed_field_ref_capture(
self.fcx.tcx,
self.fcx.param_env,
&place_with_id.place,
dummy_capture_kind,
);
let place_with_id = PlaceWithHirId { place, ..*place_with_id };
if !self.capture_information.contains_key(&place_with_id.place) {
self.init_capture_info_for_place(&place_with_id, diag_expr_id);
}
match updated_kind {
ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, .. }) => match kind {
ty::ImmBorrow => {}
ty::UniqueImmBorrow => {
self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
}
ty::MutBorrow => {
self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
}
},
// Just truncating the place will never cause capture kind to be updated to ByValue
ty::UpvarCapture::ByValue(..) => unreachable!(),
}
}
fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
}
}
/// Truncate `place` so that an `unsafe` block isn't required to capture it.
/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
/// them completely.
/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
fn restrict_precision_for_unsafe(
mut place: Place<'tcx>,
mut curr_mode: ty::UpvarCapture<'tcx>,
) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
if place.base_ty.is_unsafe_ptr() {
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
}
if place.base_ty.is_union() {
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
}
for (i, proj) in place.projections.iter().enumerate() {
if proj.ty.is_unsafe_ptr() {
// Don't apply any projections on top of an unsafe ptr.
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
break;
}
if proj.ty.is_union() {
// Don't capture preicse fields of a union.
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
break;
}
}
(place, curr_mode)
}
/// Truncate projections so that following rules are obeyed by the captured `place`:
/// - No Index projections are captured, since arrays are captured completely.
/// - No unsafe block is required to capture `place`
/// Returns the truncated place and updated cature mode.
fn restrict_capture_precision<'tcx>(
place: Place<'tcx>,
curr_mode: ty::UpvarCapture<'tcx>,
) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
if place.projections.is_empty() {
// Nothing to do here
return (place, curr_mode);
}
for (i, proj) in place.projections.iter().enumerate() {
match proj.kind {
ProjectionKind::Index => {
// Arrays are completely captured, so we drop Index projections
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
return (place, curr_mode);
}
ProjectionKind::Deref => {}
ProjectionKind::Field(..) => {} // ignore
ProjectionKind::Subslice => {} // We never capture this
}
}
return (place, curr_mode);
}
/// Truncate deref of any reference.
fn adjust_for_move_closure<'tcx>(
mut place: Place<'tcx>,
mut kind: ty::UpvarCapture<'tcx>,
) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
if let Some(idx) = first_deref {
truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
}
// AMAN: I think we don't need the span inside the ByValue anymore
// we have more detailed span in CaptureInfo
(place, ty::UpvarCapture::ByValue(None))
}
/// Adjust closure capture just that if taking ownership of data, only move data
/// from enclosing stack frame.
fn adjust_for_non_move_closure<'tcx>(
mut place: Place<'tcx>,
mut kind: ty::UpvarCapture<'tcx>,
) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
let contains_deref =
place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
match kind {
ty::UpvarCapture::ByValue(..) => {
if let Some(idx) = contains_deref {
truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
}
}
ty::UpvarCapture::ByRef(..) => {}
}
(place, kind)
}
fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
let variable_name = match place.base {
PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
_ => bug!("Capture_information should only contain upvars"),
};
let mut projections_str = String::new();
for (i, item) in place.projections.iter().enumerate() {
let proj = match item.kind {
ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
ProjectionKind::Deref => String::from("Deref"),
ProjectionKind::Index => String::from("Index"),
ProjectionKind::Subslice => String::from("Subslice"),
};
if i != 0 {
projections_str.push(',');
}
projections_str.push_str(proj.as_str());
}
format!("{}[{}]", variable_name, projections_str)
}
fn construct_capture_kind_reason_string(
tcx: TyCtxt<'_>,
place: &Place<'tcx>,
capture_info: &ty::CaptureInfo<'tcx>,
) -> String {
let place_str = construct_place_string(tcx, &place);
let capture_kind_str = match capture_info.capture_kind {
ty::UpvarCapture::ByValue(_) => "ByValue".into(),
ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
};
format!("{} captured as {} here", place_str, capture_kind_str)
}
fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
let place_str = construct_place_string(tcx, &place);
format!("{} used here", place_str)
}
fn construct_capture_info_string(
tcx: TyCtxt<'_>,
place: &Place<'tcx>,
capture_info: &ty::CaptureInfo<'tcx>,
) -> String {
let place_str = construct_place_string(tcx, &place);
let capture_kind_str = match capture_info.capture_kind {
ty::UpvarCapture::ByValue(_) => "ByValue".into(),
ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
};
format!("{} -> {}", place_str, capture_kind_str)
}
fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
tcx.hir().name(var_hir_id)
}
fn should_do_rust_2021_incompatible_closure_captures_analysis(
tcx: TyCtxt<'_>,
closure_id: hir::HirId,
) -> bool {
let (level, _) =
tcx.lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id);
!matches!(level, lint::Level::Allow)
}
/// Return a two string tuple (s1, s2)
/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
/// - s2: Comma separated names of the variables being migrated.
fn migration_suggestion_for_2229(
tcx: TyCtxt<'_>,
need_migrations: &Vec<MigrationDiagnosticInfo>,
) -> (String, String) {
let need_migrations_variables =
need_migrations.iter().map(|(v, _)| var_name(tcx, *v)).collect::<Vec<_>>();
let migration_ref_concat =
need_migrations_variables.iter().map(|v| format!("&{}", v)).collect::<Vec<_>>().join(", ");
let migration_string = if 1 == need_migrations.len() {
format!("let _ = {}", migration_ref_concat)
} else {
format!("let _ = ({})", migration_ref_concat)
};
let migrated_variables_concat =
need_migrations_variables.iter().map(|v| format!("`{}`", v)).collect::<Vec<_>>().join(", ");
(migration_string, migrated_variables_concat)
}
/// Helper function to determine if we need to escalate CaptureKind from
/// CaptureInfo A to B and returns the escalated CaptureInfo.
/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
///
/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
///
/// It is the caller's duty to figure out which path_expr_id to use.
///
/// If both the CaptureKind and Expression are considered to be equivalent,
/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
/// expressions reported back to the user as part of diagnostics based on which appears earlier
/// in the closure. This can be achieved simply by calling
/// `determine_capture_info(existing_info, current_info)`. This works out because the
/// expressions that occur earlier in the closure body than the current expression are processed before.
/// Consider the following example
/// ```rust,no_run
/// struct Point { x: i32, y: i32 }
/// let mut p: Point { x: 10, y: 10 };
///
/// let c = || {
/// p.x += 10;
/// // ^ E1 ^
/// // ...
/// // More code
/// // ...
/// p.x += 10; // E2
/// // ^ E2 ^
/// };
/// ```
/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
/// and both have an expression associated, however for diagnostics we prefer reporting
/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
/// would've already handled `E1`, and have an existing capture_information for it.
/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
fn determine_capture_info(
capture_info_a: ty::CaptureInfo<'tcx>,
capture_info_b: ty::CaptureInfo<'tcx>,
) -> ty::CaptureInfo<'tcx> {
// If the capture kind is equivalent then, we don't need to escalate and can compare the
// expressions.
let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
(ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
// We don't need to worry about the spans being ignored here.
//
// The expr_id in capture_info corresponds to the span that is stored within
// ByValue(span) and therefore it gets handled with priortizing based on
// expressions below.
true
}
(ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
ref_a.kind == ref_b.kind
}
(ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
};
if eq_capture_kind {
match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
(Some(_), _) | (None, None) => capture_info_a,
(None, Some(_)) => capture_info_b,
}
} else {
// We select the CaptureKind which ranks higher based the following priority order:
// ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
(ty::UpvarCapture::ByValue(_), _) => capture_info_a,
(_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
(ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
match (ref_a.kind, ref_b.kind) {
// Take LHS:
(ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
| (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
// Take RHS:
(ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
| (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
(ty::ImmBorrow, ty::ImmBorrow)
| (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
| (ty::MutBorrow, ty::MutBorrow) => {
bug!("Expected unequal capture kinds");
}
}
}
}
}
}
/// Truncates `place` to have up to `len` projections.
/// `curr_mode` is the current required capture kind for the place.
/// Returns the truncated `place` and the updated required capture kind.
///
/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
/// contained `Deref` of `&mut`.
fn truncate_place_to_len_and_update_capture_kind(
place: &mut Place<'tcx>,
curr_mode: &mut ty::UpvarCapture<'tcx>,
len: usize,
) {
let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
// UniqueImmBorrow
// Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
// we don't need to worry about that case here.
match curr_mode {
ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: ty::BorrowKind::MutBorrow, region }) => {
for i in len..place.projections.len() {
if place.projections[i].kind == ProjectionKind::Deref
&& is_mut_ref(place.ty_before_projection(i))
{
*curr_mode = ty::UpvarCapture::ByRef(ty::UpvarBorrow {
kind: ty::BorrowKind::UniqueImmBorrow,
region,
});
break;
}
}
}
ty::UpvarCapture::ByRef(..) => {}
ty::UpvarCapture::ByValue(..) => {}
}
place.projections.truncate(len);
}
/// Determines the Ancestry relationship of Place A relative to Place B
///
/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
fn determine_place_ancestry_relation(
place_a: &Place<'tcx>,
place_b: &Place<'tcx>,
) -> PlaceAncestryRelation {
// If Place A and Place B, don't start off from the same root variable, they are divergent.
if place_a.base != place_b.base {
return PlaceAncestryRelation::Divergent;
}
// Assume of length of projections_a = n
let projections_a = &place_a.projections;
// Assume of length of projections_b = m
let projections_b = &place_b.projections;
let same_initial_projections =
iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a == proj_b);
if same_initial_projections {
// First min(n, m) projections are the same
// Select Ancestor/Descendant
if projections_b.len() >= projections_a.len() {
PlaceAncestryRelation::Ancestor
} else {
PlaceAncestryRelation::Descendant
}
} else {
PlaceAncestryRelation::Divergent
}
}
/// Reduces the precision of the captured place when the precision doesn't yeild any benefit from
/// borrow checking prespective, allowing us to save us on the size of the capture.
///
///
/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
/// and therefore capturing precise paths yields no benefit. This optimization truncates the
/// rightmost deref of the capture if the deref is applied to a shared ref.
///
/// Reason we only drop the last deref is because of the following edge case:
///
/// ```rust
/// struct MyStruct<'a> {
/// a: &'static A,
/// b: B,
/// c: C<'a>,
/// }
///
/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
/// let c = || drop(&*m.a.field_of_a);
/// // Here we really do want to capture `*m.a` because that outlives `'static`
///
/// // If we capture `m`, then the closure no longer outlives `'static'
/// // it is constrained to `'a`
/// }
/// ```
fn truncate_capture_for_optimization<'tcx>(
mut place: Place<'tcx>,
mut curr_mode: ty::UpvarCapture<'tcx>,
) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
// Find the right-most deref (if any). All the projections that come after this
// are fields or other "in-place pointer adjustments"; these refer therefore to
// data owned by whatever pointer is being dereferenced here.
let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
match idx {
// If that pointer is a shared reference, then we don't need those fields.
Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
}
None | Some(_) => {}
}
(place, curr_mode)
}
/// Precise capture is enabled if the feature gate `capture_disjoint_fields` is enabled or if
/// user is using Rust Edition 2021 or higher.
///
/// `span` is the span of the closure.
fn enable_precise_capture(tcx: TyCtxt<'_>, span: Span) -> bool {
// We use span here to ensure that if the closure was generated by a macro with a different
// edition.
tcx.features().capture_disjoint_fields || span.rust_2021()
}
| 42.549801 | 245 | 0.557147 |
0821e5eb33ac5051a9c0581e1aebcb7477407337 | 217 | use serde::{Deserialize, Serialize};
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NotificationMessage {
pub center_name: String,
pub address: String,
pub date: String,
}
| 24.111111 | 67 | 0.723502 |
f77aef957c765a4d19d3713819bb7aeb06dc60ae | 1,232 | use tide::prelude::*;
use tide::Request;
#[derive(Debug, Deserialize, Serialize)]
struct Animal {
name: String,
legs: u8,
}
#[async_std::main]
async fn main() -> tide::Result<()> {
tide::log::start();
let mut app = tide::new();
app.at("/").get(|_| async {
Ok(json!({
"message": "See below for available endpoints/actions",
"endpoints": {
"GET_ALL": "/posts",
"GET": "/posts/:id",
"POST": "/posts title body userID",
"PUT": "/posts id title body userId",
"PATCH": "/posts/:id title? body? userId?",
"DELETE": "/posts/:id"
}
}))
});
app.at("/posts").get(get_all_posts);
app.listen("localhost:8080").await?;
Ok(())
}
async fn get_all_posts(_: Request<()>) -> tide::Result {
let body = reqwest::get("https://jsonplaceholder.typicode.com/posts")
.await?
.text()
.await?;
Ok(format!("{}", body).into())
}
// async fn order_shoes(mut req: Request<()>) -> tide::Result {
// let Animal { name, legs } = req.body_json().await?;
// Ok(format!("Hello, {}! I've put in an order for {} shoes", name, legs).into())
// }
| 28.651163 | 85 | 0.512175 |
fb5ac6c34b608bb92dfec7677587e03c7571f01b | 1,071 | use anyhow::anyhow;
use cargo_metadata::Package;
use crate::licensed::Licensed;
pub fn run(root: &Package, packages: &[&Package]) -> anyhow::Result<()> {
let mut fail = 0;
let license = root.license();
for package in packages {
if package.id == root.id {
continue;
}
let can_include = license.can_include(&package.license());
if let Some(can_include) = can_include {
if !can_include {
log::error!(
"{} cannot include package {}, license {} is incompatible with {}",
root.name,
package.name,
package.license(),
license
);
fail += 1;
}
} else {
log::warn!("{} might not be able to include package {}, license {} is not known to be compatible with {}", root.name, package.name, package.license(), license);
}
}
if fail > 0 {
Err(anyhow!("Incompatible license"))
} else {
Ok(())
}
}
| 28.945946 | 172 | 0.495798 |
16f311e3cbc5b4f469ac379f43f23474494499f8 | 1,630 | use rmp_serde::{Deserializer, Serializer};
use serde::{Deserialize, Serialize};
use std::io::Cursor;
extern crate log;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct CapabilityConfiguration {
pub module: String,
#[serde(default)]
pub values: HashMap<String, String>,
}
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct HealthRequest {
pub placeholder: bool,
}
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct HealthResponse {
pub healthy: bool,
pub message: String,
}
/// The standard function for serializing codec structs into a format that can be
/// used for message exchange between actor and host. Use of any other function to
/// serialize could result in breaking incompatibilities.
pub(crate) fn serialize<T>(
item: T,
) -> ::std::result::Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>>
where
T: Serialize,
{
let mut buf = Vec::new();
item.serialize(&mut Serializer::new(&mut buf).with_struct_map())?;
Ok(buf)
}
/// The standard function for de-serializing codec structs from a format suitable
/// for message exchange between actor and host. Use of any other function to
/// deserialize could result in breaking incompatibilities.
pub(crate) fn deserialize<'de, T: Deserialize<'de>>(
buf: &[u8],
) -> ::std::result::Result<T, Box<dyn std::error::Error + Send + Sync>> {
let mut de = Deserializer::new(Cursor::new(buf));
match Deserialize::deserialize(&mut de) {
Ok(t) => Ok(t),
Err(e) => Err(format!("Failed to de-serialize: {}", e).into()),
}
}
| 30.754717 | 82 | 0.688344 |
56d1144755a383105df425b81b85e5fec3a0b80a | 133 |
struct Point {
x:i32,
y:i32
}
fn main() {
let p = Point{x:2,y:3};
let t = p.x + p.y;
println!("{}", t);
} | 9.5 | 26 | 0.406015 |
229238fb36096231e63307d9e9387bd7630e9644 | 569 | <?xml version="1.0" encoding="UTF-8"?>
<WebElementEntity>
<description>Title of the start page content</description>
<name>ContentTitle</name>
<tag></tag>
<elementGuidId>98019a29-3719-4569-bd11-2a56c050ba4c</elementGuidId>
<selectorCollection>
<entry>
<key>CSS</key>
<value>.content > h1</value>
</entry>
<entry>
<key>BASIC</key>
<value></value>
</entry>
</selectorCollection>
<selectorMethod>CSS</selectorMethod>
<useRalativeImagePath>false</useRalativeImagePath>
</WebElementEntity>
| 28.45 | 70 | 0.648506 |
6a7adb6805b2bed7ef6ced566cb1a3b3839fb975 | 1,592 | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Common widgets.
mod align;
pub use crate::widget::align::Align;
mod button;
pub use crate::widget::button::Button;
mod label;
pub use crate::widget::label::{DynLabel, Label, LabelText};
mod either;
pub use crate::widget::either::Either;
mod flex;
pub use crate::widget::flex::{Column, Flex, Row};
mod padding;
pub use crate::widget::padding::Padding;
mod scroll;
pub use crate::widget::scroll::Scroll;
mod progress_bar;
pub use crate::widget::progress_bar::ProgressBar;
mod slider;
pub use crate::widget::slider::Slider;
mod textbox;
pub use crate::widget::textbox::TextBox;
mod sized_box;
pub use crate::widget::sized_box::SizedBox;
mod checkbox;
pub use crate::widget::checkbox::Checkbox;
mod radio;
pub use crate::widget::radio::{Radio, RadioGroup};
mod container;
pub use crate::widget::container::Container;
mod split;
pub use crate::widget::split::Split;
mod switch;
pub use crate::widget::switch::Switch;
mod env_scope;
pub use crate::widget::env_scope::EnvScope;
| 23.761194 | 75 | 0.73995 |
23793606d310b01a085dfe43fee2e8faa40b4e59 | 16,620 | use diplomat_core::Env;
use std::fmt;
use std::fmt::Write;
use diplomat_core::ast;
use indenter::indented;
use crate::cpp::config::LibraryConfig;
use crate::cpp::util::{gen_comment_block, transform_keyword_ident};
use super::conversions::{gen_cpp_to_rust, gen_rust_to_cpp};
use super::types::gen_type;
pub fn gen_struct<W: fmt::Write>(
custom_type: &ast::CustomType,
in_path: &ast::Path,
is_header: bool,
env: &Env,
library_config: &LibraryConfig,
docs_url_gen: &ast::DocsUrlGenerator,
out: &mut W,
) -> fmt::Result {
if is_header {
writeln!(
out,
"/**\n * A destruction policy for using {} with {}.\n */",
custom_type.name(),
library_config.unique_ptr.name,
)?;
writeln!(out, "struct {}Deleter {{", custom_type.name())?;
let mut deleter_body = indented(out).with_str(" ");
writeln!(
&mut deleter_body,
"void operator()(capi::{}* l) const noexcept {{",
custom_type.name()
)?;
let mut deleter_operator_body = indented(&mut deleter_body).with_str(" ");
writeln!(
&mut deleter_operator_body,
"capi::{}_destroy(l);",
custom_type.name()
)?;
writeln!(&mut deleter_body, "}}")?;
writeln!(out, "}};")?;
}
match custom_type {
ast::CustomType::Opaque(opaque) => {
if is_header {
gen_comment_block(out, &opaque.docs.to_markdown(docs_url_gen))?;
writeln!(out, "class {} {{", opaque.name)?;
writeln!(out, " public:")?;
}
let mut public_body = if is_header {
indented(out).with_str(" ")
} else {
indented(out).with_str("")
};
for method in &opaque.methods {
gen_method(
custom_type,
method,
in_path,
is_header,
true,
env,
library_config,
docs_url_gen,
&mut public_body,
)?;
}
if is_header {
writeln!(
&mut public_body,
"inline const capi::{}* AsFFI() const {{ return this->inner.get(); }}",
opaque.name
)?;
writeln!(
&mut public_body,
"inline capi::{}* AsFFIMut() {{ return this->inner.get(); }}",
opaque.name
)?;
writeln!(
&mut public_body,
"inline {}(capi::{}* i) : inner(i) {{}}",
opaque.name, opaque.name
)?;
writeln!(
&mut public_body,
"{0}() = default;\n{0}({0}&&) noexcept = default;\n{0}& operator=({0}&& other) noexcept = default;",
opaque.name
)?;
writeln!(out, " private:")?;
let mut private_body = indented(out).with_str(" ");
writeln!(
&mut private_body,
"{}<capi::{}, {}Deleter> inner;",
library_config.unique_ptr.expr, opaque.name, opaque.name
)?;
writeln!(out, "}};")?;
}
}
ast::CustomType::Struct(strct) => {
if is_header {
gen_comment_block(out, &strct.docs.to_markdown(docs_url_gen))?;
writeln!(out, "struct {} {{", strct.name)?;
writeln!(out, " public:")?;
}
let mut public_body = if is_header {
indented(out).with_str(" ")
} else {
indented(out).with_str("")
};
if is_header {
for (name, typ, docs) in &strct.fields {
let ty_name = gen_type(typ, in_path, None, env, library_config)?;
gen_comment_block(&mut public_body, &docs.to_markdown(docs_url_gen))?;
writeln!(&mut public_body, "{} {};", ty_name, name)?;
}
}
for method in &strct.methods {
gen_method(
custom_type,
method,
in_path,
is_header,
true,
env,
library_config,
docs_url_gen,
&mut public_body,
)?;
}
if is_header {
writeln!(out, "}};")?;
}
}
ast::CustomType::Enum(_) => {}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn gen_method<W: fmt::Write>(
enclosing_type: &ast::CustomType,
method: &ast::Method,
in_path: &ast::Path,
is_header: bool,
// should it convert writeables to string as an additional method?
writeable_to_string: bool,
env: &Env,
library_config: &LibraryConfig,
docs_url_gen: &ast::DocsUrlGenerator,
out: &mut W,
) -> fmt::Result {
// This method should rearrange the writeable
let rearranged_writeable = method.is_writeable_out() && writeable_to_string;
// This method has some writeable param that is preserved
let has_writeable_param = method.has_writeable_param() && !writeable_to_string;
if rearranged_writeable {
// generate the normal method too
gen_method(
enclosing_type,
method,
in_path,
is_header,
false,
env,
library_config,
docs_url_gen,
out,
)?;
}
if is_header {
gen_comment_block(out, &method.docs.to_markdown(docs_url_gen))?;
}
let params_to_gen = gen_method_interface(
method,
enclosing_type,
in_path,
is_header,
has_writeable_param,
rearranged_writeable,
env,
library_config,
out,
writeable_to_string,
)?;
if is_header {
writeln!(out, ";")?;
} else {
writeln!(out, " {{")?;
let mut method_body = indented(out).with_str(" ");
let mut all_params_invocation = vec![];
if let Some(param) = &method.self_param {
let invocation_expr = gen_cpp_to_rust(
"this",
"this",
None,
¶m.ty,
in_path,
env,
true,
&mut method_body,
);
all_params_invocation.push(invocation_expr);
}
for param in params_to_gen.iter() {
match param.ty {
ast::TypeName::StrReference(_) | ast::TypeName::PrimitiveSlice(_, _) => {
all_params_invocation.push(format!("{}.data()", param.name));
all_params_invocation.push(format!("{}.size()", param.name));
}
_ => {
let invocation_expr = gen_cpp_to_rust(
¶m.name,
¶m.name,
None,
¶m.ty,
in_path,
env,
param.name == "self",
&mut method_body,
);
all_params_invocation.push(invocation_expr);
}
}
}
if rearranged_writeable {
all_params_invocation.push("&diplomat_writeable_out".to_string());
writeln!(&mut method_body, "std::string diplomat_writeable_string;")?;
writeln!(&mut method_body, "capi::DiplomatWriteable diplomat_writeable_out = diplomat::WriteableFromString(diplomat_writeable_string);")?;
}
match &method.return_type {
None | Some(ast::TypeName::Unit) => {
writeln!(
&mut method_body,
"capi::{}({});",
method.full_path_name,
all_params_invocation.join(", ")
)?;
if rearranged_writeable {
writeln!(&mut method_body, "return diplomat_writeable_string;")?;
}
}
Some(ret_typ) => {
let out_expr = gen_rust_to_cpp(
&format!(
"capi::{}({})",
method.full_path_name,
all_params_invocation.join(", ")
),
"out_value",
ret_typ,
in_path,
env,
library_config,
&mut method_body,
);
if rearranged_writeable {
gen_writeable_out_value(&out_expr, ret_typ, &mut method_body)?;
} else {
writeln!(&mut method_body, "return {};", out_expr)?;
}
}
}
writeln!(out, "}}")?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn gen_method_interface<W: fmt::Write>(
method: &ast::Method,
enclosing_type: &ast::CustomType,
in_path: &ast::Path,
is_header: bool,
has_writeable_param: bool,
rearranged_writeable: bool,
env: &Env,
library_config: &LibraryConfig,
out: &mut W,
writeable_to_string: bool,
) -> Result<Vec<ast::Param>, fmt::Error> {
if has_writeable_param {
write!(out, "template<typename W> ")?;
}
if !is_header {
write!(out, "inline ")?;
}
let mut is_const = false;
if let Some(ref param) = method.self_param {
if let ast::TypeName::Reference(_, mutable, _lt) = ¶m.ty {
is_const = mutable.is_immutable();
}
} else if is_header {
write!(out, "static ")?;
}
if rearranged_writeable {
if let Some(ast::TypeName::Result(_, err)) = &method.return_type {
let err_ty = if err.is_zst() {
"std::monostate".into()
} else {
gen_type(err, in_path, None, env, library_config)?
};
write!(out, "diplomat::result<std::string, {}>", err_ty)?;
} else {
write!(out, "std::string")?;
}
} else {
let ty_name = match &method.return_type {
Some(ret_type) => gen_type(ret_type, in_path, None, env, library_config)?,
None => "void".into(),
};
write!(out, "{}", ty_name)?;
}
if is_header {
write!(out, " ")?;
} else {
write!(out, " {}::", enclosing_type.name())?;
}
if has_writeable_param {
write!(out, "{}_to_writeable(", method.name)?;
} else {
write!(out, "{}(", transform_keyword_ident(&method.name))?;
}
let mut params_to_gen = method.params.clone();
if rearranged_writeable {
params_to_gen.remove(params_to_gen.len() - 1);
}
for (i, param) in params_to_gen.iter().enumerate() {
if i != 0 {
write!(out, ", ")?;
}
let ty_name = if param.is_writeable() && !writeable_to_string {
"W&".into()
} else {
gen_type(¶m.ty, in_path, None, env, library_config)?
};
write!(out, "{} {}", ty_name, param.name)?;
}
write!(out, ")")?;
if is_const {
write!(out, " const")?
}
Ok(params_to_gen)
}
fn gen_writeable_out_value<W: fmt::Write>(
out_expr: &str,
ret_typ: &ast::TypeName,
method_body: &mut W,
) -> fmt::Result {
if let ast::TypeName::Result(_, _) = ret_typ {
writeln!(
method_body,
"return {}.replace_ok(std::move(diplomat_writeable_string));",
out_expr
)?;
} else {
panic!("Not in writeable out form")
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn test_simple_non_opaque_struct() {
test_file! {
#[diplomat::bridge]
mod ffi {
struct MyStruct {
a: u8,
b: u8,
}
impl MyStruct {
pub fn new(a: u8, b: u8) -> MyStruct {
unimplemented!()
}
pub fn get_a(&self) -> u8 {
unimplemented!()
}
pub fn set_b(&mut self, b: u8) {
unimplemented!()
}
}
}
}
}
#[test]
fn test_simple_opaque_struct() {
test_file! {
#[diplomat::bridge]
mod ffi {
#[diplomat::opaque]
struct MyStruct(UnknownType);
impl MyStruct {
pub fn new(a: u8, b: u8) -> Box<MyStruct> {
unimplemented!()
}
pub fn get_a(&self) -> u8 {
unimplemented!()
}
pub fn set_b(&mut self, b: u8) {
unimplemented!()
}
}
}
}
}
#[test]
fn test_method_taking_str() {
test_file! {
#[diplomat::bridge]
mod ffi {
#[diplomat::opaque]
struct MyStruct(UnknownType);
impl MyStruct {
pub fn new_str(v: &str) -> Box<MyStruct> {
unimplemented!()
}
pub fn set_str(&mut self, new_str: &str) {
unimplemented!()
}
}
}
}
}
#[test]
fn test_method_taking_slice() {
test_file! {
#[diplomat::bridge]
mod ffi {
#[diplomat::opaque]
struct MyStruct(UnknownType);
impl MyStruct {
pub fn new_slice(v: &[f64]) -> Box<MyStruct> {
unimplemented!()
}
pub fn set_slice(&mut self, new_slice: &[f64]) {
unimplemented!()
}
}
}
}
}
#[test]
fn test_method_taking_slice_using_library_config() {
test_file_using_library_config! {
#[diplomat::bridge]
mod ffi {
#[diplomat::opaque]
struct MyStruct(UnknownType);
impl MyStruct {
pub fn new_slice(v: &[f64]) -> Box<MyStruct> {
unimplemented!()
}
pub fn set_slice(&mut self, new_slice: &[f64]) {
unimplemented!()
}
}
}
}
}
#[test]
fn test_method_writeable_out() {
test_file! {
#[diplomat::bridge]
mod ffi {
#[diplomat::opaque]
struct MyStruct(UnknownType);
impl MyStruct {
pub fn write(&self, out: &mut DiplomatWriteable) {
unimplemented!()
}
pub fn write_unit(&self, out: &mut DiplomatWriteable) -> () {
unimplemented!()
}
pub fn write_result(&self, out: &mut DiplomatWriteable) -> DiplomatResult<(), u8> {
unimplemented!()
}
pub fn write_no_rearrange(&self, out: &mut DiplomatWriteable) -> u8 {
unimplemented!()
}
}
}
}
}
#[test]
fn test_struct_documentation() {
test_file! {
#[diplomat::bridge]
mod ffi {
/// Documentation for Foo.
/// Second line.
#[diplomat::rust_link(foo::Bar, Struct)]
struct Foo {
/// Documentation for x.
x: u8,
}
impl Foo {
/// Documentation for get_x.
#[diplomat::rust_link(foo::Bar::get, FnInStruct)]
pub fn get_x(&self) -> u8 {
x
}
}
}
}
}
}
| 28.954704 | 150 | 0.440493 |
6960adfad74cf7944e6b87f93651be07eab490a2 | 21,936 | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_digitalassetlinks1 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::Digitalassetlinks<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _assetlinks_check(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.assetlinks().check();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"target-web-site" => {
call = call.target_web_site(value.unwrap_or(""));
},
"target-android-app-package-name" => {
call = call.target_android_app_package_name(value.unwrap_or(""));
},
"target-android-app-certificate-sha256-fingerprint" => {
call = call.target_android_app_certificate_sha256_fingerprint(value.unwrap_or(""));
},
"source-web-site" => {
call = call.source_web_site(value.unwrap_or(""));
},
"source-android-app-package-name" => {
call = call.source_android_app_package_name(value.unwrap_or(""));
},
"source-android-app-certificate-sha256-fingerprint" => {
call = call.source_android_app_certificate_sha256_fingerprint(value.unwrap_or(""));
},
"relation" => {
call = call.relation(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["target-android-app-certificate-sha256-fingerprint", "source-android-app-certificate-sha256-fingerprint", "target-web-site", "source-web-site", "target-android-app-package-name", "relation", "source-android-app-package-name"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _statements_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.statements().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"source-web-site" => {
call = call.source_web_site(value.unwrap_or(""));
},
"source-android-app-package-name" => {
call = call.source_android_app_package_name(value.unwrap_or(""));
},
"source-android-app-certificate-sha256-fingerprint" => {
call = call.source_android_app_certificate_sha256_fingerprint(value.unwrap_or(""));
},
"relation" => {
call = call.relation(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["source-web-site", "source-android-app-certificate-sha256-fingerprint", "relation", "source-android-app-package-name"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("assetlinks", Some(opt)) => {
match opt.subcommand() {
("check", Some(opt)) => {
call_result = self._assetlinks_check(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("assetlinks".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("statements", Some(opt)) => {
match opt.subcommand() {
("list", Some(opt)) => {
call_result = self._statements_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("statements".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "digitalassetlinks1-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "digitalassetlinks1",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::Digitalassetlinks::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "callback", "fields", "key", "oauth-token", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("assetlinks", "methods: 'check'", vec."##),
"Details at http://byron.github.io/google-apis-rs/google_digitalassetlinks1_cli/assetlinks_check",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("statements", "methods: 'list'", vec.
Specifically, you should consider that for insecure websites (that is,
where the URL starts with `http://` instead of `https://`), this guarantee
cannot be made.
The `List` command is most useful in cases where the API client wants to
know all the ways in which two assets are related, or enumerate all the
relationships from a particular source asset. Example: a feature that
helps users navigate to related items. When a mobile app is running on a
device, the feature would make it easy to navigate to the corresponding web
site or Google+ profile."##),
"Details at http://byron.github.io/google-apis-rs/google_digitalassetlinks1_cli/statements_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("digitalassetlinks1")
.author("Sebastian Thiel <[email protected]>")
.version("1.0.14+20200702")
.about("Discovers relationships between online assets such as websites or mobile apps.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_digitalassetlinks1_cli")
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
} | 47.480519 | 526 | 0.482722 |
89a344bdb7b3c13d62d657dc95f1e215fc009663 | 3,968 | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use std::cmp::{Ordering, Equal, Less, Greater};
use std::vec_ng::Vec;
pub fn expand_deriving_totalord(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "TotalOrd")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "cmp",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("std", "cmp", "Ordering"))),
inline: true,
const_nonmatching: false,
combine_substructure: cs_cmp
}
)
};
trait_def.expand(cx, mitem, item, push)
}
pub fn ordering_const(cx: &mut ExtCtxt, span: Span, cnst: Ordering) -> ast::Path {
let cnst = match cnst {
Less => "Less",
Equal => "Equal",
Greater => "Greater"
};
cx.path_global(span,
vec!(cx.ident_of("std"),
cx.ident_of("cmp"),
cx.ident_of(cnst)))
}
pub fn cs_cmp(cx: &mut ExtCtxt, span: Span,
substr: &Substructure) -> @Expr {
let test_id = cx.ident_of("__test");
let equals_path = ordering_const(cx, span, Equal);
/*
Builds:
let __test = self_field1.cmp(&other_field2);
if other == ::std::cmp::Equal {
let __test = self_field2.cmp(&other_field2);
if __test == ::std::cmp::Equal {
...
} else {
__test
}
} else {
__test
}
FIXME #6449: These `if`s could/should be `match`es.
*/
cs_same_method_fold(
// foldr nests the if-elses correctly, leaving the first field
// as the outermost one, and the last as the innermost.
false,
|cx, span, old, new| {
// let __test = new;
// if __test == ::std::cmp::Equal {
// old
// } else {
// __test
// }
let assign = cx.stmt_let(span, false, test_id, new);
let cond = cx.expr_binary(span, ast::BiEq,
cx.expr_ident(span, test_id),
cx.expr_path(equals_path.clone()));
let if_ = cx.expr_if(span,
cond,
old, Some(cx.expr_ident(span, test_id)));
cx.expr_block(cx.block(span, vec!(assign), Some(if_)))
},
cx.expr_path(equals_path.clone()),
|cx, span, list, _| {
match list {
// an earlier nonmatching variant is Less than a
// later one.
[(self_var, _, _),
(other_var, _, _)] => {
let order = ordering_const(cx, span, self_var.cmp(&other_var));
cx.expr_path(order)
}
_ => cx.span_bug(span, "not exactly 2 arguments in `deriving(TotalOrd)`")
}
},
cx, span, substr)
}
| 32.793388 | 89 | 0.506048 |
9cc81c52ef41c2d86e6a754370d484e9cc8c62b8 | 275 | fn swap<T>(v: ~[mut T], i: int, j: int) { v[i] <-> v[j]; }
fn main() {
let a: ~[mut int] = ~[mut 0, 1, 2, 3, 4, 5, 6];
swap(a, 2, 4);
assert (a[2] == 4);
assert (a[4] == 2);
let mut n = 42;
n <-> a[0];
assert (a[0] == 42);
assert (n == 0);
}
| 21.153846 | 58 | 0.381818 |
14f1b0c69b8c80a8423e8de2dbe90ad0c3acb51d | 665 | #![feature(extern_crate_item_prelude)]
#![allow(unused_imports)]
extern crate tvm_frontend as tvm;
use tvm::*;
fn main() {
fn sum(args: &[TVMArgValue]) -> Result<TVMRetValue> {
let mut ret = 0;
for arg in args.iter() {
ret += arg.to_int();
}
let ret_val = TVMRetValue::from(&ret);
Ok(ret_val)
}
tvm::function::register(sum, "mysum".to_owned(), false).unwrap();
let mut registered = function::Builder::default();
registered.get_function("mysum", true);
assert!(registered.func.is_some());
registered.args(&[10, 20, 30]);
assert_eq!(registered.invoke().unwrap().to_int(), 60);
}
| 26.6 | 69 | 0.607519 |
de5e2d4371685e68eb4b046a79194fded7f41e54 | 1,981 | #[macro_use]
extern crate yaserde;
#[macro_use]
extern crate yaserde_derive;
use std::io::{Read, Write};
use yaserde::{YaDeserialize, YaSerialize};
#[test]
fn ser_type() {
test_for_type!(String, "test".to_string(), Some("test"));
test_for_type!(bool, true, Some("true"));
test_for_type!(u8, 12 as u8, Some("12"));
test_for_type!(i8, 12 as i8, Some("12"));
test_for_type!(i8, -12 as i8, Some("-12"));
test_for_type!(u16, 12 as u16, Some("12"));
test_for_type!(i16, 12 as i16, Some("12"));
test_for_type!(i16, -12 as i16, Some("-12"));
test_for_type!(u32, 12 as u32, Some("12"));
test_for_type!(i32, 12 as i32, Some("12"));
test_for_type!(i32, -12 as i32, Some("-12"));
test_for_type!(u64, 12 as u64, Some("12"));
test_for_type!(i64, 12 as i64, Some("12"));
test_for_type!(i64, -12 as i64, Some("-12"));
test_for_type!(f32, -12.5 as f32, Some("-12.5"));
test_for_type!(f64, -12.5 as f64, Some("-12.5"));
test_for_type!(Vec::<String>, vec![], None);
test_for_type!(Vec::<String>, vec!["test".to_string()], Some("test"));
test_for_attribute_type!(String, "test".to_string(), Some("test"));
test_for_attribute_type!(bool, true, Some("true"));
test_for_attribute_type!(u8, 12 as u8, Some("12"));
test_for_attribute_type!(i8, 12 as i8, Some("12"));
test_for_attribute_type!(i8, -12 as i8, Some("-12"));
test_for_attribute_type!(u16, 12 as u16, Some("12"));
test_for_attribute_type!(i16, 12 as i16, Some("12"));
test_for_attribute_type!(i16, -12 as i16, Some("-12"));
test_for_attribute_type!(u32, 12 as u32, Some("12"));
test_for_attribute_type!(i32, 12 as i32, Some("12"));
test_for_attribute_type!(i32, -12 as i32, Some("-12"));
test_for_attribute_type!(u64, 12 as u64, Some("12"));
test_for_attribute_type!(i64, 12 as i64, Some("12"));
test_for_attribute_type!(i64, -12 as i64, Some("-12"));
test_for_attribute_type!(f32, -12.5 as f32, Some("-12.5"));
test_for_attribute_type!(f64, -12.5 as f64, Some("-12.5"));
}
| 42.148936 | 72 | 0.659768 |
01141e204ca592e75897dcef476f8635e8f0667c | 4,834 | use openexr_sys as sys;
use std::ffi::{CStr, CString};
use crate::refptr::{OpaquePtr, Ref, RefMut};
#[repr(transparent)]
pub struct CppString(pub(crate) *mut sys::std_string_t);
unsafe impl OpaquePtr for CppString {
type SysPointee = sys::std_string_t;
type Pointee = CppString;
}
pub type CppStringRef<'a, P = CppString> = Ref<'a, P>;
pub type CppStringRefMut<'a, P = CppString> = RefMut<'a, P>;
impl CppString {
pub fn new(string: &str) -> CppString {
let cstring = CString::new(string).expect("Inner NUL bytes in string");
unsafe {
let mut ptr = std::ptr::null_mut();
sys::std_string_ctor(&mut ptr);
let mut dummy = std::ptr::null_mut();
sys::std_string_assign(
ptr,
&mut dummy,
cstring.as_ptr(),
cstring.as_bytes().len() as u64,
);
CppString(ptr)
}
}
pub fn as_str(self: &CppString) -> &str {
let mut cptr = std::ptr::null();
unsafe {
sys::std_string_c_str(self.0, &mut cptr);
CStr::from_ptr(cptr).to_str().unwrap()
}
}
}
impl Drop for CppString {
fn drop(&mut self) {
unsafe {
sys::std_string_dtor(self.0);
}
}
}
#[repr(transparent)]
pub struct CppVectorFloat(pub(crate) *mut sys::std_vector_float_t);
unsafe impl OpaquePtr for CppVectorFloat {
type SysPointee = sys::std_vector_float_t;
type Pointee = CppVectorFloat;
}
pub type CppVectorFloatRef<'a, P = CppVectorFloat> = Ref<'a, P>;
pub type CppVectorFloatRefMut<'a, P = CppVectorFloat> = RefMut<'a, P>;
impl CppVectorFloat {
pub fn new() -> CppVectorFloat {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::std_vector_float_ctor(&mut ptr).into_result().unwrap();
}
CppVectorFloat(ptr)
}
pub fn from_slice(vec: &[f32]) -> CppVectorFloat {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::std_vector_float_ctor(&mut ptr).into_result().unwrap();
for rs in vec {
sys::std_vector_float_push_back(ptr, rs)
.into_result()
.unwrap();
}
}
CppVectorFloat(ptr)
}
pub fn as_slice(&self) -> &[f32] {
let mut size = 0;
let mut ptr = std::ptr::null();
unsafe {
sys::std_vector_float_size(self.0, &mut size);
sys::std_vector_float_data_const(self.0, &mut ptr);
std::slice::from_raw_parts(ptr, size as usize)
}
}
pub fn as_slice_mut(&mut self) -> &mut [f32] {
let mut size = 0;
let mut ptr = std::ptr::null_mut();
unsafe {
sys::std_vector_float_size(self.0, &mut size);
sys::std_vector_float_data(self.0, &mut ptr);
std::slice::from_raw_parts_mut(ptr, size as usize)
}
}
}
#[repr(transparent)]
pub struct CppVectorString(pub(crate) *mut sys::std_vector_string_t);
unsafe impl OpaquePtr for CppVectorString {
type SysPointee = sys::std_vector_string_t;
type Pointee = CppVectorString;
}
pub type CppVectorStringRef<'a, P = CppVectorString> = Ref<'a, P>;
pub type CppVectorStringRefMut<'a, P = CppVectorString> = RefMut<'a, P>;
impl CppVectorString {
pub fn new() -> CppVectorString {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::std_vector_string_ctor(&mut ptr).into_result().unwrap();
}
CppVectorString(ptr)
}
pub fn from_slice<S: AsRef<str>>(vec: &[S]) -> CppVectorString {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::std_vector_string_ctor(&mut ptr).into_result().unwrap();
for rs in vec {
let s = CppString::new(rs.as_ref());
sys::std_vector_string_push_back(ptr, s.0)
.into_result()
.unwrap();
}
}
CppVectorString(ptr)
}
pub unsafe fn get_unchecked(&self, pos: usize) -> CppStringRef {
let mut ptr = std::ptr::null();
sys::std_vector_string_index(self.0, &mut ptr, pos as u64);
CppStringRef::new(ptr)
}
pub fn to_vec(&self) -> Vec<String> {
let mut size = 0;
unsafe {
sys::std_vector_string_size(self.0, &mut size);
let mut result = Vec::with_capacity(size as usize);
for i in 0..size {
let mut sptr = std::ptr::null();
sys::std_vector_string_index(self.0, &mut sptr, i);
let mut cptr = std::ptr::null();
sys::std_string_c_str(sptr, &mut cptr);
result.push(CStr::from_ptr(cptr).to_string_lossy().to_string());
}
result
}
}
}
| 29.120482 | 80 | 0.55813 |
db45f416c1f6a876f98f18edc362e00ab227c8c2 | 327 | pub mod ast;
pub mod ast_util;
pub mod context;
pub mod emitter;
pub mod errors;
pub mod model;
pub mod parser;
pub mod scope_map;
pub mod smt_manager;
#[macro_use]
pub mod printer;
mod block_to_assert;
mod closure;
mod def;
mod smt_process;
mod smt_verify;
mod tests;
mod typecheck;
mod util;
mod var_to_const;
mod visitor;
| 13.625 | 20 | 0.767584 |
7a7a508ffaef141660110ea67392f0a7221a37cb | 18,838 | use super::Name;
use crate::method::{Error, Method, ResponseType, Result};
use crate::rpc::monitor::Monitor;
use sint::ql::pg::models;
use sint::ql::pg::{pool::Con, rule};
use serde_derive::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::default::Default;
use log::warn;
#[derive(Debug, Serialize, Deserialize)]
pub struct Master {
pub operator: String,
pub enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub critical: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub major: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub minor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub warning: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cleared: Option<String>,
pub rops_alarmed: Option<String>,
pub interval: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub deviation_window: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hysteresis_factor: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub indicator_exposed: Option<String>,
pub indicator_name: String,
}
impl From<models::Master> for Master {
fn from(m: models::Master) -> Master {
Master {
operator: m.operator,
enabled: Some(m.enabled),
critical: m.critical,
major: m.major,
minor: m.minor,
warning: m.warning,
cleared: m.cleared,
rops_alarmed: Some(m.rops_alarmed),
interval: Some(m.interval),
deviation_window: m.deviation_window,
hysteresis_factor: m.hysteresis_factor,
indicator_exposed: m.indicator_exposed,
indicator_name: m.indicator_name,
}
}
}
impl Default for Master {
fn default() -> Self {
Master {
operator: String::from(""),
enabled: Some(false),
critical: None,
major: None,
minor: None,
warning: None,
cleared: None,
rops_alarmed: None,
interval: None,
deviation_window: None,
hysteresis_factor: None,
indicator_exposed: None,
indicator_name: String::from(""),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Guard {
pub operator: String,
pub threshold: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub rops_alarmed: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub indicator_exposed: Option<String>,
pub indicator_name: String,
}
impl From<models::Guard> for Guard {
fn from(g: models::Guard) -> Guard {
Guard {
operator: g.operator,
threshold: g.threshold,
rops_alarmed: Some(g.rops_alarmed),
indicator_exposed: g.indicator_exposed,
indicator_name: g.indicator_name,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Filter {
pub kind: String,
pub value: String,
}
impl From<models::Filter> for Filter {
fn from(f: models::Filter) -> Filter {
Filter {
kind: f.kind,
value: f.value,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MonitorRule {
pub monitor: Monitor,
pub master: Master,
#[serde(skip_serializing_if = "Option::is_none")]
pub guard: Option<Guard>,
#[serde(skip_serializing_if = "Option::is_none")]
pub filter: Option<Filter>,
}
impl MonitorRule {
fn new(monitor: Monitor) -> MonitorRule {
MonitorRule {
monitor,
master: Default::default(),
guard: None,
filter: None,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Rule {
pub service: String,
pub monitor: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub master: Option<Master>,
#[serde(skip_serializing_if = "Option::is_none")]
pub guard: Option<Guard>,
#[serde(skip_serializing_if = "Option::is_none")]
pub filter: Option<Filter>,
}
impl Rule {
fn etries(
self,
) -> (
Option<models::MasterEntry>,
Option<models::GuardEntry>,
Option<models::FilterEntry>,
) {
let Rule {
service,
monitor,
master,
guard,
filter,
} = self;
let master_entry = master.and_then(|rule_master| {
Some(models::MasterEntry {
enabled: rule_master.enabled.unwrap_or(true),
operator: rule_master.operator,
critical: rule_master.critical,
major: rule_master.major,
minor: rule_master.minor,
warning: rule_master.warning,
cleared: rule_master.cleared,
rops_alarmed: rule_master.rops_alarmed.unwrap_or(String::from("1")),
interval: rule_master.interval.unwrap_or(15),
deviation_window: rule_master.deviation_window,
hysteresis_factor: rule_master.hysteresis_factor,
indicator_exposed: rule_master.indicator_exposed,
indicator_name: rule_master.indicator_name,
monitor_name: monitor.to_owned(),
service_uri: service.to_owned(),
})
});
let guard_entry = guard.and_then(|rule_guard| {
Some(models::GuardEntry {
operator: rule_guard.operator,
threshold: rule_guard.threshold,
rops_alarmed: rule_guard.rops_alarmed.unwrap_or(String::from("1")),
indicator_exposed: rule_guard.indicator_exposed,
indicator_name: rule_guard.indicator_name,
monitor_name: monitor.to_owned(),
service_uri: service.to_owned(),
})
});
let filter_entry = filter.and_then(|rule_filter| {
Some(models::FilterEntry {
kind: rule_filter.kind,
value: rule_filter.value,
monitor_name: monitor,
service_uri: service,
})
});
(master_entry, guard_entry, filter_entry)
}
}
// ListOut is a map {<service-uri>: {<monitor-name>: MonitorRule}}
pub type ListOut = BTreeMap<String, BTreeMap<String, MonitorRule>>;
/// List lists all monitor rule that has the given service name (uri).
pub struct List {
con: Con,
}
impl List {
pub fn new(con: Con) -> Self {
List { con }
}
}
impl Method for List {
type Input = Name;
type Output = ListOut;
fn name(&self) -> &'static str {
"ListMonitorRule"
}
fn call(&self, params: Option<Self::Input>) -> Result<Self::Output> {
let service_name: String = params
.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("ListMonitorRule missing param"),
})
.map(|n| n.name)?;
let the_list = rule::list(&service_name, &self.con)
.map_err(|e| Error::query_error("ListMonitorRule", e))?;
let mut rules: Self::Output = BTreeMap::new();
let (monitors, masters, guards, filters) = the_list;
let monitors_map: BTreeMap<String, Monitor> =
monitors.into_iter().fold(BTreeMap::new(), |mut a, m| {
let monitor = Monitor::from(m);
a.entry(monitor.name.to_owned()).or_insert(monitor);
a
});
for master_model in masters.into_iter().flatten() {
let service_uri = master_model.service_uri.to_owned();
let monitor_name = master_model.monitor_name.to_owned();
let monitor = match monitors_map.get(&monitor_name) {
Some(mon) => mon,
None => {
warn!("Monitor with name {} not found in list", &monitor_name);
warn!(
"Master {:?} not included in ListMonitorRule response",
&master_model
);
continue;
}
};
let master = Master::from(master_model);
let service_entry = rules.entry(service_uri).or_insert(BTreeMap::new());
let monitor_rule_entry = service_entry
.entry(monitor_name)
.or_insert(MonitorRule::new(monitor.clone()));
monitor_rule_entry.master = master;
}
for guard_model in guards.into_iter().flatten() {
let service_uri = guard_model.service_uri.to_owned();
let monitor_name = guard_model.monitor_name.to_owned();
let monitor = match monitors_map.get(&monitor_name) {
Some(mon) => mon,
None => {
warn!("Monitor with name {} not found in list", &monitor_name);
warn!(
"Guard {:?} not included in ListMonitorRule response",
&guard_model
);
continue;
}
};
let guard = Guard::from(guard_model);
let service_entry = rules.entry(service_uri).or_insert(BTreeMap::new());
let monitor_rule_entry = service_entry
.entry(monitor_name)
.or_insert(MonitorRule::new(monitor.clone()));
monitor_rule_entry.guard = Some(guard);
}
for filter_model in filters.into_iter().flatten() {
let service_uri = filter_model.service_uri.to_owned();
let monitor_name = filter_model.monitor_name.to_owned();
let monitor = match monitors_map.get(&monitor_name) {
Some(mon) => mon,
None => {
warn!("Monitor with name {} not found in list", &monitor_name);
warn!(
"Filter {:?} not included in ListMonitorRule response",
&filter_model
);
continue;
}
};
let filter = Filter::from(filter_model);
let service_entry = rules.entry(service_uri).or_insert(BTreeMap::new());
let monitor_rule_entry = service_entry
.entry(monitor_name)
.or_insert(MonitorRule::new(monitor.clone()));
monitor_rule_entry.filter = Some(filter);
}
Ok(rules)
}
}
/// Create creates the monitor rule with given values.
pub struct Create {
con: Con,
}
impl Create {
pub fn new(con: Con) -> Self {
Create { con }
}
}
impl Method for Create {
type Input = Rule;
type Output = String;
fn name(&self) -> &'static str {
"CreateMonitorRule"
}
fn response_type(&self) -> ResponseType {
ResponseType::WithNotification
}
fn call(&self, params: Option<Self::Input>) -> Result<Self::Output> {
let rule_to_create: Rule = params.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("CreateMonitorRule missing param"),
})?;
if let Err(e) = eval::check_master(&rule_to_create.master) {
return Err(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("On master |{}|", e),
});
}
if let Err(e) = eval::check_guard(&rule_to_create.guard) {
return Err(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("On guard |{}|", e),
});
}
let (opt_master, guard, filter) = rule_to_create.etries();
let master = opt_master.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("CreateMonitorRule missing master param"),
})?;
rule::create(master, guard, filter, &self.con)
.map_err(|e| Error::query_error("CreateMonitorRule", e))
}
}
/// Set sets the monitor rule with given values.
pub struct Set {
con: Con,
}
impl Set {
pub fn new(con: Con) -> Self {
Set { con }
}
}
impl Method for Set {
type Input = Rule;
type Output = String;
fn name(&self) -> &'static str {
"SetMonitorRule"
}
fn response_type(&self) -> ResponseType {
ResponseType::WithNotification
}
fn call(&self, params: Option<Self::Input>) -> Result<Self::Output> {
let rule_to_set: Rule = params.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("SetMonitorRule missing param"),
})?;
if let Err(e) = eval::check_master(&rule_to_set.master) {
return Err(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("On master |{}|", e),
});
}
if let Err(e) = eval::check_guard(&rule_to_set.guard) {
return Err(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("On guard |{}|", e),
});
}
let (master, guard, filter) = rule_to_set.etries();
rule::set(master, guard, filter, &self.con)
.map_err(|e| Error::query_error("SetMonitorRule", e))
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ServiceMonitor {
service: String,
monitor: String,
}
/// Remove removes the monitor rule with given service uri and monitor name.
pub struct Remove {
con: Con,
}
impl Remove {
pub fn new(con: Con) -> Self {
Remove { con }
}
}
impl Method for Remove {
type Input = ServiceMonitor;
type Output = String;
fn name(&self) -> &'static str {
"RemoveMonitorRule"
}
fn response_type(&self) -> ResponseType {
ResponseType::WithNotification
}
fn call(&self, params: Option<Self::Input>) -> Result<Self::Output> {
let monitor_rule_to_remove: ServiceMonitor = params.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("RemoveMonitorRule missing param"),
})?;
rule::remove(
&monitor_rule_to_remove.service,
&monitor_rule_to_remove.monitor,
&self.con,
)
.map_err(|e| Error::query_error("RemoveMonitorRule", e))
}
}
/// RemoveGuard removes the guard in the monitor rule with given service uri and
/// monitor name.
pub struct RemoveGuard {
con: Con,
}
impl RemoveGuard {
pub fn new(con: Con) -> Self {
RemoveGuard { con }
}
}
impl Method for RemoveGuard {
type Input = ServiceMonitor;
type Output = String;
fn name(&self) -> &'static str {
"RemoveRuleGuard"
}
fn response_type(&self) -> ResponseType {
ResponseType::WithNotification
}
fn call(&self, params: Option<Self::Input>) -> Result<Self::Output> {
let monitor_rule_to_remove: ServiceMonitor = params.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("RemoveRuleGuard missing param"),
})?;
rule::remove_guard(
&monitor_rule_to_remove.service,
&monitor_rule_to_remove.monitor,
&self.con,
)
.map_err(|e| Error::query_error("RemoveRuleGuard", e))
}
}
/// RemoveFilter removes the guard in the monitor rule with given service uri and
/// monitor name.
pub struct RemoveFilter {
con: Con,
}
impl RemoveFilter {
pub fn new(con: Con) -> Self {
RemoveFilter { con }
}
}
impl Method for RemoveFilter {
type Input = ServiceMonitor;
type Output = String;
fn name(&self) -> &'static str {
"RemoveRuleFilter"
}
fn response_type(&self) -> ResponseType {
ResponseType::WithNotification
}
fn call(&self, params: Option<Self::Input>) -> Result<Self::Output> {
let monitor_rule_to_remove: ServiceMonitor = params.ok_or(Error::InvalidParam {
id: jrpc::Id::Null,
cause: format!("RemoveRuleFilter missing param"),
})?;
rule::remove_filter(
&monitor_rule_to_remove.service,
&monitor_rule_to_remove.monitor,
&self.con,
)
.map_err(|e| Error::query_error("RemoveRuleFilter", e))
}
}
mod eval {
use super::{Guard, Master};
use log::debug;
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDateTime, PyDict, PyString};
use sint::Result;
use std::str::FromStr;
#[macro_export]
macro_rules! check_threshold {
( $( $threshold:expr, $msg:literal ) ? ) => {
{
let mut result: sint::Result<()> = Ok(());
$(
if let Some(th) = $threshold {
if let Err(_) = f64::from_str(&th) {
result = threshold(&th)
.map_err(|e| sint::Error::generic(&format!("{} threshold |{}|{}", $msg, &th, e)));
}
}
)*
result
}
};
}
pub fn check_master(master_opt: &Option<Master>) -> Result<()> {
if let Some(master) = master_opt {
check_threshold!(&master.critical, "Critical")?;
check_threshold!(&master.major, "Major")?;
check_threshold!(&master.minor, "Minor")?;
check_threshold!(&master.warning, "Warning")?;
check_threshold!(&master.cleared, "Cleared")?;
check_threshold!(&master.rops_alarmed, "ROP alarmed")?;
}
Ok(())
}
pub fn check_guard(guard_opt: &Option<Guard>) -> Result<()> {
if let Some(guard) = guard_opt {
check_threshold!(&Some(guard.threshold.to_owned()), "Threshold")?;
check_threshold!(&guard.rops_alarmed, "ROP alarmed")?;
}
Ok(())
}
fn threshold(threshold_snippet: &str) -> Result<()> {
use chrono::prelude::*;
debug!("executing |{}|", threshold_snippet);
let code = "sint.core.eval_threshold(snippet, ts)";
let now = Local::now();
let gil = Python::acquire_gil();
let py = gil.python();
let globals = [("sint", py.import("sint")?)].into_py_dict(py);
let locals = PyDict::new(py);
locals.set_item(
"ts",
PyDateTime::from_timestamp(py, now.timestamp() as f64, None)?,
)?;
locals.set_item("snippet", PyString::new(py, threshold_snippet))?;
py.eval(code, Some(&globals), Some(&locals))
.map(|res| {
debug!("execution result |{:?}|", res);
})
.map_err(|py_err| sint::Error::from(py_err))
}
}
| 29.8542 | 114 | 0.555685 |
5bb95194b71ea63b9b694722155b6a307fc9045c | 15,313 | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{ensure, Context as AnyhowContext, Error},
argh::FromArgs,
carnelian::{
color::Color,
make_app_assistant,
render::{Composition, Context, CopyRegion, Image, PreClear, PreCopy, RenderExt},
App, AppAssistant, IntSize, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey,
},
euclid::default::{Point2D, Rect},
fuchsia_async as fasync,
fuchsia_zircon::{AsHandleRef, Duration, Event, Signals},
std::{fs::File, process},
};
const WHITE_COLOR: Color = Color { r: 255, g: 255, b: 255, a: 255 };
/// Display Png.
#[derive(Debug, FromArgs)]
#[argh(name = "display_png")]
struct Args {
/// PNG file to load
#[argh(option)]
file: Option<String>,
/// path to file containing gamma values. The file format is
/// a header line plus three lines of 256 three-digit hexadecimal
/// value groups.
#[argh(option)]
gamma_file: Option<String>,
/// integer value with which to divide the gamma values found in gamma
/// values file. Does nothing if no gamma file is specified.
#[argh(option, default = "1023")]
gamma_divisor: i64,
/// background color (default is white)
#[argh(option, from_str_fn(parse_color))]
background: Option<Color>,
/// an optional x,y position for the image (default is center)
#[argh(option, from_str_fn(parse_point))]
position: Option<Point2D<f32>>,
/// seconds of delay before application exits (default is 1 second)
#[argh(option, default = "1")]
timeout: i64,
}
fn parse_color(value: &str) -> Result<Color, String> {
Color::from_hash_code(value).map_err(|err| err.to_string())
}
fn parse_point(value: &str) -> Result<Point2D<f32>, String> {
let mut coords = vec![];
for value in value.split(",") {
coords.push(value.parse::<f32>().map_err(|err| err.to_string())?);
}
if coords.len() == 2 {
Ok(Point2D::new(coords[0], coords[1]))
} else {
Err("bad position".to_string())
}
}
struct PngSourceInfo {
png_reader: Option<png::Reader<File>>,
png_size: IntSize,
}
#[derive(Clone, Debug)]
struct GammaValues {
red: Vec<f32>,
green: Vec<f32>,
blue: Vec<f32>,
}
const VALUE_GROUP_LENGTH: usize = 3;
const VALUE_COUNT: usize = 256;
const VALUE_LINE_LENGTH: usize = VALUE_COUNT * VALUE_GROUP_LENGTH;
impl GammaValues {
fn parse_values_line(line: &str, divisor: f32) -> Result<Vec<f32>, Error> {
ensure!(
line.len() == VALUE_LINE_LENGTH,
"Expected value line to be length {} but saw {}",
VALUE_LINE_LENGTH,
line.len()
);
let values: Vec<f32> = (0..VALUE_LINE_LENGTH)
.step_by(3)
.filter_map(|index| {
usize::from_str_radix(&line[index..index + 3], 16)
.ok()
.and_then(|value| Some(value as f32 / divisor))
})
.collect();
ensure!(
values.len() == VALUE_COUNT,
"Expected {} values, saw {}",
VALUE_COUNT,
values.len()
);
Ok(values)
}
fn parse(source_text: &str, divisor: f32) -> Result<Self, Error> {
let parts: Vec<&str> = source_text.split("\n").collect();
ensure!(parts.len() >= 4, "Expected four lines, got {}", parts.len());
let version_line_parts: Vec<&str> = parts[0].split(" ").collect();
ensure!(
version_line_parts == vec!["Gamma", "Calibration", "1.0"],
"Expected version on first line but saw '{}'",
parts[0]
);
let version = version_line_parts[2].parse::<f32>().context("parsing version number")?;
ensure!(version == 1.0, "expected version 1.0, got {}", version);
let red = Self::parse_values_line(parts[1], divisor)?;
let green = Self::parse_values_line(parts[2], divisor)?;
let blue = Self::parse_values_line(parts[3], divisor)?;
Ok(Self { red, green, blue })
}
fn parse_file(path: &str, divisor: f32) -> Result<Self, Error> {
let source_text = std::fs::read_to_string(path)
.context(format!("Error trying to parse gamma values file: {}", path))?;
Self::parse(&source_text, divisor)
}
}
#[derive(Default)]
struct DisplayPngAppAssistant {
png_source: Option<PngSourceInfo>,
gamma_values: Option<GammaValues>,
background: Option<Color>,
position: Option<Point2D<f32>>,
}
impl DisplayPngAppAssistant {}
impl AppAssistant for DisplayPngAppAssistant {
fn setup(&mut self) -> Result<(), Error> {
let args: Args = argh::from_env();
self.background = args.background;
self.position = args.position;
if let Some(filename) = args.file {
let file = File::open(format!("{}", filename))
.context(format!("failed to open file {}", filename))?;
let decoder = png::Decoder::new(file);
let (info, png_reader) =
decoder.read_info().context(format!("failed to open image file {}", filename))?;
ensure!(
info.width > 0 && info.height > 0,
"Invalid image size for png file {}x{}",
info.width,
info.height
);
let color_type = info.color_type;
ensure!(
color_type == png::ColorType::RGBA || color_type == png::ColorType::RGB,
"unsupported color type {:#?}. Only RGB and RGBA are supported.",
color_type
);
self.png_source = Some(PngSourceInfo {
png_reader: Some(png_reader),
png_size: IntSize::new(info.width as i32, info.height as i32),
});
}
if let Some(gamma_file) = args.gamma_file {
ensure!(args.gamma_divisor != 0, "gamma_divisor value must be non-zero");
self.gamma_values =
Some(GammaValues::parse_file(&gamma_file, args.gamma_divisor as f32)?);
}
Ok(())
}
fn create_view_assistant(&mut self, _: ViewKey) -> Result<ViewAssistantPtr, Error> {
let png_source = self.png_source.take();
Ok(Box::new(DisplayPngViewAssistant::new(
png_source,
self.gamma_values.clone(),
self.background.take().unwrap_or(WHITE_COLOR),
self.position.take(),
)))
}
}
const GAMMA_TABLE_ID: u64 = 100;
struct DisplayPngViewAssistant {
png_source: Option<PngSourceInfo>,
gamma_values: Option<GammaValues>,
background: Color,
png: Option<Image>,
composition: Composition,
position: Option<Point2D<f32>>,
}
impl DisplayPngViewAssistant {
pub fn new(
png_source: Option<PngSourceInfo>,
gamma_values: Option<GammaValues>,
background: Color,
position: Option<Point2D<f32>>,
) -> Self {
let background = Color { r: background.r, g: background.g, b: background.b, a: 255 };
let composition = Composition::new(background);
Self { png_source, gamma_values, background, png: None, composition, position }
}
}
impl ViewAssistant for DisplayPngViewAssistant {
fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> {
let args: Args = argh::from_env();
if let Some(gamma_values) = self.gamma_values.as_ref() {
if let Some(frame_buffer) = context.frame_buffer.as_ref() {
let frame_buffer = frame_buffer.borrow_mut();
let mut r: [f32; 256] = [0.0; 256];
r.copy_from_slice(&gamma_values.red);
let mut g: [f32; 256] = [0.0; 256];
g.copy_from_slice(&gamma_values.green);
let mut b: [f32; 256] = [0.0; 256];
b.copy_from_slice(&gamma_values.blue);
frame_buffer.controller.import_gamma_table(
GAMMA_TABLE_ID,
&mut r,
&mut g,
&mut b,
)?;
let config = frame_buffer.get_config();
frame_buffer
.controller
.set_display_gamma_table(config.display_id, GAMMA_TABLE_ID)?;
}
}
let timer = fasync::Timer::new(fasync::Time::after(Duration::from_seconds(args.timeout)));
fasync::Task::local(async move {
timer.await;
process::exit(1);
})
.detach();
Ok(())
}
fn render(
&mut self,
render_context: &mut Context,
ready_event: Event,
context: &ViewAssistantContext,
) -> Result<(), Error> {
let pre_copy = if let Some(png_source) = self.png_source.as_mut() {
let png_size = png_source.png_size;
// Create image from PNG.
let png_image = self.png.take().unwrap_or_else(|| {
let mut png_reader = png_source.png_reader.take().expect("png_reader");
render_context
.new_image_from_png(&mut png_reader)
.expect(&format!("failed to decode file"))
});
// Center image if position has not been specified.
let position = self.position.take().unwrap_or_else(|| {
let x = (context.size.width - png_size.width as f32) / 2.0;
let y = (context.size.height - png_size.height as f32) / 2.0;
Point2D::new(x, y)
});
// Determine visible rect.
let dst_rect = Rect::new(position.to_i32(), png_size.to_i32());
let output_rect = Rect::new(Point2D::zero(), context.size.to_i32());
// Clear |image| to background color and copy |png_image| to |image|.
let ext = RenderExt {
pre_clear: Some(PreClear { color: self.background }),
pre_copy: dst_rect.intersection(&output_rect).map(|visible_rect| PreCopy {
image: png_image,
copy_region: CopyRegion {
src_offset: (visible_rect.origin - dst_rect.origin).to_point().to_u32(),
dst_offset: visible_rect.origin.to_u32(),
extent: visible_rect.size.to_u32(),
},
}),
..Default::default()
};
let image = render_context.get_current_image(context);
render_context.render(&mut self.composition, Some(Rect::zero()), image, &ext);
self.png.replace(png_image);
self.position.replace(position);
dst_rect.intersection(&output_rect).map(|visible_rect| PreCopy {
image: png_image,
copy_region: CopyRegion {
src_offset: (visible_rect.origin - dst_rect.origin).to_point().to_u32(),
dst_offset: visible_rect.origin.to_u32(),
extent: visible_rect.size.to_u32(),
},
})
} else {
None
};
// Clear |image| to background color and copy |png_image| to |image|.
let ext = RenderExt {
pre_clear: Some(PreClear { color: self.background }),
pre_copy: pre_copy,
..Default::default()
};
let image = render_context.get_current_image(context);
render_context.render(&mut self.composition, Some(Rect::zero()), image, &ext);
ready_event.as_handle_ref().signal(Signals::NONE, Signals::EVENT_SIGNALED)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
const LEGAL_SAMPLE_DATA: &'static str = r#"Gamma Calibration 1.0
00000300700a00e01101401801b01f02202602902d03003403703b03e04204504904c05005305705b05e06206506906d07007407807b07f08308608a08e09209509909d0a10a50a80ac0b00b40b80bc0bf0c30c70cb0ce0d20d60da0de0e10e50e90ec0f00f40f70fb0ff10210610910d11111411811b11f12312612a12d13113413813c13f14314614a14e15115515815c16016316716b16e17217617917d18018418818b18f19319619a19e1a11a51a91ac1b01b41b71bb1bf1c21c61ca1cd1d11d51d81dc1e01e31e71eb1ee1f21f61f91fd20120420820c20f21321721a21e22222522922d23123423823c23f24324724b24e25225625a25d26126526926c27027427827b27f28328728b28e29229629a29e2a12a52a92ad2b12b52b82bc2c02c42c82cc2d02d32d72db2df2e32e72eb2ef2f32f72fa2fe30230630a30e31231631a31e32232632932d33133533933d34134534934c35035435835c36036336736b36f37337737a37e38238638a38e39139539939d3a13a53a83ac3b03b4
00000400700b00f01201601a01d02102502902c03003403803b03f04304704b04e05205605a05e06206506906d07107507907d08108508908d09109509909d0a10a50a90ad0b10b50b90bd0c10c50c90cd0d20d60da0de0e20e60ea0ee0f20f60fa0fe10210610a10d11111511911d12112512912c13013413813c14014414714b14f15315715b15f16216616a16e17217617a17e18218618918d19119519919d1a11a51a91ad1b11b51b91bd1c11c51c81cc1d01d41d81dc1e01e41e81ec1f01f41f81fc20020420820b20f21321721b21f22322722b22f23323723b23f24224624a24e25225625a25e26226626a26e27227627a27e28228628a28e29329729b29f2a32a72ab2af2b32b72bb2bf2c42c82cc2d02d42d82dc2e02e52e92ed2f12f52f92fe30230630a30e31331731b31f32332832c33033433933d34134534a34e35235635b35f36336736b37037437837c38038438938d39139539939d3a23a63aa3ae3b23b63ba3be3c33c73cb3cf3d33d73db3df3e33e83ec3f03f43f83fc
00000300700a00e01101501801c01f02202602902d03003403803b03f04204604904d05005405805b05f06206606a06d07107507807c08008408708b08f09309609a09e0a20a60a90ad0b10b50b90bd0c00c40c80cc0d00d40d70db0df0e30e60ea0ee0f10f50f90fc10010410710b10f11211611911d12112412812c12f13313613a13e14114514814c15015315715b15e16216516916d17017417817b17f18318718a18e19219519919d1a01a41a81ab1af1b31b61ba1be1c21c51c91cd1d01d41d81db1df1e31e61ea1ee1f11f51f91fd20020420820b20f21321621a21e22122522922d23023423823b23f24324724a24e25225625925d26126526926c27027427827c27f28328728b28f29229629a29e2a22a62a92ad2b12b52b92bd2c12c52c82cc2d02d42d82dc2e02e42e82ec2f02f32f72fb2ff30330730b30f31331731b31f32332732b32f33333633a33e34234634a34e35235635935d36136536936d37137537837c38038438838c39039339739b39f3a33a73aa3ae3b23b63ba"#;
#[test]
fn legal_calibration_data() {
let gamma_values = GammaValues::parse(LEGAL_SAMPLE_DATA, 1023.0).expect("parse");
assert_eq!(gamma_values.red.len(), 256);
assert_eq!(gamma_values.red[0], 0.0);
assert_eq!(gamma_values.green.len(), 256);
assert_eq!((gamma_values.green[1] * 1023.0) as usize, 4);
assert_eq!(gamma_values.blue.len(), 256);
assert_eq!((gamma_values.blue[255] * 1023.0) as usize, 0x3ba);
}
const TRUNCATED_SAMPLE_DATA: &'static str =
"Gamma Calibration 1.0\n00000300700a00e01101401801b01f02202602902d0300340\n\n\n";
#[test]
fn empty_calibration_data() {
let gamma_values = GammaValues::parse(TRUNCATED_SAMPLE_DATA, 1023.0);
assert!(gamma_values.is_err());
}
const BAD_VERSION_SAMPLE_DATA: &'static str = "Gamma Calibration 2.0\n\n\n\n";
#[test]
fn bad_version_calibration_data() {
let gamma_values = GammaValues::parse(BAD_VERSION_SAMPLE_DATA, 1023.0);
assert!(gamma_values.is_err());
}
}
fn main() -> Result<(), Error> {
App::run(make_app_assistant::<DisplayPngAppAssistant>())
}
| 41.838798 | 771 | 0.640959 |
3a37e761e0c8617d70b653c606b37c9507c29112 | 6,986 | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
#![cfg(feature = "test_constructors")]
use address::Address;
use blocks::{
Block, BlockHeader, EPostProof, EPostTicket, FullTipset, Ticket, Tipset, TipsetKeys, TxMeta,
};
use cid::{Cid, Code::Blake2b256};
use crypto::{Signature, Signer, VRFProof};
use encoding::{from_slice, to_vec};
use forest_libp2p::chain_exchange::{
ChainExchangeResponse, ChainExchangeResponseStatus, CompactedMessages, TipsetBundle,
};
use message::{SignedMessage, UnsignedMessage};
use num_bigint::BigInt;
use std::convert::TryFrom;
use std::error::Error;
/// Defines a TipsetKey used in testing
pub fn template_key(data: &[u8]) -> Cid {
cid::new_from_cbor(data, Blake2b256)
}
/// Defines a block header used in testing
fn template_header(
ticket_p: Vec<u8>,
timestamp: u64,
epoch: i64,
msg_root: Cid,
weight: u64,
) -> BlockHeader {
let cids = construct_keys();
BlockHeader::builder()
.parents(TipsetKeys {
cids: vec![cids[0]],
})
.miner_address(Address::new_actor(&ticket_p))
.timestamp(timestamp)
.ticket(Some(Ticket {
vrfproof: VRFProof::new(ticket_p),
}))
.messages(msg_root)
.signature(Some(Signature::new_bls(vec![1, 4, 3, 6, 7, 1, 2])))
.epoch(epoch)
.weight(BigInt::from(weight))
.build()
.unwrap()
}
/// Returns a vec of 4 distinct CIDs
pub fn construct_keys() -> Vec<Cid> {
return vec![
template_key(b"test content"),
template_key(b"awesome test content "),
template_key(b"even better test content"),
template_key(b"the best test content out there"),
];
}
/// Returns a vec of block headers to be used for testing purposes
pub fn construct_headers(epoch: i64, weight: u64) -> Vec<BlockHeader> {
let data0: Vec<u8> = vec![1, 4, 3, 6, 7, 1, 2];
let data1: Vec<u8> = vec![1, 4, 3, 6, 1, 1, 2, 2, 4, 5, 3, 12, 2, 1];
let data2: Vec<u8> = vec![1, 4, 3, 6, 1, 1, 2, 2, 4, 5, 3, 12, 2];
// setup a deterministic message root within block header
let meta = TxMeta {
bls_message_root: Cid::try_from(
"bafy2bzacec4insvxxjqhl4sqdfjioz3gotxjrflb3cdpd3trtvw3zvm75jdzc",
)
.unwrap(),
secp_message_root: Cid::try_from(
"bafy2bzacecbnlmwafpin7d4wmnb6sgtsdo6cfp4dhjbroq2g574eqrzc65e5a",
)
.unwrap(),
};
let bz = to_vec(&meta).unwrap();
let msg_root = cid::new_from_cbor(&bz, Blake2b256);
return vec![
template_header(data0, 1, epoch, msg_root, weight),
template_header(data1, 2, epoch, msg_root, weight),
template_header(data2, 3, epoch, msg_root, weight),
];
}
/// Returns a Ticket to be used for testing
pub fn construct_ticket() -> Ticket {
let vrf_result = VRFProof::new(base64::decode("lmRJLzDpuVA7cUELHTguK9SFf+IVOaySG8t/0IbVeHHm3VwxzSNhi1JStix7REw6Apu6rcJQV1aBBkd39gQGxP8Abzj8YXH+RdSD5RV50OJHi35f3ixR0uhkY6+G08vV").unwrap());
Ticket::new(vrf_result)
}
/// Returns a deterministic EPostProof to be used for testing
pub fn construct_epost_proof() -> EPostProof {
let etik = EPostTicket {
partial: base64::decode("TFliU6/pdbjRyomejlXMS77qjYdMDty07vigvXH/vjI=").unwrap(),
sector_id: 284,
challenge_index: 5,
};
EPostProof{
proof: from_slice(&base64::decode("rn85uiodD29xvgIuvN5/g37IXghPtVtl3li9y+nPHCueATI1q1/oOn0FEIDXRWHLpZ4CzAqOdQh9rdHih+BI5IsdI1YpwV+UdNDspJVW/cinVE+ZoiO86ap30l77RLkrEwxUZ5v8apsSRUizoXh1IFrHgK06gk1wl5LaxY2i/CQgBoWIPx9o2EYMBbNfQcu+pRzFmiDjzT6BIhYrPbo+gm6wHFiNhp3FvAuSUH2/N+5MKZo7Eh7LwgGLc0fL4MEI").unwrap()).unwrap(),
post_rand: base64::decode("hdodcCz5kLJYRb9PT7m4z9kRvc9h02KMye9DOklnQ8v05X2ds9rgNhcTV+d/cXS+AvADHpepQODMV/6E1kbT99kdFt0xMNUsO/9YbH4ujif7sY0P8pgRAunlMgPrx7Sx").unwrap(),
candidates: vec![etik]
}
}
/// Returns a full block used for testing
pub fn construct_block() -> Block {
const EPOCH: i64 = 1;
const WEIGHT: u64 = 10;
let headers = construct_headers(EPOCH, WEIGHT);
let (bls_messages, secp_messages) = construct_messages();
Block {
header: headers[0].clone(),
secp_messages: vec![secp_messages],
bls_messages: vec![bls_messages],
}
}
/// Returns a tipset used for testing
pub fn construct_tipset(epoch: i64, weight: u64) -> Tipset {
Tipset::new(construct_headers(epoch, weight)).unwrap()
}
/// Returns a full tipset used for testing
pub fn construct_full_tipset() -> FullTipset {
const EPOCH: i64 = 1;
const WEIGHT: u64 = 10;
let headers = construct_headers(EPOCH, WEIGHT);
let mut blocks: Vec<Block> = Vec::with_capacity(headers.len());
let (bls_messages, secp_messages) = construct_messages();
blocks.push(Block {
header: headers[0].clone(),
secp_messages: vec![secp_messages],
bls_messages: vec![bls_messages],
});
FullTipset::new(blocks).unwrap()
}
const DUMMY_SIG: [u8; 1] = [0u8];
struct DummySigner;
impl Signer for DummySigner {
fn sign_bytes(&self, _: &[u8], _: &Address) -> Result<Signature, Box<dyn Error>> {
Ok(Signature::new_secp256k1(DUMMY_SIG.to_vec()))
}
}
/// Returns a tuple of unsigned and signed messages used for testing
pub fn construct_messages() -> (UnsignedMessage, SignedMessage) {
let bls_messages = UnsignedMessage::builder()
.to(Address::new_id(1))
.from(Address::new_id(2))
.build()
.unwrap();
let secp_messages = SignedMessage::new(bls_messages.clone(), &DummySigner).unwrap();
(bls_messages, secp_messages)
}
/// Returns a TipsetBundle used for testing
pub fn construct_tipset_bundle(epoch: i64, weight: u64) -> TipsetBundle {
let headers = construct_headers(epoch, weight);
let (bls, secp) = construct_messages();
let includes: Vec<Vec<u64>> = (0..headers.len()).map(|_| vec![]).collect();
TipsetBundle {
blocks: headers,
messages: Some(CompactedMessages {
bls_msgs: vec![bls],
secp_msgs: vec![secp],
bls_msg_includes: includes.clone(),
secp_msg_includes: includes,
}),
}
}
pub fn construct_dummy_header() -> BlockHeader {
BlockHeader::builder()
.miner_address(Address::new_id(1000))
.messages(cid::new_from_cbor(&[1, 2, 3], Blake2b256))
.message_receipts(cid::new_from_cbor(&[1, 2, 3], Blake2b256))
.state_root(cid::new_from_cbor(&[1, 2, 3], Blake2b256))
.build()
.unwrap()
}
/// Returns a RPCResponse used for testing
pub fn construct_chain_exchange_response() -> ChainExchangeResponse {
// construct block sync response
ChainExchangeResponse {
chain: vec![
construct_tipset_bundle(3, 10),
construct_tipset_bundle(2, 10),
construct_tipset_bundle(1, 10),
],
status: ChainExchangeResponseStatus::Success,
message: "message".to_owned(),
}
}
| 33.912621 | 321 | 0.66347 |
bb15a14a73482138c7f3c7ef0b95a315bc38434c | 48 | net.sf.jasperreports.data.cache.ColumnCacheData
| 24 | 47 | 0.875 |
1c796a65f072f4c28c89bb2637ceab35dd8cc972 | 4,426 | use super::Prefix;
use crate::{
error::Error,
keys::{PrivateKey, PublicKey},
};
use base64::decode_config;
use core::str::FromStr;
use ed25519_dalek::SecretKey;
use k256::ecdsa::{SigningKey, VerifyingKey};
#[derive(Debug, PartialEq, Clone)]
pub enum SeedPrefix {
RandomSeed128(Vec<u8>),
RandomSeed256Ed25519(Vec<u8>),
RandomSeed256ECDSAsecp256k1(Vec<u8>),
RandomSeed448(Vec<u8>),
}
impl SeedPrefix {
pub fn derive_key_pair(&self) -> Result<(PublicKey, PrivateKey), Error> {
match self {
Self::RandomSeed256Ed25519(seed) => {
let secret = SecretKey::from_bytes(seed)?;
let vk =
PublicKey::new(ed25519_dalek::PublicKey::from(&secret).as_bytes().to_vec());
let sk = PrivateKey::new(secret.as_bytes().to_vec());
Ok((vk, sk))
}
Self::RandomSeed256ECDSAsecp256k1(seed) => {
let sk = SigningKey::from_bytes(seed)?;
Ok((
PublicKey::new(VerifyingKey::from(&sk).to_bytes().to_vec()),
PrivateKey::new(sk.to_bytes().to_vec()),
))
}
_ => Err(Error::ImproperPrefixType),
}
}
}
impl FromStr for SeedPrefix {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match &s[..1] {
"A" => Ok(Self::RandomSeed256Ed25519(decode_config(
&s[1..],
base64::URL_SAFE,
)?)),
"J" => Ok(Self::RandomSeed256ECDSAsecp256k1(decode_config(
&s[1..],
base64::URL_SAFE,
)?)),
"K" => Ok(Self::RandomSeed448(decode_config(
&s[1..],
base64::URL_SAFE,
)?)),
"0" => match &s[1..2] {
"A" => Ok(Self::RandomSeed128(decode_config(
&s[2..],
base64::URL_SAFE,
)?)),
_ => Err(Error::DeserializeError(format!(
"Unknown seed prefix cod: {}",
s
))),
},
_ => Err(Error::DeserializeError(format!(
"Unknown seed prefix cod: {}",
s
))),
}
}
}
impl Prefix for SeedPrefix {
fn derivative(&self) -> Vec<u8> {
match self {
Self::RandomSeed256Ed25519(seed) => seed.to_owned(),
Self::RandomSeed256ECDSAsecp256k1(seed) => seed.to_owned(),
Self::RandomSeed448(seed) => seed.to_owned(),
Self::RandomSeed128(seed) => seed.to_owned(),
}
}
fn derivation_code(&self) -> String {
match self {
Self::RandomSeed256Ed25519(_) => "A".to_string(),
Self::RandomSeed256ECDSAsecp256k1(_) => "J".to_string(),
Self::RandomSeed448(_) => "K".to_string(),
Self::RandomSeed128(_) => "0A".to_string(),
}
}
}
#[test]
fn test_derive_keypair() -> Result<(), Error> {
use base64::URL_SAFE;
// taken from KERIPY: tests/core/test_eventing.py#1512
let seeds = vec![
"ArwXoACJgOleVZ2PY7kXn7rA0II0mHYDhc6WrBH8fDAc",
"A6zz7M08-HQSFq92sJ8KJOT2cZ47x7pXFQLPB0pckB3Q",
"AcwFTk-wgk3ZT2buPRIbK-zxgPx-TKbaegQvPEivN90Y",
"Alntkt3u6dDgiQxTATr01dy8M72uuaZEf9eTdM-70Gk8",
"A1-QxDkso9-MR1A8rZz_Naw6fgaAtayda8hrbkRVVu1E",
"AKuYMe09COczwf2nIoD5AE119n7GLFOVFlNLxZcKuswc",
"AxFfJTcSuEE11FINfXMqWttkZGnUZ8KaREhrnyAXTsjw",
"ALq-w1UKkdrppwZzGTtz4PWYEeWm0-sDHzOv5sq96xJY",
];
let expected_pubkeys = vec![
"SuhyBcPZEZLK-fcw5tzHn2N46wRCG_ZOoeKtWTOunRA=",
"VcuJOOJF1IE8svqEtrSuyQjGTd2HhfAkt9y2QkUtFJI=",
"T1iAhBWCkvChxNWsby2J0pJyxBIxbAtbLA0Ljx-Grh8=",
"KPE5eeJRzkRTMOoRGVd2m18o8fLqM2j9kaxLhV3x8AQ=",
"1kcBE7h0ImWW6_Sp7MQxGYSshZZz6XM7OiUE5DXm0dU=",
"4JDgo3WNSUpt-NG14Ni31_GCmrU0r38yo7kgDuyGkQM=",
"VjWcaNX2gCkHOjk6rkmqPBCxkRCqwIJ-3OjdYmMwxf4=",
"T1nEDepd6CSAMCE7NY_jlLdG6_mKUlKS_mW-2HJY1hg=",
];
for (seed_str, expected_pk) in seeds.iter().zip(expected_pubkeys.iter()) {
let seed: SeedPrefix = seed_str.parse()?;
let (pub_key, _priv_key) = seed.derive_key_pair()?;
let b64_pubkey = base64::encode_config(pub_key.key(), URL_SAFE);
assert_eq!(&b64_pubkey, expected_pk);
}
Ok(())
}
| 33.78626 | 96 | 0.563714 |
e461bb574bad0b5b0d98994e7a3d1e02d1e8c2ab | 781 | // quiz1.rs
// This is a quiz for the following sections:
// - Variables
// - Functions
// Mary is buying apples. One apple usually costs 2 Rustbucks, but if you buy
// more than 40 at once, each apple only costs 1! Write a function that calculates
// the price of an order of apples given the order amount. No hints this time!
// I AM DONE! :)
// Put your function here!
fn calculate_apple_price(counts: u16) -> u16 {
if counts > 40 {
counts
} else if counts > 0 {
counts * 2
} else {
0
}
}
// Don't modify this function!
#[test]
fn verify_test() {
let price1 = calculate_apple_price(35);
let price2 = calculate_apple_price(40);
let price3 = calculate_apple_price(65);
assert_eq!(70, price1);
assert_eq!(80, price2);
assert_eq!(65, price3);
}
| 22.970588 | 82 | 0.676056 |
abf7028134747871626f28e40ac2cdf8ef8312cf | 3,896 | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
mod async_cancel;
mod async_cell;
mod bindings;
pub mod error;
mod error_codes;
mod extensions;
mod flags;
mod gotham_state;
mod inspector;
mod module_specifier;
mod modules;
mod normalize_path;
mod ops;
mod ops_builtin;
mod ops_json;
mod ops_metrics;
mod resources;
mod runtime;
// Re-exports
pub use futures;
pub use parking_lot;
pub use serde;
pub use serde_json;
pub use serde_v8;
pub use serde_v8::Buffer as ZeroCopyBuf;
pub use serde_v8::ByteString;
pub use serde_v8::StringOrBuffer;
pub use url;
pub use v8;
pub use crate::async_cancel::CancelFuture;
pub use crate::async_cancel::CancelHandle;
pub use crate::async_cancel::CancelTryFuture;
pub use crate::async_cancel::Cancelable;
pub use crate::async_cancel::Canceled;
pub use crate::async_cancel::TryCancelable;
pub use crate::async_cell::AsyncMut;
pub use crate::async_cell::AsyncMutFuture;
pub use crate::async_cell::AsyncRef;
pub use crate::async_cell::AsyncRefCell;
pub use crate::async_cell::AsyncRefFuture;
pub use crate::async_cell::RcLike;
pub use crate::async_cell::RcRef;
pub use crate::flags::v8_set_flags;
pub use crate::inspector::InspectorSessionProxy;
pub use crate::inspector::JsRuntimeInspector;
pub use crate::inspector::LocalInspectorSession;
pub use crate::module_specifier::resolve_import;
pub use crate::module_specifier::resolve_path;
pub use crate::module_specifier::resolve_url;
pub use crate::module_specifier::resolve_url_or_path;
pub use crate::module_specifier::ModuleResolutionError;
pub use crate::module_specifier::ModuleSpecifier;
pub use crate::module_specifier::DUMMY_SPECIFIER;
pub use crate::modules::FsModuleLoader;
pub use crate::modules::ModuleId;
pub use crate::modules::ModuleLoadId;
pub use crate::modules::ModuleLoader;
pub use crate::modules::ModuleSource;
pub use crate::modules::ModuleSourceFuture;
pub use crate::modules::NoopModuleLoader;
pub use crate::runtime::CompiledWasmModuleStore;
pub use crate::runtime::SharedArrayBufferStore;
// TODO(bartlomieju): this struct should be implementation
// detail nad not be public
pub use crate::modules::RecursiveModuleLoad;
pub use crate::normalize_path::normalize_path;
pub use crate::ops::serialize_op_result;
pub use crate::ops::Op;
pub use crate::ops::OpAsyncFuture;
pub use crate::ops::OpCall;
pub use crate::ops::OpFn;
pub use crate::ops::OpId;
pub use crate::ops::OpPayload;
pub use crate::ops::OpResult;
pub use crate::ops::OpState;
pub use crate::ops::OpTable;
pub use crate::ops::PromiseId;
pub use crate::ops_builtin::op_close;
pub use crate::ops_builtin::op_print;
pub use crate::ops_builtin::op_resources;
pub use crate::ops_json::op_async;
pub use crate::ops_json::op_async_unref;
pub use crate::ops_json::op_sync;
pub use crate::ops_json::void_op_async;
pub use crate::ops_json::void_op_sync;
pub use crate::resources::Resource;
pub use crate::resources::ResourceId;
pub use crate::resources::ResourceTable;
pub use crate::runtime::GetErrorClassFn;
pub use crate::runtime::JsErrorCreateFn;
pub use crate::runtime::JsRuntime;
pub use crate::runtime::RuntimeOptions;
pub use crate::runtime::Snapshot;
// pub use crate::runtime_modules::include_js_files!;
pub use crate::extensions::Extension;
pub use crate::extensions::OpMiddlewareFn;
pub use crate::extensions::OpPair;
pub fn v8_version() -> &'static str {
v8::V8::get_version()
}
/// A helper macro that will return a call site in Rust code. Should be
/// used when executing internal one-line scripts for JsRuntime lifecycle.
///
/// Returns a string in form of: "`[deno:<filename>:<line>:<column>]`"
#[macro_export]
macro_rules! located_script_name {
() => {
format!(
"[deno:{}:{}:{}]",
std::file!(),
std::line!(),
std::column!()
);
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_v8_version() {
assert!(v8_version().len() > 3);
}
}
| 29.740458 | 74 | 0.762064 |
095a85ab21e96c05c1056b67abf6627d044e4c63 | 572 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern:expected `~str` but found `int`
static i: ~str = 10i;
fn main() { info2!("{:?}", i); }
| 38.133333 | 68 | 0.711538 |
6a719d7127505f19194b6fc3c44db7710acbf9f3 | 4,951 | extern crate serialport as serial_port;
use serial_port::{available_ports, SerialPort, SerialPortType};
use std::io::{self, Write};
use std::time::Duration;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "serial-com")]
/// An example of StructOpt usage.
struct Opt {
#[structopt(short, long)]
/// Show a list of serial ports
list: bool,
#[structopt(short, long)]
/// Debug mode for this command
debug: bool,
#[structopt(short, long, default_value = "115200")]
/// Set baud rate speed
baud: u32,
#[structopt(short, long, default_value = "/dev/ttyUSB0")] // "/dev/ttyACM0")]
/// Set port to use
port: String,
}
fn main() {
// parse command prompt args
let opt = Opt::from_args();
if opt.debug {
println!("{:?}", opt);
}
// list com ports if --list is passed
if opt.list {
com_list_info()
} else {
let port_builder =
serial_port::new(opt.port.as_str(), opt.baud).timeout(Duration::from_millis(10));
if opt.debug {
print!("Serial Port Builder Info \n{:#?}", port_builder);
};
let mut port = port_builder.open().unwrap_or_else(|e| {
// check error type not found and display short error message
if e.kind() == serial_port::ErrorKind::Io(io::ErrorKind::NotFound) {
eprintln!("Serial port {} not found.", opt.port.as_str());
// output full error message in debug mode
if opt.debug {
eprintln!("Debug Mode: Serial Port {} {:?}", opt.port.as_str(), e);
};
std::process::exit(1); // exit with error
} else {
// any over error display full error message
eprintln!("Serial Port {} {:?}", opt.port.as_str(), e);
std::process::exit(1); // exit with error
}
});
write_port(&mut port);
read_port(port);
// exit with no error
std::process::exit(0);
}
}
fn write_port(port: &mut Box<dyn SerialPort>) {
let output = "This is a test. This is only a test.".as_bytes();
let bytes_sent = port.write(output).unwrap_or_else(|e| {
std::process::exit(1);
});
print!("bytes sent {} \n", bytes_sent.to_string());
}
fn read_port(mut port: Box<dyn SerialPort>) {
let mut serial_buf: Vec<u8> = vec![0; 32];
let _bytes_read = port
.read(serial_buf.as_mut_slice())
.expect("Error reading from the serial port !");
println!(
"Read from serial port \n{:?}\n",
serial_buf.to_ascii_lowercase()
);
}
fn com_list_info() {
match available_ports() {
Ok(ports) => {
match ports.len() {
0 => println!("No ports found."),
1 => println!("Found 1 port:"),
n => println!("Found {} ports:", n),
};
for p in ports {
println!("\n {}", p.port_name);
match p.port_type {
SerialPortType::UsbPort(info) => {
println!(" Type: USB");
println!(" VID: {:04x}", info.vid);
println!(" PID: {:04x}", info.pid);
println!(
" Serial Number: {}",
info.serial_number.as_ref().map_or("", String::as_str)
);
println!(
" Manufacturer: {}",
info.manufacturer.as_ref().map_or("", String::as_str)
);
println!(
" Manufacturer database: {}",
info.manufacturer_database
.as_ref()
.map_or("", String::as_str)
);
println!(
" Product: {}",
info.product.as_ref().map_or("", String::as_str)
);
println!(
" Product database: {}",
info.product_database.as_ref().map_or("", String::as_str)
);
}
SerialPortType::BluetoothPort => {
println!(" Type: Bluetooth");
}
SerialPortType::PciPort => {
println!(" Type: PCI");
}
SerialPortType::Unknown => {
println!(" Type: Unknown");
}
}
}
}
Err(e) => {
eprintln!("{:?}", e);
eprintln!("Error listing serial ports");
}
}
}
| 34.622378 | 93 | 0.447788 |
898df83d62046e4e15ba59849396904e79afb63b | 35,725 | //! Handles lowering of build-system specific workspace information (`cargo
//! metadata` or `rust-project.json`) into representation stored in the salsa
//! database -- `CrateGraph`.
use std::{collections::VecDeque, convert::TryFrom, fmt, fs, process::Command};
use anyhow::{format_err, Context, Result};
use base_db::{CrateDisplayName, CrateGraph, CrateId, CrateName, Edition, Env, FileId, ProcMacro};
use cfg::{CfgDiff, CfgOptions};
use paths::{AbsPath, AbsPathBuf};
use proc_macro_api::ProcMacroClient;
use rustc_hash::{FxHashMap, FxHashSet};
use stdx::always;
use crate::{
build_scripts::BuildScriptOutput,
cargo_workspace::{DepKind, PackageData, RustcSource},
cfg_flag::CfgFlag,
rustc_cfg,
sysroot::SysrootCrate,
utf8_stdout, CargoConfig, CargoWorkspace, ManifestPath, ProjectJson, ProjectManifest, Sysroot,
TargetKind, WorkspaceBuildScripts,
};
pub type CfgOverrides = FxHashMap<String, CfgDiff>;
/// `PackageRoot` describes a package root folder.
/// Which may be an external dependency, or a member of
/// the current workspace.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct PackageRoot {
/// Is a member of the current workspace
pub is_member: bool,
pub include: Vec<AbsPathBuf>,
pub exclude: Vec<AbsPathBuf>,
}
#[derive(Clone, Eq, PartialEq)]
pub enum ProjectWorkspace {
/// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
Cargo {
cargo: CargoWorkspace,
build_scripts: WorkspaceBuildScripts,
sysroot: Sysroot,
rustc: Option<CargoWorkspace>,
/// Holds cfg flags for the current target. We get those by running
/// `rustc --print cfg`.
///
/// FIXME: make this a per-crate map, as, eg, build.rs might have a
/// different target.
rustc_cfg: Vec<CfgFlag>,
cfg_overrides: CfgOverrides,
},
/// Project workspace was manually specified using a `rust-project.json` file.
Json { project: ProjectJson, sysroot: Option<Sysroot>, rustc_cfg: Vec<CfgFlag> },
// FIXME: The primary limitation of this approach is that the set of detached files needs to be fixed at the beginning.
// That's not the end user experience we should strive for.
// Ideally, you should be able to just open a random detached file in existing cargo projects, and get the basic features working.
// That needs some changes on the salsa-level though.
// In particular, we should split the unified CrateGraph (which currently has maximal durability) into proper crate graph, and a set of ad hoc roots (with minimal durability).
// Then, we need to hide the graph behind the queries such that most queries look only at the proper crate graph, and fall back to ad hoc roots only if there's no results.
// After this, we should be able to tweak the logic in reload.rs to add newly opened files, which don't belong to any existing crates, to the set of the detached files.
// //
/// Project with a set of disjoint files, not belonging to any particular workspace.
/// Backed by basic sysroot crates for basic completion and highlighting.
DetachedFiles { files: Vec<AbsPathBuf>, sysroot: Sysroot, rustc_cfg: Vec<CfgFlag> },
}
impl fmt::Debug for ProjectWorkspace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Make sure this isn't too verbose.
match self {
ProjectWorkspace::Cargo {
cargo,
build_scripts: _,
sysroot,
rustc,
rustc_cfg,
cfg_overrides,
} => f
.debug_struct("Cargo")
.field("root", &cargo.workspace_root().file_name())
.field("n_packages", &cargo.packages().len())
.field("n_sysroot_crates", &sysroot.crates().len())
.field(
"n_rustc_compiler_crates",
&rustc.as_ref().map_or(0, |rc| rc.packages().len()),
)
.field("n_rustc_cfg", &rustc_cfg.len())
.field("n_cfg_overrides", &cfg_overrides.len())
.finish(),
ProjectWorkspace::Json { project, sysroot, rustc_cfg } => {
let mut debug_struct = f.debug_struct("Json");
debug_struct.field("n_crates", &project.n_crates());
if let Some(sysroot) = sysroot {
debug_struct.field("n_sysroot_crates", &sysroot.crates().len());
}
debug_struct.field("n_rustc_cfg", &rustc_cfg.len());
debug_struct.finish()
}
ProjectWorkspace::DetachedFiles { files, sysroot, rustc_cfg } => f
.debug_struct("DetachedFiles")
.field("n_files", &files.len())
.field("n_sysroot_crates", &sysroot.crates().len())
.field("n_rustc_cfg", &rustc_cfg.len())
.finish(),
}
}
}
impl ProjectWorkspace {
pub fn load(
manifest: ProjectManifest,
config: &CargoConfig,
progress: &dyn Fn(String),
) -> Result<ProjectWorkspace> {
let res = match manifest {
ProjectManifest::ProjectJson(project_json) => {
let file = fs::read_to_string(&project_json).with_context(|| {
format!("Failed to read json file {}", project_json.display())
})?;
let data = serde_json::from_str(&file).with_context(|| {
format!("Failed to deserialize json file {}", project_json.display())
})?;
let project_location = project_json.parent().to_path_buf();
let project_json = ProjectJson::new(&project_location, data);
ProjectWorkspace::load_inline(project_json, config.target.as_deref())?
}
ProjectManifest::CargoToml(cargo_toml) => {
let cargo_version = utf8_stdout({
let mut cmd = Command::new(toolchain::cargo());
cmd.arg("--version");
cmd
})?;
let meta = CargoWorkspace::fetch_metadata(&cargo_toml, config, progress)
.with_context(|| {
format!(
"Failed to read Cargo metadata from Cargo.toml file {}, {}",
cargo_toml.display(),
cargo_version
)
})?;
let cargo = CargoWorkspace::new(meta);
let sysroot = if config.no_sysroot {
Sysroot::default()
} else {
Sysroot::discover(cargo_toml.parent()).with_context(|| {
format!(
"Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
cargo_toml.display()
)
})?
};
let rustc_dir = match &config.rustc_source {
Some(RustcSource::Path(path)) => ManifestPath::try_from(path.clone()).ok(),
Some(RustcSource::Discover) => Sysroot::discover_rustc(&cargo_toml),
None => None,
};
let rustc = match rustc_dir {
Some(rustc_dir) => Some({
let meta = CargoWorkspace::fetch_metadata(&rustc_dir, config, progress)
.with_context(|| {
format!("Failed to read Cargo metadata for Rust sources")
})?;
CargoWorkspace::new(meta)
}),
None => None,
};
let rustc_cfg = rustc_cfg::get(Some(&cargo_toml), config.target.as_deref());
let cfg_overrides = config.cfg_overrides();
ProjectWorkspace::Cargo {
cargo,
build_scripts: WorkspaceBuildScripts::default(),
sysroot,
rustc,
rustc_cfg,
cfg_overrides,
}
}
};
Ok(res)
}
pub fn load_inline(
project_json: ProjectJson,
target: Option<&str>,
) -> Result<ProjectWorkspace> {
let sysroot = match &project_json.sysroot_src {
Some(path) => Some(Sysroot::load(path)?),
None => None,
};
let rustc_cfg = rustc_cfg::get(None, target);
Ok(ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg })
}
pub fn load_detached_files(detached_files: Vec<AbsPathBuf>) -> Result<ProjectWorkspace> {
let sysroot = Sysroot::discover(
detached_files
.first()
.and_then(|it| it.parent())
.ok_or_else(|| format_err!("No detached files to load"))?,
)?;
let rustc_cfg = rustc_cfg::get(None, None);
Ok(ProjectWorkspace::DetachedFiles { files: detached_files, sysroot, rustc_cfg })
}
pub fn run_build_scripts(
&self,
config: &CargoConfig,
progress: &dyn Fn(String),
) -> Result<WorkspaceBuildScripts> {
match self {
ProjectWorkspace::Cargo { cargo, .. } => {
WorkspaceBuildScripts::run(config, cargo, progress)
}
ProjectWorkspace::Json { .. } | ProjectWorkspace::DetachedFiles { .. } => {
Ok(WorkspaceBuildScripts::default())
}
}
}
pub fn set_build_scripts(&mut self, bs: WorkspaceBuildScripts) {
match self {
ProjectWorkspace::Cargo { build_scripts, .. } => *build_scripts = bs,
_ => {
always!(bs == WorkspaceBuildScripts::default());
}
}
}
/// Returns the roots for the current `ProjectWorkspace`
/// The return type contains the path and whether or not
/// the root is a member of the current workspace
pub fn to_roots(&self) -> Vec<PackageRoot> {
match self {
ProjectWorkspace::Json { project, sysroot, rustc_cfg: _ } => project
.crates()
.map(|(_, krate)| PackageRoot {
is_member: krate.is_workspace_member,
include: krate.include.clone(),
exclude: krate.exclude.clone(),
})
.collect::<FxHashSet<_>>()
.into_iter()
.chain(sysroot.as_ref().into_iter().flat_map(|sysroot| {
sysroot.crates().map(move |krate| PackageRoot {
is_member: false,
include: vec![sysroot[krate].root.parent().to_path_buf()],
exclude: Vec::new(),
})
}))
.collect::<Vec<_>>(),
ProjectWorkspace::Cargo {
cargo,
sysroot,
rustc,
rustc_cfg: _,
cfg_overrides: _,
build_scripts,
} => {
cargo
.packages()
.map(|pkg| {
let is_member = cargo[pkg].is_member;
let pkg_root = cargo[pkg].manifest.parent().to_path_buf();
let mut include = vec![pkg_root.clone()];
include.extend(
build_scripts.outputs.get(pkg).and_then(|it| it.out_dir.clone()),
);
// In case target's path is manually set in Cargo.toml to be
// outside the package root, add its parent as an extra include.
// An example of this situation would look like this:
//
// ```toml
// [lib]
// path = "../../src/lib.rs"
// ```
let extra_targets = cargo[pkg]
.targets
.iter()
.filter(|&&tgt| cargo[tgt].kind == TargetKind::Lib)
.filter_map(|&tgt| cargo[tgt].root.parent())
.map(|tgt| tgt.normalize().to_path_buf())
.filter(|path| !path.starts_with(&pkg_root));
include.extend(extra_targets);
let mut exclude = vec![pkg_root.join(".git")];
if is_member {
exclude.push(pkg_root.join("target"));
} else {
exclude.push(pkg_root.join("tests"));
exclude.push(pkg_root.join("examples"));
exclude.push(pkg_root.join("benches"));
}
PackageRoot { is_member, include, exclude }
})
.chain(sysroot.crates().map(|krate| PackageRoot {
is_member: false,
include: vec![sysroot[krate].root.parent().to_path_buf()],
exclude: Vec::new(),
}))
.chain(rustc.into_iter().flat_map(|rustc| {
rustc.packages().map(move |krate| PackageRoot {
is_member: false,
include: vec![rustc[krate].manifest.parent().to_path_buf()],
exclude: Vec::new(),
})
}))
.collect()
}
ProjectWorkspace::DetachedFiles { files, sysroot, .. } => files
.into_iter()
.map(|detached_file| PackageRoot {
is_member: true,
include: vec![detached_file.clone()],
exclude: Vec::new(),
})
.chain(sysroot.crates().map(|krate| PackageRoot {
is_member: false,
include: vec![sysroot[krate].root.parent().to_path_buf()],
exclude: Vec::new(),
}))
.collect(),
}
}
pub fn n_packages(&self) -> usize {
match self {
ProjectWorkspace::Json { project, .. } => project.n_crates(),
ProjectWorkspace::Cargo { cargo, sysroot, rustc, .. } => {
let rustc_package_len = rustc.as_ref().map_or(0, |rc| rc.packages().len());
cargo.packages().len() + sysroot.crates().len() + rustc_package_len
}
ProjectWorkspace::DetachedFiles { sysroot, files, .. } => {
sysroot.crates().len() + files.len()
}
}
}
pub fn to_crate_graph(
&self,
proc_macro_client: Option<&ProcMacroClient>,
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
) -> CrateGraph {
let _p = profile::span("ProjectWorkspace::to_crate_graph");
let proc_macro_loader = |path: &AbsPath| match proc_macro_client {
Some(client) => client.by_dylib_path(path),
None => Vec::new(),
};
let mut crate_graph = match self {
ProjectWorkspace::Json { project, sysroot, rustc_cfg } => project_json_to_crate_graph(
rustc_cfg.clone(),
&proc_macro_loader,
load,
project,
sysroot,
),
ProjectWorkspace::Cargo {
cargo,
sysroot,
rustc,
rustc_cfg,
cfg_overrides,
build_scripts,
} => cargo_to_crate_graph(
rustc_cfg.clone(),
cfg_overrides,
&proc_macro_loader,
load,
cargo,
build_scripts,
sysroot,
rustc,
),
ProjectWorkspace::DetachedFiles { files, sysroot, rustc_cfg } => {
detached_files_to_crate_graph(rustc_cfg.clone(), load, files, sysroot)
}
};
if crate_graph.patch_cfg_if() {
log::debug!("Patched std to depend on cfg-if")
} else {
log::debug!("Did not patch std to depend on cfg-if")
}
crate_graph
}
}
fn project_json_to_crate_graph(
rustc_cfg: Vec<CfgFlag>,
proc_macro_loader: &dyn Fn(&AbsPath) -> Vec<ProcMacro>,
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
project: &ProjectJson,
sysroot: &Option<Sysroot>,
) -> CrateGraph {
let mut crate_graph = CrateGraph::default();
let sysroot_deps = sysroot
.as_ref()
.map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load));
let mut cfg_cache: FxHashMap<&str, Vec<CfgFlag>> = FxHashMap::default();
let crates: FxHashMap<CrateId, CrateId> = project
.crates()
.filter_map(|(crate_id, krate)| {
let file_path = &krate.root_module;
let file_id = load(file_path)?;
Some((crate_id, krate, file_id))
})
.map(|(crate_id, krate, file_id)| {
let env = krate.env.clone().into_iter().collect();
let proc_macro = krate.proc_macro_dylib_path.clone().map(|it| proc_macro_loader(&it));
let target_cfgs = match krate.target.as_deref() {
Some(target) => {
cfg_cache.entry(target).or_insert_with(|| rustc_cfg::get(None, Some(target)))
}
None => &rustc_cfg,
};
let mut cfg_options = CfgOptions::default();
cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned());
(
crate_id,
crate_graph.add_crate_root(
file_id,
krate.edition,
krate.display_name.clone(),
cfg_options.clone(),
cfg_options,
env,
proc_macro.unwrap_or_default(),
),
)
})
.collect();
for (from, krate) in project.crates() {
if let Some(&from) = crates.get(&from) {
if let Some((public_deps, libproc_macro)) = &sysroot_deps {
for (name, to) in public_deps.iter() {
add_dep(&mut crate_graph, from, name.clone(), *to)
}
if krate.is_proc_macro {
if let Some(proc_macro) = libproc_macro {
add_dep(
&mut crate_graph,
from,
CrateName::new("proc_macro").unwrap(),
*proc_macro,
);
}
}
}
for dep in &krate.deps {
if let Some(&to) = crates.get(&dep.crate_id) {
add_dep(&mut crate_graph, from, dep.name.clone(), to)
}
}
}
}
crate_graph
}
fn cargo_to_crate_graph(
rustc_cfg: Vec<CfgFlag>,
override_cfg: &CfgOverrides,
proc_macro_loader: &dyn Fn(&AbsPath) -> Vec<ProcMacro>,
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
cargo: &CargoWorkspace,
build_scripts: &WorkspaceBuildScripts,
sysroot: &Sysroot,
rustc: &Option<CargoWorkspace>,
) -> CrateGraph {
let _p = profile::span("cargo_to_crate_graph");
let mut crate_graph = CrateGraph::default();
let (public_deps, libproc_macro) =
sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load);
let mut cfg_options = CfgOptions::default();
cfg_options.extend(rustc_cfg);
let mut pkg_to_lib_crate = FxHashMap::default();
// Add test cfg for non-sysroot crates
cfg_options.insert_atom("test".into());
cfg_options.insert_atom("debug_assertions".into());
let mut pkg_crates = FxHashMap::default();
// Does any crate signal to rust-analyzer that they need the rustc_private crates?
let mut has_private = false;
// Next, create crates for each package, target pair
for pkg in cargo.packages() {
let mut cfg_options = &cfg_options;
let mut replaced_cfg_options;
if let Some(overrides) = override_cfg.get(&cargo[pkg].name) {
// FIXME: this is sort of a hack to deal with #![cfg(not(test))] vanishing such as seen
// in ed25519_dalek (#7243), and libcore (#9203) (although you only hit that one while
// working on rust-lang/rust as that's the only time it appears outside sysroot).
//
// A more ideal solution might be to reanalyze crates based on where the cursor is and
// figure out the set of cfgs that would have to apply to make it active.
replaced_cfg_options = cfg_options.clone();
replaced_cfg_options.apply_diff(overrides.clone());
cfg_options = &replaced_cfg_options;
};
has_private |= cargo[pkg].metadata.rustc_private;
let mut lib_tgt = None;
for &tgt in cargo[pkg].targets.iter() {
if let Some(file_id) = load(&cargo[tgt].root) {
let crate_id = add_target_crate_root(
&mut crate_graph,
&cargo[pkg],
build_scripts.outputs.get(pkg),
&cfg_options,
proc_macro_loader,
file_id,
&cargo[tgt].name,
);
if cargo[tgt].kind == TargetKind::Lib {
lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
pkg_to_lib_crate.insert(pkg, crate_id);
}
if let Some(proc_macro) = libproc_macro {
add_dep(
&mut crate_graph,
crate_id,
CrateName::new("proc_macro").unwrap(),
proc_macro,
);
}
pkg_crates.entry(pkg).or_insert_with(Vec::new).push((crate_id, cargo[tgt].kind));
}
}
// Set deps to the core, std and to the lib target of the current package
for (from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
if let Some((to, name)) = lib_tgt.clone() {
if to != *from && *kind != TargetKind::BuildScript {
// (build script can not depend on its library target)
// For root projects with dashes in their name,
// cargo metadata does not do any normalization,
// so we do it ourselves currently
let name = CrateName::normalize_dashes(&name);
add_dep(&mut crate_graph, *from, name, to);
}
}
for (name, krate) in public_deps.iter() {
add_dep(&mut crate_graph, *from, name.clone(), *krate);
}
}
}
// Now add a dep edge from all targets of upstream to the lib
// target of downstream.
for pkg in cargo.packages() {
for dep in cargo[pkg].dependencies.iter() {
let name = CrateName::new(&dep.name).unwrap();
if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
for (from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
if dep.kind == DepKind::Build && *kind != TargetKind::BuildScript {
// Only build scripts may depend on build dependencies.
continue;
}
if dep.kind != DepKind::Build && *kind == TargetKind::BuildScript {
// Build scripts may only depend on build dependencies.
continue;
}
add_dep(&mut crate_graph, *from, name.clone(), to)
}
}
}
}
if has_private {
// If the user provided a path to rustc sources, we add all the rustc_private crates
// and create dependencies on them for the crates which opt-in to that
if let Some(rustc_workspace) = rustc {
handle_rustc_crates(
rustc_workspace,
load,
&mut crate_graph,
&cfg_options,
proc_macro_loader,
&mut pkg_to_lib_crate,
&public_deps,
cargo,
&pkg_crates,
);
}
}
crate_graph
}
fn detached_files_to_crate_graph(
rustc_cfg: Vec<CfgFlag>,
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
detached_files: &[AbsPathBuf],
sysroot: &Sysroot,
) -> CrateGraph {
let _p = profile::span("detached_files_to_crate_graph");
let mut crate_graph = CrateGraph::default();
let (public_deps, _libproc_macro) =
sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load);
let mut cfg_options = CfgOptions::default();
cfg_options.extend(rustc_cfg);
for detached_file in detached_files {
let file_id = match load(detached_file) {
Some(file_id) => file_id,
None => {
log::error!("Failed to load detached file {:?}", detached_file);
continue;
}
};
let display_name = detached_file
.file_stem()
.and_then(|os_str| os_str.to_str())
.map(|file_stem| CrateDisplayName::from_canonical_name(file_stem.to_string()));
let detached_file_crate = crate_graph.add_crate_root(
file_id,
Edition::CURRENT,
display_name,
cfg_options.clone(),
cfg_options.clone(),
Env::default(),
Vec::new(),
);
for (name, krate) in public_deps.iter() {
add_dep(&mut crate_graph, detached_file_crate, name.clone(), *krate);
}
}
crate_graph
}
fn handle_rustc_crates(
rustc_workspace: &CargoWorkspace,
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
crate_graph: &mut CrateGraph,
cfg_options: &CfgOptions,
proc_macro_loader: &dyn Fn(&AbsPath) -> Vec<ProcMacro>,
pkg_to_lib_crate: &mut FxHashMap<la_arena::Idx<crate::PackageData>, CrateId>,
public_deps: &[(CrateName, CrateId)],
cargo: &CargoWorkspace,
pkg_crates: &FxHashMap<la_arena::Idx<crate::PackageData>, Vec<(CrateId, TargetKind)>>,
) {
let mut rustc_pkg_crates = FxHashMap::default();
// The root package of the rustc-dev component is rustc_driver, so we match that
let root_pkg =
rustc_workspace.packages().find(|package| rustc_workspace[*package].name == "rustc_driver");
// The rustc workspace might be incomplete (such as if rustc-dev is not
// installed for the current toolchain) and `rustcSource` is set to discover.
if let Some(root_pkg) = root_pkg {
// Iterate through every crate in the dependency subtree of rustc_driver using BFS
let mut queue = VecDeque::new();
queue.push_back(root_pkg);
while let Some(pkg) = queue.pop_front() {
// Don't duplicate packages if they are dependended on a diamond pattern
// N.B. if this line is ommitted, we try to analyse over 4_800_000 crates
// which is not ideal
if rustc_pkg_crates.contains_key(&pkg) {
continue;
}
for dep in &rustc_workspace[pkg].dependencies {
queue.push_back(dep.pkg);
}
for &tgt in rustc_workspace[pkg].targets.iter() {
if rustc_workspace[tgt].kind != TargetKind::Lib {
continue;
}
if let Some(file_id) = load(&rustc_workspace[tgt].root) {
let crate_id = add_target_crate_root(
crate_graph,
&rustc_workspace[pkg],
None,
cfg_options,
proc_macro_loader,
file_id,
&rustc_workspace[tgt].name,
);
pkg_to_lib_crate.insert(pkg, crate_id);
// Add dependencies on core / std / alloc for this crate
for (name, krate) in public_deps.iter() {
add_dep(crate_graph, crate_id, name.clone(), *krate);
}
rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
}
}
}
}
// Now add a dep edge from all targets of upstream to the lib
// target of downstream.
for pkg in rustc_pkg_crates.keys().copied() {
for dep in rustc_workspace[pkg].dependencies.iter() {
let name = CrateName::new(&dep.name).unwrap();
if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
add_dep(crate_graph, from, name.clone(), to);
}
}
}
}
// Add a dependency on the rustc_private crates for all targets of each package
// which opts in
for dep in rustc_workspace.packages() {
let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
if let Some(&to) = pkg_to_lib_crate.get(&dep) {
for pkg in cargo.packages() {
let package = &cargo[pkg];
if !package.metadata.rustc_private {
continue;
}
for (from, _) in pkg_crates.get(&pkg).into_iter().flatten() {
// Avoid creating duplicate dependencies
// This avoids the situation where `from` depends on e.g. `arrayvec`, but
// `rust_analyzer` thinks that it should use the one from the `rustcSource`
// instead of the one from `crates.io`
if !crate_graph[*from].dependencies.iter().any(|d| d.name == name) {
add_dep(crate_graph, *from, name.clone(), to);
}
}
}
}
}
}
fn add_target_crate_root(
crate_graph: &mut CrateGraph,
pkg: &PackageData,
build_data: Option<&BuildScriptOutput>,
cfg_options: &CfgOptions,
proc_macro_loader: &dyn Fn(&AbsPath) -> Vec<ProcMacro>,
file_id: FileId,
cargo_name: &str,
) -> CrateId {
let edition = pkg.edition;
let cfg_options = {
let mut opts = cfg_options.clone();
for feature in pkg.active_features.iter() {
opts.insert_key_value("feature".into(), feature.into());
}
if let Some(cfgs) = build_data.as_ref().map(|it| &it.cfgs) {
opts.extend(cfgs.iter().cloned());
}
opts
};
let mut env = Env::default();
inject_cargo_env(pkg, &mut env);
if let Some(envs) = build_data.map(|it| &it.envs) {
for (k, v) in envs {
env.set(k, v.clone());
}
}
let proc_macro = build_data
.as_ref()
.and_then(|it| it.proc_macro_dylib_path.as_ref())
.map(|it| proc_macro_loader(it))
.unwrap_or_default();
let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_string());
let mut potential_cfg_options = cfg_options.clone();
potential_cfg_options.extend(
pkg.features
.iter()
.map(|feat| CfgFlag::KeyValue { key: "feature".into(), value: feat.0.into() }),
);
let crate_id = crate_graph.add_crate_root(
file_id,
edition,
Some(display_name),
cfg_options,
potential_cfg_options,
env,
proc_macro,
);
crate_id
}
fn sysroot_to_crate_graph(
crate_graph: &mut CrateGraph,
sysroot: &Sysroot,
rustc_cfg: Vec<CfgFlag>,
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
) -> (Vec<(CrateName, CrateId)>, Option<CrateId>) {
let _p = profile::span("sysroot_to_crate_graph");
let mut cfg_options = CfgOptions::default();
cfg_options.extend(rustc_cfg);
let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = sysroot
.crates()
.filter_map(|krate| {
let file_id = load(&sysroot[krate].root)?;
let env = Env::default();
let proc_macro = vec![];
let display_name = CrateDisplayName::from_canonical_name(sysroot[krate].name.clone());
let crate_id = crate_graph.add_crate_root(
file_id,
Edition::CURRENT,
Some(display_name),
cfg_options.clone(),
cfg_options.clone(),
env,
proc_macro,
);
Some((krate, crate_id))
})
.collect();
for from in sysroot.crates() {
for &to in sysroot[from].deps.iter() {
let name = CrateName::new(&sysroot[to].name).unwrap();
if let (Some(&from), Some(&to)) = (sysroot_crates.get(&from), sysroot_crates.get(&to)) {
add_dep(crate_graph, from, name, to);
}
}
}
let public_deps = sysroot
.public_deps()
.map(|(name, idx)| (CrateName::new(name).unwrap(), sysroot_crates[&idx]))
.collect::<Vec<_>>();
let libproc_macro = sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
(public_deps, libproc_macro)
}
fn add_dep(graph: &mut CrateGraph, from: CrateId, name: CrateName, to: CrateId) {
if let Err(err) = graph.add_dep(from, name, to) {
log::error!("{}", err)
}
}
/// Recreates the compile-time environment variables that Cargo sets.
///
/// Should be synced with
/// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
///
/// FIXME: ask Cargo to provide this data instead of re-deriving.
fn inject_cargo_env(package: &PackageData, env: &mut Env) {
// FIXME: Missing variables:
// CARGO_BIN_NAME, CARGO_BIN_EXE_<name>
let manifest_dir = package.manifest.parent();
env.set("CARGO_MANIFEST_DIR".into(), manifest_dir.as_os_str().to_string_lossy().into_owned());
// Not always right, but works for common cases.
env.set("CARGO".into(), "cargo".into());
env.set("CARGO_PKG_VERSION".into(), package.version.to_string());
env.set("CARGO_PKG_VERSION_MAJOR".into(), package.version.major.to_string());
env.set("CARGO_PKG_VERSION_MINOR".into(), package.version.minor.to_string());
env.set("CARGO_PKG_VERSION_PATCH".into(), package.version.patch.to_string());
env.set("CARGO_PKG_VERSION_PRE".into(), package.version.pre.to_string());
env.set("CARGO_PKG_AUTHORS".into(), String::new());
env.set("CARGO_PKG_NAME".into(), package.name.clone());
// FIXME: This isn't really correct (a package can have many crates with different names), but
// it's better than leaving the variable unset.
env.set("CARGO_CRATE_NAME".into(), CrateName::normalize_dashes(&package.name).to_string());
env.set("CARGO_PKG_DESCRIPTION".into(), String::new());
env.set("CARGO_PKG_HOMEPAGE".into(), String::new());
env.set("CARGO_PKG_REPOSITORY".into(), String::new());
env.set("CARGO_PKG_LICENSE".into(), String::new());
env.set("CARGO_PKG_LICENSE_FILE".into(), String::new());
}
| 40.095398 | 179 | 0.536599 |
7ac426352e42ec3591ec08bfaba456746ef6ee7d | 2,513 | //! Endpoint for handling session creation
use std::time::Duration;
use super::SharedOptions;
use crate::libraries::{
helpers::{constants, parse_seconds},
tracing::{self, constants::service},
};
use crate::libraries::{
lifecycle::Heart,
net::{advertise::ServiceAdvertisorJob, discovery::ServiceDescriptor},
};
use anyhow::Result;
use jatsl::{schedule, JobScheduler, StatusServer};
use log::info;
use structopt::StructOpt;
mod context;
mod jobs;
mod structures;
mod tasks;
use context::Context;
use jobs::SessionHandlerJob;
pub use structures::*;
#[derive(Debug, StructOpt, Clone)]
/// Endpoint for handling session creation
///
/// Handles scheduling and provisioning lifecycle of sessions.
pub struct Options {
/// Unique instance identifier
#[structopt(env)]
id: String,
/// Host under which the manager server is reachable by the proxy
#[structopt(long, env)]
host: String,
/// Port on which the HTTP server will listen
#[structopt(short, long, default_value = constants::PORT_MANAGER)]
port: u16,
/// Maximum duration to wait in queue; in seconds
#[structopt(long, env, default_value = "600", parse(try_from_str = parse_seconds))]
timeout_queue: Duration,
/// Maximum duration to wait for a session to become provisioned; in seconds
#[structopt(long, env, default_value = "300", parse(try_from_str = parse_seconds))]
timeout_provisioning: Duration,
}
pub async fn run(shared_options: SharedOptions, options: Options) -> Result<()> {
tracing::init(
&shared_options.trace_endpoint,
service::MANAGER,
Some(&options.id),
)?;
let (mut heart, _) = Heart::new();
let endpoint = format!("{}:{}", options.host, options.port);
let context = Context::new(shared_options.redis, options.clone()).await;
let scheduler = JobScheduler::default();
let status_job = StatusServer::new(&scheduler, shared_options.status_server);
let heart_beat_job = context.heart_beat.clone();
let metrics_job = context.metrics.clone();
let session_handler_job = SessionHandlerJob::new(options.port);
let advertise_job = ServiceAdvertisorJob::new(ServiceDescriptor::Manager, endpoint);
schedule!(scheduler, context, {
status_job,
heart_beat_job,
metrics_job,
session_handler_job,
advertise_job
});
let death_reason = heart.death().await;
info!("Heart died: {}", death_reason);
scheduler.terminate_jobs().await;
Ok(())
}
| 28.556818 | 88 | 0.690012 |
33778d5e09144711bb003d49b92f016e0cf879a0 | 113 | pub mod spells;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| 10.272727 | 29 | 0.469027 |
ef261281d2117bca9d0ac44a3d90d76b775e0490 | 1,371 | // This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md
use cranelift_codegen::Context;
use cranelift_codegen::MachSrcLoc;
use wasmer_compiler::{wasmparser::Range, FunctionAddressMap, InstructionAddressMap, SourceLoc};
pub fn get_function_address_map<'data>(
context: &Context,
range: Range,
body_len: usize,
) -> FunctionAddressMap {
let mut instructions = Vec::new();
// New-style backend: we have a `MachCompileResult` that will give us `MachSrcLoc` mapping
// tuples.
let mcr = context.mach_compile_result.as_ref().unwrap();
for &MachSrcLoc { start, end, loc } in mcr.buffer.get_srclocs_sorted() {
instructions.push(InstructionAddressMap {
srcloc: SourceLoc::new(loc.bits()),
code_offset: start as usize,
code_len: (end - start) as usize,
});
}
// Generate artificial srcloc for function start/end to identify boundary
// within module. Similar to FuncTranslator::cur_srcloc(): it will wrap around
// if byte code is larger than 4 GB.
let start_srcloc = SourceLoc::new(range.start as u32);
let end_srcloc = SourceLoc::new(range.end as u32);
FunctionAddressMap {
instructions,
start_srcloc,
end_srcloc,
body_offset: 0,
body_len,
}
}
| 34.275 | 95 | 0.680525 |
6a10e542f171606302e184e5d889b46062c5a8da | 15,573 | // Generated from definition io.k8s.api.certificates.v1beta1.CertificateSigningRequestSpec
/// This information is immutable after the request is created. Only the Request and Usages fields can be set on creation, other fields are derived by Kubernetes and cannot be modified by users.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CertificateSigningRequestSpec {
/// Extra information about the requesting user. See user.Info interface for details.
pub extra: Option<std::collections::BTreeMap<String, Vec<String>>>,
/// Group information about the requesting user. See user.Info interface for details.
pub groups: Option<Vec<String>>,
/// Base64-encoded PKCS#10 CSR data
pub request: crate::ByteString,
/// UID information about the requesting user. See user.Info interface for details.
pub uid: Option<String>,
/// allowedUsages specifies a set of usage contexts the key will be valid for. See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3
/// https://tools.ietf.org/html/rfc5280#section-4.2.1.12
pub usages: Option<Vec<String>>,
/// Information about the requesting user. See user.Info interface for details.
pub username: Option<String>,
}
impl<'de> crate::serde::Deserialize<'de> for CertificateSigningRequestSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_extra,
Key_groups,
Key_request,
Key_uid,
Key_usages,
Key_username,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
Ok(match v {
"extra" => Field::Key_extra,
"groups" => Field::Key_groups,
"request" => Field::Key_request,
"uid" => Field::Key_uid,
"usages" => Field::Key_usages,
"username" => Field::Key_username,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = CertificateSigningRequestSpec;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("CertificateSigningRequestSpec")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
let mut value_extra: Option<std::collections::BTreeMap<String, Vec<String>>> = None;
let mut value_groups: Option<Vec<String>> = None;
let mut value_request: Option<crate::ByteString> = None;
let mut value_uid: Option<String> = None;
let mut value_usages: Option<Vec<String>> = None;
let mut value_username: Option<String> = None;
while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_extra => value_extra = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_groups => value_groups = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_request => value_request = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_uid => value_uid = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_usages => value_usages = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_username => value_username = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(CertificateSigningRequestSpec {
extra: value_extra,
groups: value_groups,
request: value_request.unwrap_or_default(),
uid: value_uid,
usages: value_usages,
username: value_username,
})
}
}
deserializer.deserialize_struct(
"CertificateSigningRequestSpec",
&[
"extra",
"groups",
"request",
"uid",
"usages",
"username",
],
Visitor,
)
}
}
impl crate::serde::Serialize for CertificateSigningRequestSpec {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
let mut state = serializer.serialize_struct(
"CertificateSigningRequestSpec",
1 +
self.extra.as_ref().map_or(0, |_| 1) +
self.groups.as_ref().map_or(0, |_| 1) +
self.uid.as_ref().map_or(0, |_| 1) +
self.usages.as_ref().map_or(0, |_| 1) +
self.username.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.extra {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "extra", value)?;
}
if let Some(value) = &self.groups {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "groups", value)?;
}
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "request", &self.request)?;
if let Some(value) = &self.uid {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "uid", value)?;
}
if let Some(value) = &self.usages {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "usages", value)?;
}
if let Some(value) = &self.username {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "username", value)?;
}
crate::serde::ser::SerializeStruct::end(state)
}
}
#[cfg(feature = "schemars")]
impl crate::schemars::JsonSchema for CertificateSigningRequestSpec {
fn schema_name() -> String {
"io.k8s.api.certificates.v1beta1.CertificateSigningRequestSpec".to_owned()
}
fn json_schema(__gen: &mut crate::schemars::gen::SchemaGenerator) -> crate::schemars::schema::Schema {
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("This information is immutable after the request is created. Only the Request and Usages fields can be set on creation, other fields are derived by Kubernetes and cannot be modified by users.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
object: Some(Box::new(crate::schemars::schema::ObjectValidation {
properties: IntoIterator::into_iter([
(
"extra".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Extra information about the requesting user. See user.Info interface for details.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
object: Some(Box::new(crate::schemars::schema::ObjectValidation {
additional_properties: Some(Box::new(
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))),
array: Some(Box::new(crate::schemars::schema::ArrayValidation {
items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
})
))),
..Default::default()
})),
..Default::default()
})
)),
..Default::default()
})),
..Default::default()
}),
),
(
"groups".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Group information about the requesting user. See user.Info interface for details.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))),
array: Some(Box::new(crate::schemars::schema::ArrayValidation {
items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
})
))),
..Default::default()
})),
..Default::default()
}),
),
(
"request".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Base64-encoded PKCS#10 CSR data".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
format: Some("byte".to_owned()),
..Default::default()
}),
),
(
"uid".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("UID information about the requesting user. See user.Info interface for details.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
}),
),
(
"usages".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("allowedUsages specifies a set of usage contexts the key will be valid for. See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3\n https://tools.ietf.org/html/rfc5280#section-4.2.1.12".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Array))),
array: Some(Box::new(crate::schemars::schema::ArrayValidation {
items: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
})
))),
..Default::default()
})),
..Default::default()
}),
),
(
"username".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Information about the requesting user. See user.Info interface for details.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
..Default::default()
}),
),
]).collect(),
required: IntoIterator::into_iter([
"request",
]).map(std::borrow::ToOwned::to_owned).collect(),
..Default::default()
})),
..Default::default()
})
}
}
| 55.419929 | 255 | 0.497335 |
6238cf97c8012556c01e978aa02c07eb2378b500 | 62,361 | #![doc = "Peripheral access API for ATSAME51G18A microcontrollers (generated using svd2rust v0.19.0 ( ))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next]
svd2rust release can be generated by cloning the svd2rust [repository], checking out the above commit, and running `cargo doc --open`.\n\n[here]: https://docs.rs/svd2rust/0.19.0/svd2rust/#peripheral-api\n[next]: https://github.com/rust-embedded/svd2rust/blob/master/CHANGELOG.md#unreleased\n[repository]: https://github.com/rust-embedded/svd2rust"]
#![deny(const_err)]
#![deny(dead_code)]
#![deny(improper_ctypes)]
#![deny(missing_docs)]
#![deny(no_mangle_generic_items)]
#![deny(non_shorthand_field_patterns)]
#![deny(overflowing_literals)]
#![deny(path_statements)]
#![deny(patterns_in_fns_without_body)]
#![deny(private_in_public)]
#![deny(unconditional_recursion)]
#![deny(unused_allocation)]
#![deny(unused_comparisons)]
#![deny(unused_parens)]
#![deny(while_true)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![no_std]
use core::marker::PhantomData;
use core::ops::Deref;
#[doc = r"Number available in the NVIC for configuring priority"]
pub const NVIC_PRIO_BITS: u8 = 3;
#[cfg(feature = "rt")]
pub use self::Interrupt as interrupt;
pub use cortex_m::peripheral::Peripherals as CorePeripherals;
pub use cortex_m::peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, SYST, TPIU};
#[cfg(feature = "rt")]
pub use cortex_m_rt::interrupt;
#[allow(unused_imports)]
use generic::*;
#[doc = r"Common register and bit access and modify traits"]
pub mod generic;
#[cfg(feature = "rt")]
extern "C" {
fn PM();
fn MCLK();
fn OSCCTRL_XOSC0();
fn OSCCTRL_XOSC1();
fn OSCCTRL_DFLL();
fn OSCCTRL_DPLL0();
fn OSCCTRL_DPLL1();
fn OSC32KCTRL();
fn SUPC_OTHER();
fn SUPC_BODDET();
fn WDT();
fn RTC();
fn EIC_EXTINT_0();
fn EIC_EXTINT_1();
fn EIC_EXTINT_2();
fn EIC_EXTINT_3();
fn EIC_EXTINT_4();
fn EIC_EXTINT_5();
fn EIC_EXTINT_6();
fn EIC_EXTINT_7();
fn EIC_EXTINT_8();
fn EIC_EXTINT_9();
fn EIC_EXTINT_10();
fn EIC_EXTINT_11();
fn EIC_EXTINT_12();
fn EIC_EXTINT_13();
fn EIC_EXTINT_14();
fn EIC_EXTINT_15();
fn FREQM();
fn NVMCTRL_0();
fn NVMCTRL_1();
fn DMAC_0();
fn DMAC_1();
fn DMAC_2();
fn DMAC_3();
fn DMAC_OTHER();
fn EVSYS_0();
fn EVSYS_1();
fn EVSYS_2();
fn EVSYS_3();
fn EVSYS_OTHER();
fn PAC();
fn RAMECC();
fn SERCOM0_0();
fn SERCOM0_1();
fn SERCOM0_2();
fn SERCOM0_OTHER();
fn SERCOM1_0();
fn SERCOM1_1();
fn SERCOM1_2();
fn SERCOM1_OTHER();
fn SERCOM2_0();
fn SERCOM2_1();
fn SERCOM2_2();
fn SERCOM2_OTHER();
fn SERCOM3_0();
fn SERCOM3_1();
fn SERCOM3_2();
fn SERCOM3_OTHER();
fn SERCOM4_0();
fn SERCOM4_1();
fn SERCOM4_2();
fn SERCOM4_OTHER();
fn SERCOM5_0();
fn SERCOM5_1();
fn SERCOM5_2();
fn SERCOM5_OTHER();
fn CAN0();
fn USB_OTHER();
fn USB_SOF_HSOF();
fn USB_TRCPT0();
fn USB_TRCPT1();
fn TCC0_OTHER();
fn TCC0_MC0();
fn TCC0_MC1();
fn TCC0_MC2();
fn TCC0_MC3();
fn TCC0_MC4();
fn TCC0_MC5();
fn TCC1_OTHER();
fn TCC1_MC0();
fn TCC1_MC1();
fn TCC1_MC2();
fn TCC1_MC3();
fn TCC2_OTHER();
fn TCC2_MC0();
fn TCC2_MC1();
fn TCC2_MC2();
fn TC0();
fn TC1();
fn TC2();
fn TC3();
fn PDEC_OTHER();
fn PDEC_MC0();
fn PDEC_MC1();
fn ADC0_OTHER();
fn ADC0_RESRDY();
fn ADC1_OTHER();
fn ADC1_RESRDY();
fn AC();
fn DAC_OTHER();
fn DAC_EMPTY_0();
fn DAC_EMPTY_1();
fn DAC_RESRDY_0();
fn DAC_RESRDY_1();
fn PCC();
fn AES();
fn TRNG();
fn ICM();
fn QSPI();
fn SDHC0();
}
#[doc(hidden)]
pub union Vector {
_handler: unsafe extern "C" fn(),
_reserved: u32,
}
#[cfg(feature = "rt")]
#[doc(hidden)]
#[link_section = ".vector_table.interrupts"]
#[no_mangle]
pub static __INTERRUPTS: [Vector; 136] = [
Vector { _handler: PM },
Vector { _handler: MCLK },
Vector {
_handler: OSCCTRL_XOSC0,
},
Vector {
_handler: OSCCTRL_XOSC1,
},
Vector {
_handler: OSCCTRL_DFLL,
},
Vector {
_handler: OSCCTRL_DPLL0,
},
Vector {
_handler: OSCCTRL_DPLL1,
},
Vector {
_handler: OSC32KCTRL,
},
Vector {
_handler: SUPC_OTHER,
},
Vector {
_handler: SUPC_BODDET,
},
Vector { _handler: WDT },
Vector { _handler: RTC },
Vector {
_handler: EIC_EXTINT_0,
},
Vector {
_handler: EIC_EXTINT_1,
},
Vector {
_handler: EIC_EXTINT_2,
},
Vector {
_handler: EIC_EXTINT_3,
},
Vector {
_handler: EIC_EXTINT_4,
},
Vector {
_handler: EIC_EXTINT_5,
},
Vector {
_handler: EIC_EXTINT_6,
},
Vector {
_handler: EIC_EXTINT_7,
},
Vector {
_handler: EIC_EXTINT_8,
},
Vector {
_handler: EIC_EXTINT_9,
},
Vector {
_handler: EIC_EXTINT_10,
},
Vector {
_handler: EIC_EXTINT_11,
},
Vector {
_handler: EIC_EXTINT_12,
},
Vector {
_handler: EIC_EXTINT_13,
},
Vector {
_handler: EIC_EXTINT_14,
},
Vector {
_handler: EIC_EXTINT_15,
},
Vector { _handler: FREQM },
Vector {
_handler: NVMCTRL_0,
},
Vector {
_handler: NVMCTRL_1,
},
Vector { _handler: DMAC_0 },
Vector { _handler: DMAC_1 },
Vector { _handler: DMAC_2 },
Vector { _handler: DMAC_3 },
Vector {
_handler: DMAC_OTHER,
},
Vector { _handler: EVSYS_0 },
Vector { _handler: EVSYS_1 },
Vector { _handler: EVSYS_2 },
Vector { _handler: EVSYS_3 },
Vector {
_handler: EVSYS_OTHER,
},
Vector { _handler: PAC },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _handler: RAMECC },
Vector {
_handler: SERCOM0_0,
},
Vector {
_handler: SERCOM0_1,
},
Vector {
_handler: SERCOM0_2,
},
Vector {
_handler: SERCOM0_OTHER,
},
Vector {
_handler: SERCOM1_0,
},
Vector {
_handler: SERCOM1_1,
},
Vector {
_handler: SERCOM1_2,
},
Vector {
_handler: SERCOM1_OTHER,
},
Vector {
_handler: SERCOM2_0,
},
Vector {
_handler: SERCOM2_1,
},
Vector {
_handler: SERCOM2_2,
},
Vector {
_handler: SERCOM2_OTHER,
},
Vector {
_handler: SERCOM3_0,
},
Vector {
_handler: SERCOM3_1,
},
Vector {
_handler: SERCOM3_2,
},
Vector {
_handler: SERCOM3_OTHER,
},
Vector {
_handler: SERCOM4_0,
},
Vector {
_handler: SERCOM4_1,
},
Vector {
_handler: SERCOM4_2,
},
Vector {
_handler: SERCOM4_OTHER,
},
Vector {
_handler: SERCOM5_0,
},
Vector {
_handler: SERCOM5_1,
},
Vector {
_handler: SERCOM5_2,
},
Vector {
_handler: SERCOM5_OTHER,
},
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _handler: CAN0 },
Vector { _reserved: 0 },
Vector {
_handler: USB_OTHER,
},
Vector {
_handler: USB_SOF_HSOF,
},
Vector {
_handler: USB_TRCPT0,
},
Vector {
_handler: USB_TRCPT1,
},
Vector { _reserved: 0 },
Vector {
_handler: TCC0_OTHER,
},
Vector { _handler: TCC0_MC0 },
Vector { _handler: TCC0_MC1 },
Vector { _handler: TCC0_MC2 },
Vector { _handler: TCC0_MC3 },
Vector { _handler: TCC0_MC4 },
Vector { _handler: TCC0_MC5 },
Vector {
_handler: TCC1_OTHER,
},
Vector { _handler: TCC1_MC0 },
Vector { _handler: TCC1_MC1 },
Vector { _handler: TCC1_MC2 },
Vector { _handler: TCC1_MC3 },
Vector {
_handler: TCC2_OTHER,
},
Vector { _handler: TCC2_MC0 },
Vector { _handler: TCC2_MC1 },
Vector { _handler: TCC2_MC2 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _handler: TC0 },
Vector { _handler: TC1 },
Vector { _handler: TC2 },
Vector { _handler: TC3 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector {
_handler: PDEC_OTHER,
},
Vector { _handler: PDEC_MC0 },
Vector { _handler: PDEC_MC1 },
Vector {
_handler: ADC0_OTHER,
},
Vector {
_handler: ADC0_RESRDY,
},
Vector {
_handler: ADC1_OTHER,
},
Vector {
_handler: ADC1_RESRDY,
},
Vector { _handler: AC },
Vector {
_handler: DAC_OTHER,
},
Vector {
_handler: DAC_EMPTY_0,
},
Vector {
_handler: DAC_EMPTY_1,
},
Vector {
_handler: DAC_RESRDY_0,
},
Vector {
_handler: DAC_RESRDY_1,
},
Vector { _reserved: 0 },
Vector { _handler: PCC },
Vector { _handler: AES },
Vector { _handler: TRNG },
Vector { _handler: ICM },
Vector { _reserved: 0 },
Vector { _handler: QSPI },
Vector { _handler: SDHC0 },
];
#[doc = r"Enumeration of all the interrupts."]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u16)]
pub enum Interrupt {
#[doc = "0 - PM"]
PM = 0,
#[doc = "1 - MCLK"]
MCLK = 1,
#[doc = "2 - OSCCTRL_XOSC0"]
OSCCTRL_XOSC0 = 2,
#[doc = "3 - OSCCTRL_XOSC1"]
OSCCTRL_XOSC1 = 3,
#[doc = "4 - OSCCTRL_DFLL"]
OSCCTRL_DFLL = 4,
#[doc = "5 - OSCCTRL_DPLL0"]
OSCCTRL_DPLL0 = 5,
#[doc = "6 - OSCCTRL_DPLL1"]
OSCCTRL_DPLL1 = 6,
#[doc = "7 - OSC32KCTRL"]
OSC32KCTRL = 7,
#[doc = "8 - SUPC_OTHER"]
SUPC_OTHER = 8,
#[doc = "9 - SUPC_BODDET"]
SUPC_BODDET = 9,
#[doc = "10 - WDT"]
WDT = 10,
#[doc = "11 - RTC"]
RTC = 11,
#[doc = "12 - EIC_EXTINT_0"]
EIC_EXTINT_0 = 12,
#[doc = "13 - EIC_EXTINT_1"]
EIC_EXTINT_1 = 13,
#[doc = "14 - EIC_EXTINT_2"]
EIC_EXTINT_2 = 14,
#[doc = "15 - EIC_EXTINT_3"]
EIC_EXTINT_3 = 15,
#[doc = "16 - EIC_EXTINT_4"]
EIC_EXTINT_4 = 16,
#[doc = "17 - EIC_EXTINT_5"]
EIC_EXTINT_5 = 17,
#[doc = "18 - EIC_EXTINT_6"]
EIC_EXTINT_6 = 18,
#[doc = "19 - EIC_EXTINT_7"]
EIC_EXTINT_7 = 19,
#[doc = "20 - EIC_EXTINT_8"]
EIC_EXTINT_8 = 20,
#[doc = "21 - EIC_EXTINT_9"]
EIC_EXTINT_9 = 21,
#[doc = "22 - EIC_EXTINT_10"]
EIC_EXTINT_10 = 22,
#[doc = "23 - EIC_EXTINT_11"]
EIC_EXTINT_11 = 23,
#[doc = "24 - EIC_EXTINT_12"]
EIC_EXTINT_12 = 24,
#[doc = "25 - EIC_EXTINT_13"]
EIC_EXTINT_13 = 25,
#[doc = "26 - EIC_EXTINT_14"]
EIC_EXTINT_14 = 26,
#[doc = "27 - EIC_EXTINT_15"]
EIC_EXTINT_15 = 27,
#[doc = "28 - FREQM"]
FREQM = 28,
#[doc = "29 - NVMCTRL_0"]
NVMCTRL_0 = 29,
#[doc = "30 - NVMCTRL_1"]
NVMCTRL_1 = 30,
#[doc = "31 - DMAC_0"]
DMAC_0 = 31,
#[doc = "32 - DMAC_1"]
DMAC_1 = 32,
#[doc = "33 - DMAC_2"]
DMAC_2 = 33,
#[doc = "34 - DMAC_3"]
DMAC_3 = 34,
#[doc = "35 - DMAC_OTHER"]
DMAC_OTHER = 35,
#[doc = "36 - EVSYS_0"]
EVSYS_0 = 36,
#[doc = "37 - EVSYS_1"]
EVSYS_1 = 37,
#[doc = "38 - EVSYS_2"]
EVSYS_2 = 38,
#[doc = "39 - EVSYS_3"]
EVSYS_3 = 39,
#[doc = "40 - EVSYS_OTHER"]
EVSYS_OTHER = 40,
#[doc = "41 - PAC"]
PAC = 41,
#[doc = "45 - RAMECC"]
RAMECC = 45,
#[doc = "46 - SERCOM0_0"]
SERCOM0_0 = 46,
#[doc = "47 - SERCOM0_1"]
SERCOM0_1 = 47,
#[doc = "48 - SERCOM0_2"]
SERCOM0_2 = 48,
#[doc = "49 - SERCOM0_OTHER"]
SERCOM0_OTHER = 49,
#[doc = "50 - SERCOM1_0"]
SERCOM1_0 = 50,
#[doc = "51 - SERCOM1_1"]
SERCOM1_1 = 51,
#[doc = "52 - SERCOM1_2"]
SERCOM1_2 = 52,
#[doc = "53 - SERCOM1_OTHER"]
SERCOM1_OTHER = 53,
#[doc = "54 - SERCOM2_0"]
SERCOM2_0 = 54,
#[doc = "55 - SERCOM2_1"]
SERCOM2_1 = 55,
#[doc = "56 - SERCOM2_2"]
SERCOM2_2 = 56,
#[doc = "57 - SERCOM2_OTHER"]
SERCOM2_OTHER = 57,
#[doc = "58 - SERCOM3_0"]
SERCOM3_0 = 58,
#[doc = "59 - SERCOM3_1"]
SERCOM3_1 = 59,
#[doc = "60 - SERCOM3_2"]
SERCOM3_2 = 60,
#[doc = "61 - SERCOM3_OTHER"]
SERCOM3_OTHER = 61,
#[doc = "62 - SERCOM4_0"]
SERCOM4_0 = 62,
#[doc = "63 - SERCOM4_1"]
SERCOM4_1 = 63,
#[doc = "64 - SERCOM4_2"]
SERCOM4_2 = 64,
#[doc = "65 - SERCOM4_OTHER"]
SERCOM4_OTHER = 65,
#[doc = "66 - SERCOM5_0"]
SERCOM5_0 = 66,
#[doc = "67 - SERCOM5_1"]
SERCOM5_1 = 67,
#[doc = "68 - SERCOM5_2"]
SERCOM5_2 = 68,
#[doc = "69 - SERCOM5_OTHER"]
SERCOM5_OTHER = 69,
#[doc = "78 - CAN0"]
CAN0 = 78,
#[doc = "80 - USB_OTHER"]
USB_OTHER = 80,
#[doc = "81 - USB_SOF_HSOF"]
USB_SOF_HSOF = 81,
#[doc = "82 - USB_TRCPT0"]
USB_TRCPT0 = 82,
#[doc = "83 - USB_TRCPT1"]
USB_TRCPT1 = 83,
#[doc = "85 - TCC0_OTHER"]
TCC0_OTHER = 85,
#[doc = "86 - TCC0_MC0"]
TCC0_MC0 = 86,
#[doc = "87 - TCC0_MC1"]
TCC0_MC1 = 87,
#[doc = "88 - TCC0_MC2"]
TCC0_MC2 = 88,
#[doc = "89 - TCC0_MC3"]
TCC0_MC3 = 89,
#[doc = "90 - TCC0_MC4"]
TCC0_MC4 = 90,
#[doc = "91 - TCC0_MC5"]
TCC0_MC5 = 91,
#[doc = "92 - TCC1_OTHER"]
TCC1_OTHER = 92,
#[doc = "93 - TCC1_MC0"]
TCC1_MC0 = 93,
#[doc = "94 - TCC1_MC1"]
TCC1_MC1 = 94,
#[doc = "95 - TCC1_MC2"]
TCC1_MC2 = 95,
#[doc = "96 - TCC1_MC3"]
TCC1_MC3 = 96,
#[doc = "97 - TCC2_OTHER"]
TCC2_OTHER = 97,
#[doc = "98 - TCC2_MC0"]
TCC2_MC0 = 98,
#[doc = "99 - TCC2_MC1"]
TCC2_MC1 = 99,
#[doc = "100 - TCC2_MC2"]
TCC2_MC2 = 100,
#[doc = "107 - TC0"]
TC0 = 107,
#[doc = "108 - TC1"]
TC1 = 108,
#[doc = "109 - TC2"]
TC2 = 109,
#[doc = "110 - TC3"]
TC3 = 110,
#[doc = "115 - PDEC_OTHER"]
PDEC_OTHER = 115,
#[doc = "116 - PDEC_MC0"]
PDEC_MC0 = 116,
#[doc = "117 - PDEC_MC1"]
PDEC_MC1 = 117,
#[doc = "118 - ADC0_OTHER"]
ADC0_OTHER = 118,
#[doc = "119 - ADC0_RESRDY"]
ADC0_RESRDY = 119,
#[doc = "120 - ADC1_OTHER"]
ADC1_OTHER = 120,
#[doc = "121 - ADC1_RESRDY"]
ADC1_RESRDY = 121,
#[doc = "122 - AC"]
AC = 122,
#[doc = "123 - DAC_OTHER"]
DAC_OTHER = 123,
#[doc = "124 - DAC_EMPTY_0"]
DAC_EMPTY_0 = 124,
#[doc = "125 - DAC_EMPTY_1"]
DAC_EMPTY_1 = 125,
#[doc = "126 - DAC_RESRDY_0"]
DAC_RESRDY_0 = 126,
#[doc = "127 - DAC_RESRDY_1"]
DAC_RESRDY_1 = 127,
#[doc = "129 - PCC"]
PCC = 129,
#[doc = "130 - AES"]
AES = 130,
#[doc = "131 - TRNG"]
TRNG = 131,
#[doc = "132 - ICM"]
ICM = 132,
#[doc = "134 - QSPI"]
QSPI = 134,
#[doc = "135 - SDHC0"]
SDHC0 = 135,
}
unsafe impl cortex_m::interrupt::InterruptNumber for Interrupt {
#[inline(always)]
fn number(self) -> u16 {
self as u16
}
}
#[doc = "Analog Comparators"]
pub struct AC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for AC {}
impl AC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const ac::RegisterBlock = 0x4200_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ac::RegisterBlock {
Self::PTR
}
}
impl Deref for AC {
type Target = ac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for AC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("AC").finish()
}
}
#[doc = "Analog Comparators"]
pub mod ac;
#[doc = "Analog Digital Converter"]
pub struct ADC0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC0 {}
impl ADC0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc0::RegisterBlock = 0x4300_1c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc0::RegisterBlock {
Self::PTR
}
}
impl Deref for ADC0 {
type Target = adc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC0 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC0").finish()
}
}
#[doc = "Analog Digital Converter"]
pub mod adc0;
#[doc = "Analog Digital Converter"]
pub struct ADC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC1 {}
impl ADC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc0::RegisterBlock = 0x4300_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc0::RegisterBlock {
Self::PTR
}
}
impl Deref for ADC1 {
type Target = adc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC1").finish()
}
}
#[doc = "Advanced Encryption Standard"]
pub struct AES {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for AES {}
impl AES {
#[doc = r"Pointer to the register block"]
pub const PTR: *const aes::RegisterBlock = 0x4200_2400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const aes::RegisterBlock {
Self::PTR
}
}
impl Deref for AES {
type Target = aes::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for AES {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("AES").finish()
}
}
#[doc = "Advanced Encryption Standard"]
pub mod aes;
#[doc = "Control Area Network"]
pub struct CAN0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CAN0 {}
impl CAN0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const can0::RegisterBlock = 0x4200_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const can0::RegisterBlock {
Self::PTR
}
}
impl Deref for CAN0 {
type Target = can0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CAN0 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CAN0").finish()
}
}
#[doc = "Control Area Network"]
pub mod can0;
#[doc = "Configurable Custom Logic"]
pub struct CCL {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CCL {}
impl CCL {
#[doc = r"Pointer to the register block"]
pub const PTR: *const ccl::RegisterBlock = 0x4200_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ccl::RegisterBlock {
Self::PTR
}
}
impl Deref for CCL {
type Target = ccl::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CCL {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CCL").finish()
}
}
#[doc = "Configurable Custom Logic"]
pub mod ccl;
#[doc = "Cortex M Cache Controller"]
pub struct CMCC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CMCC {}
impl CMCC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const cmcc::RegisterBlock = 0x4100_6000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const cmcc::RegisterBlock {
Self::PTR
}
}
impl Deref for CMCC {
type Target = cmcc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CMCC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CMCC").finish()
}
}
#[doc = "Cortex M Cache Controller"]
pub mod cmcc;
#[doc = "Digital-to-Analog Converter"]
pub struct DAC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DAC {}
impl DAC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac::RegisterBlock = 0x4300_2400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac::RegisterBlock {
Self::PTR
}
}
impl Deref for DAC {
type Target = dac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DAC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DAC").finish()
}
}
#[doc = "Digital-to-Analog Converter"]
pub mod dac;
#[doc = "Direct Memory Access Controller"]
pub struct DMAC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMAC {}
impl DMAC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dmac::RegisterBlock = 0x4100_a000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dmac::RegisterBlock {
Self::PTR
}
}
impl Deref for DMAC {
type Target = dmac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMAC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMAC").finish()
}
}
#[doc = "Direct Memory Access Controller"]
pub mod dmac;
#[doc = "Device Service Unit"]
pub struct DSU {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DSU {}
impl DSU {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dsu::RegisterBlock = 0x4100_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dsu::RegisterBlock {
Self::PTR
}
}
impl Deref for DSU {
type Target = dsu::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DSU {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DSU").finish()
}
}
#[doc = "Device Service Unit"]
pub mod dsu;
#[doc = "External Interrupt Controller"]
pub struct EIC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for EIC {}
impl EIC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const eic::RegisterBlock = 0x4000_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const eic::RegisterBlock {
Self::PTR
}
}
impl Deref for EIC {
type Target = eic::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for EIC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("EIC").finish()
}
}
#[doc = "External Interrupt Controller"]
pub mod eic;
#[doc = "Event System Interface"]
pub struct EVSYS {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for EVSYS {}
impl EVSYS {
#[doc = r"Pointer to the register block"]
pub const PTR: *const evsys::RegisterBlock = 0x4100_e000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const evsys::RegisterBlock {
Self::PTR
}
}
impl Deref for EVSYS {
type Target = evsys::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for EVSYS {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("EVSYS").finish()
}
}
#[doc = "Event System Interface"]
pub mod evsys;
#[doc = "Frequency Meter"]
pub struct FREQM {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FREQM {}
impl FREQM {
#[doc = r"Pointer to the register block"]
pub const PTR: *const freqm::RegisterBlock = 0x4000_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const freqm::RegisterBlock {
Self::PTR
}
}
impl Deref for FREQM {
type Target = freqm::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FREQM {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FREQM").finish()
}
}
#[doc = "Frequency Meter"]
pub mod freqm;
#[doc = "Generic Clock Generator"]
pub struct GCLK {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GCLK {}
impl GCLK {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gclk::RegisterBlock = 0x4000_1c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gclk::RegisterBlock {
Self::PTR
}
}
impl Deref for GCLK {
type Target = gclk::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GCLK {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GCLK").finish()
}
}
#[doc = "Generic Clock Generator"]
pub mod gclk;
#[doc = "HSB Matrix"]
pub struct HMATRIX {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for HMATRIX {}
impl HMATRIX {
#[doc = r"Pointer to the register block"]
pub const PTR: *const hmatrix::RegisterBlock = 0x4100_c000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const hmatrix::RegisterBlock {
Self::PTR
}
}
impl Deref for HMATRIX {
type Target = hmatrix::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for HMATRIX {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("HMATRIX").finish()
}
}
#[doc = "HSB Matrix"]
pub mod hmatrix;
#[doc = "Integrity Check Monitor"]
pub struct ICM {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ICM {}
impl ICM {
#[doc = r"Pointer to the register block"]
pub const PTR: *const icm::RegisterBlock = 0x4200_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const icm::RegisterBlock {
Self::PTR
}
}
impl Deref for ICM {
type Target = icm::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ICM {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ICM").finish()
}
}
#[doc = "Integrity Check Monitor"]
pub mod icm;
#[doc = "Main Clock"]
pub struct MCLK {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for MCLK {}
impl MCLK {
#[doc = r"Pointer to the register block"]
pub const PTR: *const mclk::RegisterBlock = 0x4000_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const mclk::RegisterBlock {
Self::PTR
}
}
impl Deref for MCLK {
type Target = mclk::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for MCLK {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("MCLK").finish()
}
}
#[doc = "Main Clock"]
pub mod mclk;
#[doc = "Non-Volatile Memory Controller"]
pub struct NVMCTRL {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for NVMCTRL {}
impl NVMCTRL {
#[doc = r"Pointer to the register block"]
pub const PTR: *const nvmctrl::RegisterBlock = 0x4100_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const nvmctrl::RegisterBlock {
Self::PTR
}
}
impl Deref for NVMCTRL {
type Target = nvmctrl::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for NVMCTRL {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("NVMCTRL").finish()
}
}
#[doc = "Non-Volatile Memory Controller"]
pub mod nvmctrl;
#[doc = "Oscillators Control"]
pub struct OSCCTRL {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for OSCCTRL {}
impl OSCCTRL {
#[doc = r"Pointer to the register block"]
pub const PTR: *const oscctrl::RegisterBlock = 0x4000_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const oscctrl::RegisterBlock {
Self::PTR
}
}
impl Deref for OSCCTRL {
type Target = oscctrl::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for OSCCTRL {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("OSCCTRL").finish()
}
}
#[doc = "Oscillators Control"]
pub mod oscctrl;
#[doc = "32kHz Oscillators Control"]
pub struct OSC32KCTRL {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for OSC32KCTRL {}
impl OSC32KCTRL {
#[doc = r"Pointer to the register block"]
pub const PTR: *const osc32kctrl::RegisterBlock = 0x4000_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const osc32kctrl::RegisterBlock {
Self::PTR
}
}
impl Deref for OSC32KCTRL {
type Target = osc32kctrl::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for OSC32KCTRL {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("OSC32KCTRL").finish()
}
}
#[doc = "32kHz Oscillators Control"]
pub mod osc32kctrl;
#[doc = "Peripheral Access Controller"]
pub struct PAC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PAC {}
impl PAC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pac::RegisterBlock = 0x4000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pac::RegisterBlock {
Self::PTR
}
}
impl Deref for PAC {
type Target = pac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PAC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PAC").finish()
}
}
#[doc = "Peripheral Access Controller"]
pub mod pac;
#[doc = "Parallel Capture Controller"]
pub struct PCC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PCC {}
impl PCC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pcc::RegisterBlock = 0x4300_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pcc::RegisterBlock {
Self::PTR
}
}
impl Deref for PCC {
type Target = pcc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PCC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PCC").finish()
}
}
#[doc = "Parallel Capture Controller"]
pub mod pcc;
#[doc = "Quadrature Decodeur"]
pub struct PDEC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PDEC {}
impl PDEC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pdec::RegisterBlock = 0x4200_1c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pdec::RegisterBlock {
Self::PTR
}
}
impl Deref for PDEC {
type Target = pdec::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PDEC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PDEC").finish()
}
}
#[doc = "Quadrature Decodeur"]
pub mod pdec;
#[doc = "Power Manager"]
pub struct PM {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PM {}
impl PM {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pm::RegisterBlock = 0x4000_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pm::RegisterBlock {
Self::PTR
}
}
impl Deref for PM {
type Target = pm::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PM {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PM").finish()
}
}
#[doc = "Power Manager"]
pub mod pm;
#[doc = "Port Module"]
pub struct PORT {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PORT {}
impl PORT {
#[doc = r"Pointer to the register block"]
pub const PTR: *const port::RegisterBlock = 0x4100_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const port::RegisterBlock {
Self::PTR
}
}
impl Deref for PORT {
type Target = port::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PORT {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PORT").finish()
}
}
#[doc = "Port Module"]
pub mod port;
#[doc = "Quad SPI interface"]
pub struct QSPI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for QSPI {}
impl QSPI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const qspi::RegisterBlock = 0x4200_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const qspi::RegisterBlock {
Self::PTR
}
}
impl Deref for QSPI {
type Target = qspi::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for QSPI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("QSPI").finish()
}
}
#[doc = "Quad SPI interface"]
pub mod qspi;
#[doc = "RAM ECC"]
pub struct RAMECC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RAMECC {}
impl RAMECC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const ramecc::RegisterBlock = 0x4102_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ramecc::RegisterBlock {
Self::PTR
}
}
impl Deref for RAMECC {
type Target = ramecc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RAMECC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RAMECC").finish()
}
}
#[doc = "RAM ECC"]
pub mod ramecc;
#[doc = "Reset Controller"]
pub struct RSTC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RSTC {}
impl RSTC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rstc::RegisterBlock = 0x4000_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rstc::RegisterBlock {
Self::PTR
}
}
impl Deref for RSTC {
type Target = rstc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RSTC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RSTC").finish()
}
}
#[doc = "Reset Controller"]
pub mod rstc;
#[doc = "Real-Time Counter"]
pub struct RTC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RTC {}
impl RTC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rtc::RegisterBlock = 0x4000_2400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rtc::RegisterBlock {
Self::PTR
}
}
impl Deref for RTC {
type Target = rtc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RTC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RTC").finish()
}
}
#[doc = "Real-Time Counter"]
pub mod rtc;
#[doc = "SD/MMC Host Controller"]
pub struct SDHC0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SDHC0 {}
impl SDHC0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sdhc0::RegisterBlock = 0x4500_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sdhc0::RegisterBlock {
Self::PTR
}
}
impl Deref for SDHC0 {
type Target = sdhc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SDHC0 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SDHC0").finish()
}
}
#[doc = "SD/MMC Host Controller"]
pub mod sdhc0;
#[doc = "Serial Communication Interface"]
pub struct SERCOM0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SERCOM0 {}
impl SERCOM0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sercom0::RegisterBlock = 0x4000_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sercom0::RegisterBlock {
Self::PTR
}
}
impl Deref for SERCOM0 {
type Target = sercom0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SERCOM0 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SERCOM0").finish()
}
}
#[doc = "Serial Communication Interface"]
pub mod sercom0;
#[doc = "Serial Communication Interface"]
pub struct SERCOM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SERCOM1 {}
impl SERCOM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sercom0::RegisterBlock = 0x4000_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sercom0::RegisterBlock {
Self::PTR
}
}
impl Deref for SERCOM1 {
type Target = sercom0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SERCOM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SERCOM1").finish()
}
}
#[doc = "Serial Communication Interface"]
pub struct SERCOM2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SERCOM2 {}
impl SERCOM2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sercom0::RegisterBlock = 0x4101_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sercom0::RegisterBlock {
Self::PTR
}
}
impl Deref for SERCOM2 {
type Target = sercom0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SERCOM2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SERCOM2").finish()
}
}
#[doc = "Serial Communication Interface"]
pub struct SERCOM3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SERCOM3 {}
impl SERCOM3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sercom0::RegisterBlock = 0x4101_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sercom0::RegisterBlock {
Self::PTR
}
}
impl Deref for SERCOM3 {
type Target = sercom0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SERCOM3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SERCOM3").finish()
}
}
#[doc = "Serial Communication Interface"]
pub struct SERCOM4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SERCOM4 {}
impl SERCOM4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sercom0::RegisterBlock = 0x4300_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sercom0::RegisterBlock {
Self::PTR
}
}
impl Deref for SERCOM4 {
type Target = sercom0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SERCOM4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SERCOM4").finish()
}
}
#[doc = "Serial Communication Interface"]
pub struct SERCOM5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SERCOM5 {}
impl SERCOM5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sercom0::RegisterBlock = 0x4300_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sercom0::RegisterBlock {
Self::PTR
}
}
impl Deref for SERCOM5 {
type Target = sercom0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SERCOM5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SERCOM5").finish()
}
}
#[doc = "Supply Controller"]
pub struct SUPC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SUPC {}
impl SUPC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const supc::RegisterBlock = 0x4000_1800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const supc::RegisterBlock {
Self::PTR
}
}
impl Deref for SUPC {
type Target = supc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SUPC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SUPC").finish()
}
}
#[doc = "Supply Controller"]
pub mod supc;
#[doc = "Basic Timer Counter"]
pub struct TC0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TC0 {}
impl TC0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tc0::RegisterBlock = 0x4000_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TC0 {
type Target = tc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TC0 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TC0").finish()
}
}
#[doc = "Basic Timer Counter"]
pub mod tc0;
#[doc = "Basic Timer Counter"]
pub struct TC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TC1 {}
impl TC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tc0::RegisterBlock = 0x4000_3c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TC1 {
type Target = tc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TC1").finish()
}
}
#[doc = "Basic Timer Counter"]
pub struct TC2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TC2 {}
impl TC2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tc0::RegisterBlock = 0x4101_a000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TC2 {
type Target = tc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TC2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TC2").finish()
}
}
#[doc = "Basic Timer Counter"]
pub struct TC3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TC3 {}
impl TC3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tc0::RegisterBlock = 0x4101_c000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TC3 {
type Target = tc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TC3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TC3").finish()
}
}
#[doc = "Timer Counter Control"]
pub struct TCC0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TCC0 {}
impl TCC0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tcc0::RegisterBlock = 0x4101_6000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tcc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TCC0 {
type Target = tcc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TCC0 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TCC0").finish()
}
}
#[doc = "Timer Counter Control"]
pub mod tcc0;
#[doc = "Timer Counter Control"]
pub struct TCC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TCC1 {}
impl TCC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tcc0::RegisterBlock = 0x4101_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tcc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TCC1 {
type Target = tcc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TCC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TCC1").finish()
}
}
#[doc = "Timer Counter Control"]
pub struct TCC2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TCC2 {}
impl TCC2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tcc0::RegisterBlock = 0x4200_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tcc0::RegisterBlock {
Self::PTR
}
}
impl Deref for TCC2 {
type Target = tcc0::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TCC2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TCC2").finish()
}
}
#[doc = "True Random Generator"]
pub struct TRNG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TRNG {}
impl TRNG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const trng::RegisterBlock = 0x4200_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const trng::RegisterBlock {
Self::PTR
}
}
impl Deref for TRNG {
type Target = trng::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TRNG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TRNG").finish()
}
}
#[doc = "True Random Generator"]
pub mod trng;
#[doc = "Universal Serial Bus"]
pub struct USB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USB {}
impl USB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usb::RegisterBlock = 0x4100_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usb::RegisterBlock {
Self::PTR
}
}
impl Deref for USB {
type Target = usb::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USB").finish()
}
}
#[doc = "Universal Serial Bus"]
pub mod usb;
#[doc = "Watchdog Timer"]
pub struct WDT {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for WDT {}
impl WDT {
#[doc = r"Pointer to the register block"]
pub const PTR: *const wdt::RegisterBlock = 0x4000_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const wdt::RegisterBlock {
Self::PTR
}
}
impl Deref for WDT {
type Target = wdt::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for WDT {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("WDT").finish()
}
}
#[doc = "Watchdog Timer"]
pub mod wdt;
#[doc = "Core Debug Register"]
pub struct COREDEBUG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for COREDEBUG {}
impl COREDEBUG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const core_debug::RegisterBlock = 0xe000_edf0 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const core_debug::RegisterBlock {
Self::PTR
}
}
impl Deref for COREDEBUG {
type Target = core_debug::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for COREDEBUG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("COREDEBUG").finish()
}
}
#[doc = "Core Debug Register"]
pub mod core_debug;
#[doc = "Embedded Trace Macrocell"]
pub struct ETM {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ETM {}
impl ETM {
#[doc = r"Pointer to the register block"]
pub const PTR: *const etm::RegisterBlock = 0xe004_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const etm::RegisterBlock {
Self::PTR
}
}
impl Deref for ETM {
type Target = etm::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ETM {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ETM").finish()
}
}
#[doc = "Embedded Trace Macrocell"]
pub mod etm;
#[doc = "System timer"]
pub struct SYSTICK {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SYSTICK {}
impl SYSTICK {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sys_tick::RegisterBlock = 0xe000_e010 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sys_tick::RegisterBlock {
Self::PTR
}
}
impl Deref for SYSTICK {
type Target = sys_tick::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SYSTICK {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SYSTICK").finish()
}
}
#[doc = "System timer"]
pub mod sys_tick;
#[doc = "System Control Registers"]
pub struct SYSTEMCONTROL {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SYSTEMCONTROL {}
impl SYSTEMCONTROL {
#[doc = r"Pointer to the register block"]
pub const PTR: *const system_control::RegisterBlock = 0xe000_e000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const system_control::RegisterBlock {
Self::PTR
}
}
impl Deref for SYSTEMCONTROL {
type Target = system_control::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SYSTEMCONTROL {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SYSTEMCONTROL").finish()
}
}
#[doc = "System Control Registers"]
pub mod system_control;
#[doc = "Trace Port Interface Register"]
pub struct TPI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TPI {}
impl TPI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tpi::RegisterBlock = 0xe004_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tpi::RegisterBlock {
Self::PTR
}
}
impl Deref for TPI {
type Target = tpi::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TPI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TPI").finish()
}
}
#[doc = "Trace Port Interface Register"]
pub mod tpi;
#[no_mangle]
static mut DEVICE_PERIPHERALS: bool = false;
#[doc = r"All the peripherals"]
#[allow(non_snake_case)]
pub struct Peripherals {
#[doc = "AC"]
pub AC: AC,
#[doc = "ADC0"]
pub ADC0: ADC0,
#[doc = "ADC1"]
pub ADC1: ADC1,
#[doc = "AES"]
pub AES: AES,
#[doc = "CAN0"]
pub CAN0: CAN0,
#[doc = "CCL"]
pub CCL: CCL,
#[doc = "CMCC"]
pub CMCC: CMCC,
#[doc = "DAC"]
pub DAC: DAC,
#[doc = "DMAC"]
pub DMAC: DMAC,
#[doc = "DSU"]
pub DSU: DSU,
#[doc = "EIC"]
pub EIC: EIC,
#[doc = "EVSYS"]
pub EVSYS: EVSYS,
#[doc = "FREQM"]
pub FREQM: FREQM,
#[doc = "GCLK"]
pub GCLK: GCLK,
#[doc = "HMATRIX"]
pub HMATRIX: HMATRIX,
#[doc = "ICM"]
pub ICM: ICM,
#[doc = "MCLK"]
pub MCLK: MCLK,
#[doc = "NVMCTRL"]
pub NVMCTRL: NVMCTRL,
#[doc = "OSCCTRL"]
pub OSCCTRL: OSCCTRL,
#[doc = "OSC32KCTRL"]
pub OSC32KCTRL: OSC32KCTRL,
#[doc = "PAC"]
pub PAC: PAC,
#[doc = "PCC"]
pub PCC: PCC,
#[doc = "PDEC"]
pub PDEC: PDEC,
#[doc = "PM"]
pub PM: PM,
#[doc = "PORT"]
pub PORT: PORT,
#[doc = "QSPI"]
pub QSPI: QSPI,
#[doc = "RAMECC"]
pub RAMECC: RAMECC,
#[doc = "RSTC"]
pub RSTC: RSTC,
#[doc = "RTC"]
pub RTC: RTC,
#[doc = "SDHC0"]
pub SDHC0: SDHC0,
#[doc = "SERCOM0"]
pub SERCOM0: SERCOM0,
#[doc = "SERCOM1"]
pub SERCOM1: SERCOM1,
#[doc = "SERCOM2"]
pub SERCOM2: SERCOM2,
#[doc = "SERCOM3"]
pub SERCOM3: SERCOM3,
#[doc = "SERCOM4"]
pub SERCOM4: SERCOM4,
#[doc = "SERCOM5"]
pub SERCOM5: SERCOM5,
#[doc = "SUPC"]
pub SUPC: SUPC,
#[doc = "TC0"]
pub TC0: TC0,
#[doc = "TC1"]
pub TC1: TC1,
#[doc = "TC2"]
pub TC2: TC2,
#[doc = "TC3"]
pub TC3: TC3,
#[doc = "TCC0"]
pub TCC0: TCC0,
#[doc = "TCC1"]
pub TCC1: TCC1,
#[doc = "TCC2"]
pub TCC2: TCC2,
#[doc = "TRNG"]
pub TRNG: TRNG,
#[doc = "USB"]
pub USB: USB,
#[doc = "WDT"]
pub WDT: WDT,
#[doc = "COREDEBUG"]
pub COREDEBUG: COREDEBUG,
#[doc = "ETM"]
pub ETM: ETM,
#[doc = "SYSTICK"]
pub SYSTICK: SYSTICK,
#[doc = "SYSTEMCONTROL"]
pub SYSTEMCONTROL: SYSTEMCONTROL,
#[doc = "TPI"]
pub TPI: TPI,
}
impl Peripherals {
#[doc = r"Returns all the peripherals *once*"]
#[inline]
pub fn take() -> Option<Self> {
cortex_m::interrupt::free(|_| {
if unsafe { DEVICE_PERIPHERALS } {
None
} else {
Some(unsafe { Peripherals::steal() })
}
})
}
#[doc = r"Unchecked version of `Peripherals::take`"]
#[inline]
pub unsafe fn steal() -> Self {
DEVICE_PERIPHERALS = true;
Peripherals {
AC: AC {
_marker: PhantomData,
},
ADC0: ADC0 {
_marker: PhantomData,
},
ADC1: ADC1 {
_marker: PhantomData,
},
AES: AES {
_marker: PhantomData,
},
CAN0: CAN0 {
_marker: PhantomData,
},
CCL: CCL {
_marker: PhantomData,
},
CMCC: CMCC {
_marker: PhantomData,
},
DAC: DAC {
_marker: PhantomData,
},
DMAC: DMAC {
_marker: PhantomData,
},
DSU: DSU {
_marker: PhantomData,
},
EIC: EIC {
_marker: PhantomData,
},
EVSYS: EVSYS {
_marker: PhantomData,
},
FREQM: FREQM {
_marker: PhantomData,
},
GCLK: GCLK {
_marker: PhantomData,
},
HMATRIX: HMATRIX {
_marker: PhantomData,
},
ICM: ICM {
_marker: PhantomData,
},
MCLK: MCLK {
_marker: PhantomData,
},
NVMCTRL: NVMCTRL {
_marker: PhantomData,
},
OSCCTRL: OSCCTRL {
_marker: PhantomData,
},
OSC32KCTRL: OSC32KCTRL {
_marker: PhantomData,
},
PAC: PAC {
_marker: PhantomData,
},
PCC: PCC {
_marker: PhantomData,
},
PDEC: PDEC {
_marker: PhantomData,
},
PM: PM {
_marker: PhantomData,
},
PORT: PORT {
_marker: PhantomData,
},
QSPI: QSPI {
_marker: PhantomData,
},
RAMECC: RAMECC {
_marker: PhantomData,
},
RSTC: RSTC {
_marker: PhantomData,
},
RTC: RTC {
_marker: PhantomData,
},
SDHC0: SDHC0 {
_marker: PhantomData,
},
SERCOM0: SERCOM0 {
_marker: PhantomData,
},
SERCOM1: SERCOM1 {
_marker: PhantomData,
},
SERCOM2: SERCOM2 {
_marker: PhantomData,
},
SERCOM3: SERCOM3 {
_marker: PhantomData,
},
SERCOM4: SERCOM4 {
_marker: PhantomData,
},
SERCOM5: SERCOM5 {
_marker: PhantomData,
},
SUPC: SUPC {
_marker: PhantomData,
},
TC0: TC0 {
_marker: PhantomData,
},
TC1: TC1 {
_marker: PhantomData,
},
TC2: TC2 {
_marker: PhantomData,
},
TC3: TC3 {
_marker: PhantomData,
},
TCC0: TCC0 {
_marker: PhantomData,
},
TCC1: TCC1 {
_marker: PhantomData,
},
TCC2: TCC2 {
_marker: PhantomData,
},
TRNG: TRNG {
_marker: PhantomData,
},
USB: USB {
_marker: PhantomData,
},
WDT: WDT {
_marker: PhantomData,
},
COREDEBUG: COREDEBUG {
_marker: PhantomData,
},
ETM: ETM {
_marker: PhantomData,
},
SYSTICK: SYSTICK {
_marker: PhantomData,
},
SYSTEMCONTROL: SYSTEMCONTROL {
_marker: PhantomData,
},
TPI: TPI {
_marker: PhantomData,
},
}
}
}
| 26.125262 | 348 | 0.572457 |
5d3a2ee8fe0233082aefb54107e7ca3a4c0d9b63 | 99 | mod discovery_handler;
mod discovery_impl;
pub use self::discovery_handler::OnvifDiscoveryHandler;
| 24.75 | 55 | 0.858586 |
e8f93aac7d4c35a24ab75ca8498dcd51d10a6bdf | 4,351 | use proc_macro2::TokenStream;
use quote::quote;
pub use self_rust_tokenize_derive::SelfRustTokenize;
pub trait SelfRustTokenize {
/// Returns the tokens used to construct self
fn to_tokens(&self) -> TokenStream;
}
macro_rules! implement_using_quote_to_tokens {
($($T:ty),*) => {
$(
impl SelfRustTokenize for $T {
fn to_tokens(&self) -> TokenStream {
quote::ToTokens::to_token_stream(self)
}
}
)*
};
}
implement_using_quote_to_tokens!(
u8,
u16,
u32,
u64,
u128,
i8,
i16,
i32,
i64,
i128,
f32,
f64,
char,
bool,
&'static str
);
impl<T: SelfRustTokenize> SelfRustTokenize for Box<T> {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = (&**self).to_tokens();
quote!(Box::new(#inner_tokens))
}
}
impl<T: SelfRustTokenize> SelfRustTokenize for Vec<T> {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = self.iter().map(SelfRustTokenize::to_tokens);
quote!(vec![#(#inner_tokens),*])
}
}
impl<T: SelfRustTokenize> SelfRustTokenize for Option<T> {
fn to_tokens(&self) -> TokenStream {
match self {
Some(value) => {
let inner_tokens = value.to_tokens();
quote!(Some(#inner_tokens))
}
None => quote!(None),
}
}
}
impl SelfRustTokenize for String {
fn to_tokens(&self) -> TokenStream {
let value = self.as_str();
quote!(String::from(#value))
}
}
impl<T: SelfRustTokenize, const N: usize> SelfRustTokenize for [T; N] {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = self.iter().map(SelfRustTokenize::to_tokens);
quote!([#(#inner_tokens),*])
}
}
impl<T: SelfRustTokenize> SelfRustTokenize for [T] {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = self.iter().map(SelfRustTokenize::to_tokens);
quote!(&[#(#inner_tokens),*])
}
}
impl SelfRustTokenize for () {
fn to_tokens(&self) -> TokenStream {
quote!(())
}
}
// Thanks! https://stackoverflow.com/a/56700760/10048799
macro_rules! tuple_impls {
( $( $name:ident )+ ) => {
impl<$($name: SelfRustTokenize),+> SelfRustTokenize for ($($name,)+)
{
fn to_tokens(&self) -> TokenStream {
#[allow(non_snake_case)]
let ($($name,)+) = self;
let inner_tokens = &[$(SelfRustTokenize::to_tokens($name)),+];
quote!((#(#inner_tokens,)*))
}
}
};
}
tuple_impls! { A }
tuple_impls! { A B }
tuple_impls! { A B C }
tuple_impls! { A B C D }
tuple_impls! { A B C D E }
tuple_impls! { A B C D E F }
tuple_impls! { A B C D E F G }
tuple_impls! { A B C D E F G H }
tuple_impls! { A B C D E F G H I }
tuple_impls! { A B C D E F G H I J }
tuple_impls! { A B C D E F G H I J K }
tuple_impls! { A B C D E F G H I J K L }
#[cfg(feature = "references")]
mod references {
use super::{SelfRustTokenize, TokenStream};
use quote::quote;
impl<'a, T: SelfRustTokenize> SelfRustTokenize for &'a T {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = (*self).to_tokens();
quote!(&#inner_tokens)
}
}
impl<'a, T: SelfRustTokenize> SelfRustTokenize for &'a mut T {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = (**self).to_tokens();
quote!(&mut #inner_tokens)
}
}
impl<'a, T: SelfRustTokenize> SelfRustTokenize for &'a [T] {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = self.iter().map(SelfRustTokenize::to_tokens);
quote!(&[#(#inner_tokens),*])
}
}
impl<'a, T: SelfRustTokenize> SelfRustTokenize for &'a mut [T] {
fn to_tokens(&self) -> TokenStream {
let inner_tokens = self.iter().map(SelfRustTokenize::to_tokens);
quote!(&mut [#(#inner_tokens),*])
}
}
}
#[cfg(feature = "smallvec")]
impl<T: smallvec::Array> SelfRustTokenize for smallvec::SmallVec<T>
where
T::Item: SelfRustTokenize,
{
fn to_tokens(&self) -> TokenStream {
let inner_tokens = self.iter().map(SelfRustTokenize::to_tokens);
quote!(::smallvec::smallvec![#(#inner_tokens),*])
}
}
| 26.369697 | 78 | 0.569524 |
1cb525dc7aea47e55197d2187bc2a4775df23707 | 793 |
pub fn print_difference(x: f32, y: f32) {
println!("Difference between {} and {} is {}", x, y, (x - y).abs());
}
pub fn print_array(a: [f32; 2]) {
println!("The coordinates are ({}, {})", a[0], a[1]);
}
pub fn ding(x: i32) {
if x == 13 {
println!("Ding, you found 13!");
}
}
pub fn on_off(val: bool) {
if val {
println!("Lights are on!");
}
}
pub fn print_distance(x: f32, y: f32) {
// Using z.0 and z.1 is not nearly as nice as using x and y. Lucky for
// us, Rust supports destructuring function arguments. Try replacing "z" in
// the parameter list above with "(x, y)" and then adjust the a function
// body to use x and y.
println!(
"Distance to the origin is {}",
( x.powf(2.0) + y.powf(2.0) ).sqrt());
}
| 25.580645 | 80 | 0.556116 |
f4a42f25f4cadd3ab7dde2e957ae4bc0912e1ce6 | 649 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[no_mangle]
pub extern "C" fn proxy_abi_version_0_2_0() {}
| 38.176471 | 75 | 0.742681 |
26428474f1b3bc578262df2b6a4719b4013101a8 | 2,714 | // errors6.rs
// Using catch-all error types like `Box<dyn error::Error>` isn't recommended
// for library code, where callers might want to make decisions based on the
// error content, instead of printing it out or propagating it further. Here,
// we define a custom error type to make it possible for callers to decide
// what to do next when our function returns an error.
// Make these tests pass! Execute `rustlings hint errors6` for hints :)
use std::num::ParseIntError;
// This is a custom error type that we will be using in `parse_pos_nonzero()`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
Creation(CreationError),
ParseInt(ParseIntError),
}
impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err)
}
// TODO: add another error conversion function here.
fn from_parse(err: ParseIntError) -> ParsePosNonzeroError {
ParsePosNonzeroError::ParseInt(err)
}
}
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
// TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error.
let x = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parse)?;
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}
// Don't change anything below this line.
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
match value {
x if x < 0 => Err(CreationError::Negative),
x if x == 0 => Err(CreationError::Zero),
x => Ok(PositiveNonzeroInteger(x as u64)),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_error() {
// We can't construct a ParseIntError, so we have to pattern match.
assert!(matches!(
parse_pos_nonzero("not a number"),
Err(ParsePosNonzeroError::ParseInt(_))
));
}
#[test]
fn test_negative() {
assert_eq!(
parse_pos_nonzero("-555"),
Err(ParsePosNonzeroError::Creation(CreationError::Negative))
);
}
#[test]
fn test_zero() {
assert_eq!(
parse_pos_nonzero("0"),
Err(ParsePosNonzeroError::Creation(CreationError::Zero))
);
}
#[test]
fn test_positive() {
let x = PositiveNonzeroInteger::new(42);
assert!(x.is_ok());
assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap()));
}
}
fn main() {}
| 27.979381 | 87 | 0.651069 |
fc0815a410561bfa5ce08fe288e792a75eda486b | 5,307 | use crate::methodobject::PyMethodDef;
use crate::moduleobject::PyModuleDef;
use crate::object::PyObject;
use crate::pyport::Py_ssize_t;
use std::os::raw::{c_char, c_int, c_long};
extern "C" {
#[cfg_attr(PyPy, link_name = "PyPyArg_Parse")]
pub fn PyArg_Parse(arg1: *mut PyObject, arg2: *const c_char, ...) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPyArg_ParseTuple")]
pub fn PyArg_ParseTuple(arg1: *mut PyObject, arg2: *const c_char, ...) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPyArg_ParseTupleAndKeywords")]
pub fn PyArg_ParseTupleAndKeywords(
arg1: *mut PyObject,
arg2: *mut PyObject,
arg3: *const c_char,
arg4: *mut *mut c_char,
...
) -> c_int;
pub fn PyArg_ValidateKeywordArguments(arg1: *mut PyObject) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPyArg_UnpackTuple")]
pub fn PyArg_UnpackTuple(
arg1: *mut PyObject,
arg2: *const c_char,
arg3: Py_ssize_t,
arg4: Py_ssize_t,
...
) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPy_BuildValue")]
pub fn Py_BuildValue(arg1: *const c_char, ...) -> *mut PyObject;
// #[cfg_attr(PyPy, link_name = "_PyPy_BuildValue_SizeT")]
//pub fn _Py_BuildValue_SizeT(arg1: *const c_char, ...)
// -> *mut PyObject;
// #[cfg_attr(PyPy, link_name = "PyPy_VaBuildValue")]
// skipped non-limited _PyArg_UnpackStack
// skipped non-limited _PyArg_NoKeywords
// skipped non-limited _PyArg_NoKwnames
// skipped non-limited _PyArg_NoPositional
// skipped non-limited _PyArg_BadArgument
// skipped non-limited _PyArg_CheckPositional
//pub fn Py_VaBuildValue(arg1: *const c_char, arg2: va_list)
// -> *mut PyObject;
// skipped non-limited _Py_VaBuildStack
// skipped non-limited _PyArg_Parser
// skipped non-limited _PyArg_ParseTupleAndKeywordsFast
// skipped non-limited _PyArg_ParseStack
// skipped non-limited _PyArg_ParseStackAndKeywords
// skipped non-limited _PyArg_VaParseTupleAndKeywordsFast
// skipped non-limited _PyArg_UnpackKeywords
// skipped non-limited _PyArg_Fini
#[cfg(Py_3_10)]
pub fn PyModule_AddObjectRef(
module: *mut PyObject,
name: *const c_char,
value: *mut PyObject,
) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPyModule_AddObject")]
pub fn PyModule_AddObject(
module: *mut PyObject,
name: *const c_char,
value: *mut PyObject,
) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPyModule_AddIntConstant")]
pub fn PyModule_AddIntConstant(
module: *mut PyObject,
name: *const c_char,
value: c_long,
) -> c_int;
#[cfg_attr(PyPy, link_name = "PyPyModule_AddStringConstant")]
pub fn PyModule_AddStringConstant(
module: *mut PyObject,
name: *const c_char,
value: *const c_char,
) -> c_int;
// skipped non-limited / 3.9 PyModule_AddType
// skipped PyModule_AddIntMacro
// skipped PyModule_AddStringMacro
pub fn PyModule_SetDocString(arg1: *mut PyObject, arg2: *const c_char) -> c_int;
pub fn PyModule_AddFunctions(arg1: *mut PyObject, arg2: *mut PyMethodDef) -> c_int;
pub fn PyModule_ExecDef(module: *mut PyObject, def: *mut PyModuleDef) -> c_int;
}
pub const Py_CLEANUP_SUPPORTED: i32 = 0x2_0000;
pub const PYTHON_API_VERSION: i32 = 1013;
pub const PYTHON_ABI_VERSION: i32 = 3;
extern "C" {
#[cfg(not(py_sys_config = "Py_TRACE_REFS"))]
#[cfg_attr(PyPy, link_name = "PyPyModule_Create2")]
pub fn PyModule_Create2(module: *mut PyModuleDef, apiver: c_int) -> *mut PyObject;
#[cfg(py_sys_config = "Py_TRACE_REFS")]
fn PyModule_Create2TraceRefs(module: *mut PyModuleDef, apiver: c_int) -> *mut PyObject;
#[cfg(not(py_sys_config = "Py_TRACE_REFS"))]
pub fn PyModule_FromDefAndSpec2(
def: *mut PyModuleDef,
spec: *mut PyObject,
module_api_version: c_int,
) -> *mut PyObject;
#[cfg(py_sys_config = "Py_TRACE_REFS")]
fn PyModule_FromDefAndSpec2TraceRefs(
def: *mut PyModuleDef,
spec: *mut PyObject,
module_api_version: c_int,
) -> *mut PyObject;
}
#[cfg(py_sys_config = "Py_TRACE_REFS")]
#[inline]
pub unsafe fn PyModule_Create2(module: *mut PyModuleDef, apiver: c_int) -> *mut PyObject {
PyModule_Create2TraceRefs(module, apiver)
}
#[cfg(py_sys_config = "Py_TRACE_REFS")]
#[inline]
pub unsafe fn PyModule_FromDefAndSpec2(
def: *mut PyModuleDef,
spec: *mut PyObject,
module_api_version: c_int,
) -> *mut PyObject {
PyModule_FromDefAndSpec2TraceRefs(def, spec, module_api_version)
}
#[inline]
pub unsafe fn PyModule_Create(module: *mut PyModuleDef) -> *mut PyObject {
PyModule_Create2(
module,
if cfg!(Py_LIMITED_API) {
PYTHON_ABI_VERSION
} else {
PYTHON_API_VERSION
},
)
}
#[inline]
pub unsafe fn PyModule_FromDefAndSpec(def: *mut PyModuleDef, spec: *mut PyObject) -> *mut PyObject {
PyModule_FromDefAndSpec2(
def,
spec,
if cfg!(Py_LIMITED_API) {
PYTHON_ABI_VERSION
} else {
PYTHON_API_VERSION
},
)
}
#[cfg(not(Py_LIMITED_API))]
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut _Py_PackageContext: *const c_char;
}
| 32.759259 | 100 | 0.664594 |
ac502e3a786413625727934e93f473ddbd7125c7 | 1,150 | use super::navi_table_name::NaviTableName;
use apllodb_immutable_schema_engine_domain::vtable::VTable;
use serde::{Deserialize, Serialize};
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Serialize, Deserialize)]
pub(super) struct CreateTableSqlForNavi(String);
impl CreateTableSqlForNavi {
pub(super) fn as_str(&self) -> &str {
&self.0
}
}
impl From<&VTable> for CreateTableSqlForNavi {
fn from(vtable: &VTable) -> Self {
use crate::sqlite::to_sql_string::ToSqlString;
// TODO Set primary key for performance.
let sql = format!(
"
CREATE TABLE {navi_table_name} (
{pk_coldefs},
{cname_revision} INTEGER NOT NULL,
{cname_version_number} INTEGER
)
",
navi_table_name = NaviTableName::from(vtable.table_name().clone()).to_sql_string(),
pk_coldefs = vtable
.table_wide_constraints()
.pk_column_data_types()
.to_sql_string(),
cname_revision = super::CNAME_REVISION,
cname_version_number = super::CNAME_VERSION_NUMBER
);
Self(sql)
}
}
| 28.75 | 95 | 0.64 |
d7f41d43601046080a895670256c44ab150c70ba | 9,197 | // TODO: Temporary redirect
crate use crate::context::CommandRegistry;
use crate::evaluate::{evaluate_baseline_expr, Scope};
use crate::parser::{hir, hir::SyntaxType, parse_command, CallNode};
use crate::prelude::*;
use derive_new::new;
use indexmap::IndexMap;
use log::trace;
use serde::{Deserialize, Serialize};
use std::fmt;
#[allow(unused)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum NamedType {
Switch,
Mandatory(SyntaxType),
Optional(SyntaxType),
}
#[allow(unused)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PositionalType {
Mandatory(String, SyntaxType),
Optional(String, SyntaxType),
}
impl PositionalType {
pub fn mandatory(name: &str, ty: SyntaxType) -> PositionalType {
PositionalType::Mandatory(name.to_string(), ty)
}
pub fn mandatory_any(name: &str) -> PositionalType {
PositionalType::Mandatory(name.to_string(), SyntaxType::Any)
}
pub fn mandatory_block(name: &str) -> PositionalType {
PositionalType::Mandatory(name.to_string(), SyntaxType::Block)
}
pub fn optional(name: &str, ty: SyntaxType) -> PositionalType {
PositionalType::Optional(name.to_string(), ty)
}
pub fn optional_any(name: &str) -> PositionalType {
PositionalType::Optional(name.to_string(), SyntaxType::Any)
}
#[allow(unused)]
crate fn to_coerce_hint(&self) -> Option<SyntaxType> {
match self {
PositionalType::Mandatory(_, SyntaxType::Block)
| PositionalType::Optional(_, SyntaxType::Block) => Some(SyntaxType::Block),
_ => None,
}
}
crate fn name(&self) -> &str {
match self {
PositionalType::Mandatory(s, _) => s,
PositionalType::Optional(s, _) => s,
}
}
crate fn syntax_type(&self) -> SyntaxType {
match *self {
PositionalType::Mandatory(_, t) => t,
PositionalType::Optional(_, t) => t,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, new)]
pub struct Signature {
pub name: String,
#[new(default)]
pub positional: Vec<PositionalType>,
#[new(value = "false")]
pub rest_positional: bool,
#[new(default)]
pub named: IndexMap<String, NamedType>,
#[new(value = "false")]
pub is_filter: bool,
}
impl Signature {
pub fn build(name: impl Into<String>) -> Signature {
Signature::new(name.into())
}
pub fn required(mut self, name: impl Into<String>, ty: impl Into<SyntaxType>) -> Signature {
self.positional
.push(PositionalType::Mandatory(name.into(), ty.into()));
self
}
pub fn optional(mut self, name: impl Into<String>, ty: impl Into<SyntaxType>) -> Signature {
self.positional
.push(PositionalType::Optional(name.into(), ty.into()));
self
}
pub fn named(mut self, name: impl Into<String>, ty: impl Into<SyntaxType>) -> Signature {
self.named
.insert(name.into(), NamedType::Optional(ty.into()));
self
}
pub fn required_named(
mut self,
name: impl Into<String>,
ty: impl Into<SyntaxType>,
) -> Signature {
self.named
.insert(name.into(), NamedType::Mandatory(ty.into()));
self
}
pub fn switch(mut self, name: impl Into<String>) -> Signature {
self.named.insert(name.into(), NamedType::Switch);
self
}
pub fn filter(mut self) -> Signature {
self.is_filter = true;
self
}
pub fn rest(mut self) -> Signature {
self.rest_positional = true;
self
}
}
#[derive(Debug, Default, new, Serialize, Deserialize, Clone)]
pub struct EvaluatedArgs {
pub positional: Option<Vec<Tagged<Value>>>,
pub named: Option<IndexMap<String, Tagged<Value>>>,
}
impl EvaluatedArgs {
pub fn slice_from(&self, from: usize) -> Vec<Tagged<Value>> {
let positional = &self.positional;
match positional {
None => vec![],
Some(list) => list[from..].to_vec(),
}
}
}
#[derive(new)]
pub struct DebugEvaluatedPositional<'a> {
positional: &'a Option<Vec<Tagged<Value>>>,
}
impl fmt::Debug for DebugEvaluatedPositional<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.positional {
None => write!(f, "None"),
Some(positional) => f
.debug_list()
.entries(positional.iter().map(|p| p.debug()))
.finish(),
}
}
}
#[derive(new)]
pub struct DebugEvaluatedNamed<'a> {
named: &'a Option<IndexMap<String, Tagged<Value>>>,
}
impl fmt::Debug for DebugEvaluatedNamed<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.named {
None => write!(f, "None"),
Some(named) => f
.debug_map()
.entries(named.iter().map(|(k, v)| (k, v.debug())))
.finish(),
}
}
}
pub struct DebugEvaluatedArgs<'a> {
args: &'a EvaluatedArgs,
}
impl fmt::Debug for DebugEvaluatedArgs<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = f.debug_struct("Args");
s.field(
"positional",
&DebugEvaluatedPositional::new(&self.args.positional),
);
s.field("named", &DebugEvaluatedNamed::new(&self.args.named));
s.finish()
}
}
impl EvaluatedArgs {
pub fn debug(&'a self) -> DebugEvaluatedArgs<'a> {
DebugEvaluatedArgs { args: self }
}
pub fn nth(&self, pos: usize) -> Option<&Tagged<Value>> {
match &self.positional {
None => None,
Some(array) => array.iter().nth(pos),
}
}
pub fn expect_nth(&self, pos: usize) -> Result<&Tagged<Value>, ShellError> {
match &self.positional {
None => Err(ShellError::unimplemented("Better error: expect_nth")),
Some(array) => match array.iter().nth(pos) {
None => Err(ShellError::unimplemented("Better error: expect_nth")),
Some(item) => Ok(item),
},
}
}
pub fn len(&self) -> usize {
match &self.positional {
None => 0,
Some(array) => array.len(),
}
}
pub fn has(&self, name: &str) -> bool {
match &self.named {
None => false,
Some(named) => named.contains_key(name),
}
}
pub fn get(&self, name: &str) -> Option<&Tagged<Value>> {
match &self.named {
None => None,
Some(named) => named.get(name),
}
}
pub fn positional_iter(&'a self) -> PositionalIter<'a> {
match &self.positional {
None => PositionalIter::Empty,
Some(v) => {
let iter = v.iter();
PositionalIter::Array(iter)
}
}
}
}
pub enum PositionalIter<'a> {
Empty,
Array(std::slice::Iter<'a, Tagged<Value>>),
}
impl Iterator for PositionalIter<'a> {
type Item = &'a Tagged<Value>;
fn next(&mut self) -> Option<Self::Item> {
match self {
PositionalIter::Empty => None,
PositionalIter::Array(iter) => iter.next(),
}
}
}
impl Signature {
crate fn parse_args(
&self,
call: &Tagged<CallNode>,
registry: &CommandRegistry,
source: &Text,
) -> Result<hir::Call, ShellError> {
let args = parse_command(self, registry, call, source)?;
trace!("parsed args: {:?}", args);
Ok(args)
}
#[allow(unused)]
crate fn signature(&self) -> String {
format!("TODO")
}
}
crate fn evaluate_args(
call: &hir::Call,
registry: &CommandRegistry,
scope: &Scope,
source: &Text,
) -> Result<EvaluatedArgs, ShellError> {
let positional: Result<Option<Vec<_>>, _> = call
.positional()
.as_ref()
.map(|p| {
p.iter()
.map(|e| evaluate_baseline_expr(e, registry, scope, source))
.collect()
})
.transpose();
let positional = positional?;
let named: Result<Option<IndexMap<String, Tagged<Value>>>, ShellError> = call
.named()
.as_ref()
.map(|n| {
let mut results = IndexMap::new();
for (name, value) in n.named.iter() {
match value {
hir::named::NamedValue::PresentSwitch(span) => {
results.insert(
name.clone(),
Tagged::from_simple_spanned_item(Value::boolean(true), *span),
);
}
hir::named::NamedValue::Value(expr) => {
results.insert(
name.clone(),
evaluate_baseline_expr(expr, registry, scope, source)?,
);
}
_ => {}
};
}
Ok(results)
})
.transpose();
let named = named?;
Ok(EvaluatedArgs::new(positional, named))
}
| 26.352436 | 96 | 0.542242 |
7294ca1e1a36efb22ca0aaa87c105f9bfe5c5c8a | 1,669 | use crate::game::{Transition, WizardState};
use crate::ui::UI;
use ezgui::{EventCtx, ModalMenu, Wizard};
use geom::Duration;
pub fn time_controls(ctx: &mut EventCtx, ui: &mut UI, menu: &mut ModalMenu) -> Option<Transition> {
if menu.action("step forwards 0.1s") {
ui.primary.sim.step(&ui.primary.map, Duration::seconds(0.1));
if let Some(ref mut s) = ui.secondary {
s.sim.step(&s.map, Duration::seconds(0.1));
}
ui.recalculate_current_selection(ctx);
} else if menu.action("step forwards 10 mins") {
ctx.loading_screen("step forwards 10 minutes", |_, mut timer| {
ui.primary
.sim
.timed_step(&ui.primary.map, Duration::minutes(10), &mut timer);
if let Some(ref mut s) = ui.secondary {
s.sim.timed_step(&s.map, Duration::minutes(10), &mut timer);
}
});
ui.recalculate_current_selection(ctx);
} else if menu.action("jump to specific time") {
return Some(Transition::Push(WizardState::new(Box::new(jump_to_time))));
}
None
}
fn jump_to_time(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {
let t = wiz.wrap(ctx).input_time_slider(
"Jump to what time?",
ui.primary.sim.time(),
Duration::END_OF_DAY,
)?;
let dt = t - ui.primary.sim.time();
ctx.loading_screen(&format!("step forwards {}", dt), |_, mut timer| {
ui.primary.sim.timed_step(&ui.primary.map, dt, &mut timer);
if let Some(ref mut s) = ui.secondary {
s.sim.timed_step(&s.map, dt, &mut timer);
}
});
Some(Transition::Pop)
}
| 37.931818 | 99 | 0.591971 |
1424725fd01b47e845f9b429198869638459a33e | 49 | net.sf.jasperreports.data.DataAdapterServiceUtil
| 24.5 | 48 | 0.897959 |
e494bbb40b1575292569c14309644548ced898e6 | 7,489 | use super::{background::Background, Connection};
use crate::body::LiftBody;
use futures::{try_ready, Async, Future, Poll};
use http::Version;
use http_body::Body as HttpBody;
use http_connection::HttpConnection;
use hyper::client::conn::{Builder, Handshake};
use hyper::Error;
use std::fmt;
use std::marker::PhantomData;
use tokio_executor::{DefaultExecutor, TypedExecutor};
use tokio_io::{AsyncRead, AsyncWrite};
use tower_http_util::connection::HttpMakeConnection;
use tower_service::Service;
/// Creates a `hyper` connection
///
/// This accepts a `hyper::client::conn::Builder` and provides
/// a `MakeService` implementation to create connections from some
/// target `A`
#[derive(Debug)]
pub struct Connect<A, B, C, E> {
inner: C,
builder: Builder,
exec: E,
_pd: PhantomData<(A, B)>,
}
/// Executor that will spawn the background connection task.
pub trait ConnectExecutor<T, B>: TypedExecutor<Background<T, B>>
where
T: AsyncRead + AsyncWrite + Send + 'static,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
{
}
/// A future that resolves to the eventual connection or an error.
pub struct ConnectFuture<A, B, C, E>
where
B: HttpBody,
C: HttpMakeConnection<A>,
{
state: State<A, B, C>,
builder: Builder,
exec: E,
}
enum State<A, B, C>
where
B: HttpBody,
C: HttpMakeConnection<A>,
{
Connect(C::Future),
Handshake(Handshake<C::Connection, LiftBody<B>>),
}
/// The error produced from creating a connection
#[derive(Debug)]
pub enum ConnectError<T> {
/// An error occurred while attempting to establish the connection.
Connect(T),
/// An error occurred while performing hyper's handshake.
Handshake(Error),
/// An error occurred attempting to spawn the connect task on the
/// provided executor.
SpawnError,
}
// ==== impl ConnectExecutor ====
impl<E, T, B> ConnectExecutor<T, B> for E
where
T: AsyncRead + AsyncWrite + Send + 'static,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
E: TypedExecutor<Background<T, B>>,
{
}
// ===== impl Connect =====
impl<A, B, C> Connect<A, B, C, DefaultExecutor>
where
C: HttpMakeConnection<A>,
B: HttpBody,
C::Connection: Send + 'static,
{
/// Create a new `Connect`.
///
/// The `C` argument is used to obtain new session layer instances
/// (`AsyncRead` + `AsyncWrite`). For each new client service returned, a
/// Service is returned that can be driven by `poll_service` and to send
/// requests via `call`.
pub fn new(inner: C) -> Self {
Connect::with_builder(inner, Builder::new())
}
/// Create a new `Connect` with a builder.
pub fn with_builder(inner: C, builder: Builder) -> Self {
Connect::with_executor(inner, builder, DefaultExecutor::current())
}
}
impl<A, B, C, E> Connect<A, B, C, E>
where
C: HttpMakeConnection<A>,
B: HttpBody,
C::Connection: Send + 'static,
{
/// Create a new `Connect`.
///
/// The `C` argument is used to obtain new session layer instances
/// (`AsyncRead` + `AsyncWrite`). For each new client service returned, a
/// Service is returned that can be driven by `poll_service` and to send
/// requests via `call`.
///
/// The `E` argument is the executor that the background task for the connection
/// will be spawned on.
pub fn with_executor(inner: C, builder: Builder, exec: E) -> Self {
Connect {
inner,
builder,
exec,
_pd: PhantomData,
}
}
}
impl<A, B, C, E> Service<A> for Connect<A, B, C, E>
where
C: HttpMakeConnection<A> + 'static,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
C::Connection: Send + 'static,
E: ConnectExecutor<C::Connection, B> + Clone,
{
type Response = Connection<B>;
type Error = ConnectError<C::Error>;
type Future = ConnectFuture<A, B, C, E>;
/// Check if the `MakeConnection` is ready for a new connection.
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.inner.poll_ready().map_err(ConnectError::Connect)
}
/// Obtains a Connection on a single plaintext h2 connection to a remote.
fn call(&mut self, target: A) -> Self::Future {
let state = State::Connect(self.inner.make_connection(target));
let builder = self.builder.clone();
let exec = self.exec.clone();
ConnectFuture {
state,
builder,
exec,
}
}
}
// ===== impl ConnectFuture =====
impl<A, B, C, E> Future for ConnectFuture<A, B, C, E>
where
C: HttpMakeConnection<A>,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
C::Connection: Send + 'static,
E: ConnectExecutor<C::Connection, B>,
{
type Item = Connection<B>;
type Error = ConnectError<C::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
let io = match self.state {
State::Connect(ref mut fut) => {
let res = fut.poll().map_err(ConnectError::Connect);
try_ready!(res)
}
State::Handshake(ref mut fut) => {
let (sender, conn) = try_ready!(fut.poll().map_err(ConnectError::Handshake));
let (bg, handle) = Background::new(conn);
self.exec.spawn(bg).map_err(|_| ConnectError::SpawnError)?;
let connection = Connection::new(sender, handle);
return Ok(Async::Ready(connection));
}
};
let mut builder = self.builder.clone();
if let Some(Version::HTTP_2) = io.negotiated_version() {
builder.http2_only(true);
}
let handshake = builder.handshake(io);
self.state = State::Handshake(handshake);
}
}
}
impl<A, B, C, E> fmt::Debug for ConnectFuture<A, B, C, E>
where
C: HttpMakeConnection<A>,
B: HttpBody,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("ConnectFuture")
}
}
// ==== impl ConnectError ====
impl<T> fmt::Display for ConnectError<T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConnectError::Connect(ref why) => write!(
f,
"Error attempting to establish underlying session layer: {}",
why
),
ConnectError::Handshake(ref why) => {
write!(f, "Error while performing HTTP handshake: {}", why,)
}
ConnectError::SpawnError => write!(f, "Error spawning background task"),
}
}
}
impl<T> std::error::Error for ConnectError<T>
where
T: std::error::Error,
{
fn description(&self) -> &str {
match *self {
ConnectError::Connect(_) => "error attempting to establish underlying session layer",
ConnectError::Handshake(_) => "error performing HTTP handshake",
ConnectError::SpawnError => "Error spawning background task",
}
}
fn cause(&self) -> Option<&dyn std::error::Error> {
match *self {
ConnectError::Connect(ref why) => Some(why),
ConnectError::Handshake(ref why) => Some(why),
ConnectError::SpawnError => None,
}
}
}
| 28.693487 | 97 | 0.59327 |
d6bd736e139585070884fe6923519f6d1bdf9533 | 19,564 | use std::{
collections::HashMap,
convert::TryFrom,
fmt::{self, Display, Formatter},
io::{Cursor, Error},
};
use async_trait::async_trait;
use tokio::io::AsyncReadExt;
use super::buffer;
const DEFAULT_CAPACITY: usize = 64;
pub const SSL_REQUEST_PROTOCOL: u16 = 1234;
pub struct StartupMessage {
pub protocol_version: ProtocolVersion,
pub parameters: HashMap<String, String>,
}
impl StartupMessage {
pub async fn from(mut buffer: &mut Cursor<Vec<u8>>) -> Result<Self, Error> {
let major_protocol_version = buffer.read_u16().await?;
let minor_protocol_version = buffer.read_u16().await?;
let protocol_version = ProtocolVersion::new(major_protocol_version, minor_protocol_version);
let mut parameters = HashMap::new();
if major_protocol_version != SSL_REQUEST_PROTOCOL {
loop {
let name = buffer::read_string(&mut buffer).await?;
if name.is_empty() {
break;
}
let value = buffer::read_string(&mut buffer).await?;
parameters.insert(name, value);
}
}
Ok(Self {
protocol_version,
parameters,
})
}
}
pub struct ErrorResponse {
// https://www.postgresql.org/docs/14/protocol-error-fields.html
pub severity: ErrorSeverity,
pub code: ErrorCode,
pub message: String,
}
impl ErrorResponse {
pub fn new(severity: ErrorSeverity, code: ErrorCode, message: String) -> Self {
Self {
severity,
code,
message,
}
}
}
impl Serialize for ErrorResponse {
const CODE: u8 = b'E';
fn serialize(&self) -> Option<Vec<u8>> {
let mut buffer = Vec::with_capacity(DEFAULT_CAPACITY);
let severity = self.severity.to_string();
buffer.push(b'S');
buffer::write_string(&mut buffer, &severity);
buffer.push(b'V');
buffer::write_string(&mut buffer, &severity);
buffer.push(b'C');
buffer::write_string(&mut buffer, &self.code.to_string());
buffer.push(b'M');
buffer::write_string(&mut buffer, &self.message);
buffer.push(0);
Some(buffer)
}
}
pub struct SSLResponse {}
impl SSLResponse {
pub fn new() -> Self {
Self {}
}
}
impl Serialize for SSLResponse {
const CODE: u8 = b'N';
fn serialize(&self) -> Option<Vec<u8>> {
None
}
}
pub struct Authentication {
response: AuthenticationRequest,
}
impl Authentication {
pub fn new(response: AuthenticationRequest) -> Self {
Self { response }
}
}
impl Serialize for Authentication {
const CODE: u8 = b'R';
fn serialize(&self) -> Option<Vec<u8>> {
Some(self.response.to_bytes())
}
}
pub struct ReadyForQuery {
transaction_status: TransactionStatus,
}
impl ReadyForQuery {
pub fn new(transaction_status: TransactionStatus) -> Self {
Self { transaction_status }
}
}
impl Serialize for ReadyForQuery {
const CODE: u8 = b'Z';
fn serialize(&self) -> Option<Vec<u8>> {
Some(vec![self.transaction_status.to_byte()])
}
}
pub struct ParameterStatus {
name: String,
value: String,
}
impl ParameterStatus {
pub fn new(name: String, value: String) -> Self {
Self { name, value }
}
}
impl Serialize for ParameterStatus {
const CODE: u8 = b'S';
fn serialize(&self) -> Option<Vec<u8>> {
let mut buffer = Vec::with_capacity(DEFAULT_CAPACITY);
buffer::write_string(&mut buffer, &self.name);
buffer::write_string(&mut buffer, &self.value);
Some(buffer)
}
}
pub struct CommandComplete {
tag: CommandCompleteTag,
rows: u32,
}
impl CommandComplete {
pub fn new(tag: CommandCompleteTag, rows: u32) -> Self {
Self { tag, rows }
}
}
impl Serialize for CommandComplete {
const CODE: u8 = b'C';
fn serialize(&self) -> Option<Vec<u8>> {
let string = format!("{} {}", self.tag, self.rows);
let mut buffer = Vec::with_capacity(DEFAULT_CAPACITY);
buffer::write_string(&mut buffer, &string);
Some(buffer)
}
}
pub struct RowDescription {
fields: Vec<RowDescriptionField>,
}
impl RowDescription {
pub fn new(fields: Vec<RowDescriptionField>) -> Self {
Self { fields }
}
}
impl Serialize for RowDescription {
const CODE: u8 = b'T';
fn serialize(&self) -> Option<Vec<u8>> {
// FIXME!
let size = u16::try_from(self.fields.len()).unwrap();
let mut buffer = Vec::with_capacity(DEFAULT_CAPACITY);
buffer.extend_from_slice(&size.to_be_bytes());
for field in self.fields.iter() {
buffer::write_string(&mut buffer, &field.name);
buffer.extend_from_slice(&field.table_oid.to_be_bytes());
buffer.extend_from_slice(&field.attribute_number.to_be_bytes());
buffer.extend_from_slice(&field.data_type_oid.to_be_bytes());
buffer.extend_from_slice(&field.data_type_size.to_be_bytes());
buffer.extend_from_slice(&field.type_modifier.to_be_bytes());
buffer.extend_from_slice(&field.format_code.to_be_bytes());
}
Some(buffer)
}
}
pub struct RowDescriptionField {
name: String,
// TODO: REWORK!
table_oid: i32,
attribute_number: i16,
data_type_oid: i32,
data_type_size: i16,
type_modifier: i32,
format_code: i16,
}
impl RowDescriptionField {
pub fn new(name: String) -> Self {
Self {
name,
table_oid: 0,
attribute_number: 0,
data_type_oid: 25,
data_type_size: -1,
type_modifier: -1,
format_code: 0,
}
}
}
pub struct DataRow {
values: Vec<Option<String>>,
}
impl DataRow {
pub fn new(values: Vec<Option<String>>) -> Self {
Self { values }
}
}
impl Serialize for DataRow {
const CODE: u8 = b'D';
fn serialize(&self) -> Option<Vec<u8>> {
let mut buffer = Vec::with_capacity(DEFAULT_CAPACITY);
let size = u16::try_from(self.values.len()).unwrap();
buffer.extend_from_slice(&size.to_be_bytes());
for value in self.values.iter() {
match value {
None => buffer.extend_from_slice(&(-1_i32).to_be_bytes()),
Some(value) => {
let size = u32::try_from(value.len()).unwrap();
buffer.extend_from_slice(&size.to_be_bytes());
buffer.extend_from_slice(value.as_bytes());
}
};
}
Some(buffer)
}
}
#[derive(Debug, PartialEq)]
pub struct PasswordMessage {
pub password: String,
}
#[async_trait]
impl Deserialize for PasswordMessage {
async fn deserialize(mut buffer: Cursor<Vec<u8>>) -> Result<Self, Error>
where
Self: Sized,
{
Ok(Self {
password: buffer::read_string(&mut buffer).await?,
})
}
}
/// This command is used for prepared statement creation on the server side
#[derive(Debug, PartialEq)]
pub struct Parse {
/// The name of the prepared statement. Empty string is used for unamed statements
pub name: String,
/// SQL query with placeholders ($1)
pub query: String,
// Types for parameters
pub param_types: Vec<u32>,
}
#[async_trait]
impl Deserialize for Parse {
async fn deserialize(mut buffer: Cursor<Vec<u8>>) -> Result<Self, Error>
where
Self: Sized,
{
let name = buffer::read_string(&mut buffer).await?;
let query = buffer::read_string(&mut buffer).await?;
let total = buffer.read_i16().await?;
let mut param_types = Vec::with_capacity(total as usize);
for _ in 0..total {
param_types.push(buffer.read_u32().await?);
}
Ok(Self {
name,
query,
param_types,
})
}
}
/// This command is used for prepared statement creation on the server side
#[derive(Debug, PartialEq)]
pub struct Bind {
/// The name of the destination portal (an empty string selects the unnamed portal).
pub portal: String,
/// The name of the source prepared statement (an empty string selects the unnamed prepared statement).
pub statement: String,
/// Format for parameters
pub parameter_formats: Vec<Format>,
/// Raw values for parameters
pub parameter_values: Vec<Option<Vec<u8>>>,
/// Format for results
pub result_formats: Vec<Format>,
}
#[async_trait]
impl Deserialize for Bind {
async fn deserialize(mut buffer: Cursor<Vec<u8>>) -> Result<Self, Error>
where
Self: Sized,
{
let portal = buffer::read_string(&mut buffer).await?;
let statement = buffer::read_string(&mut buffer).await?;
let mut parameter_formats = Vec::new();
{
let total = buffer.read_i16().await?;
for _ in 0..total {
parameter_formats.push(buffer::read_format(&mut buffer).await?);
}
}
let mut parameter_values = Vec::new();
{
let total = buffer.read_i16().await?;
for _ in 0..total {
let len = buffer.read_i32().await?;
if len == -1 {
parameter_values.push(None);
} else {
let mut value = Vec::with_capacity(len as usize);
for _ in 0..len {
value.push(buffer.read_u8().await?);
}
parameter_values.push(Some(value));
}
}
}
let mut result_formats = Vec::new();
{
let total = buffer.read_i16().await?;
for _ in 0..total {
result_formats.push(buffer::read_format(&mut buffer).await?);
}
}
Ok(Self {
portal,
statement,
parameter_formats,
parameter_values,
result_formats: vec![],
})
}
}
#[derive(Debug, PartialEq)]
pub enum DescribeType {
Statement,
Portal,
}
#[derive(Debug, PartialEq)]
pub struct Describe {
pub typ: DescribeType,
pub name: String,
}
#[async_trait]
impl Deserialize for Describe {
async fn deserialize(mut buffer: Cursor<Vec<u8>>) -> Result<Self, Error>
where
Self: Sized,
{
let typ = match buffer.read_u8().await? {
b'S' => DescribeType::Statement,
b'P' => DescribeType::Portal,
t => {
return Err(Error::new(
std::io::ErrorKind::Other,
format!("Unknown describe code: {}", t),
));
}
};
let name = buffer::read_string(&mut buffer).await?;
Ok(Self { typ, name })
}
}
#[derive(Debug, PartialEq)]
pub struct Query {
pub query: String,
}
#[async_trait]
impl Deserialize for Query {
async fn deserialize(mut buffer: Cursor<Vec<u8>>) -> Result<Self, Error>
where
Self: Sized,
{
Ok(Self {
query: buffer::read_string(&mut buffer).await?,
})
}
}
#[derive(Debug, PartialEq)]
pub enum Format {
Text,
Binary,
}
#[derive(Debug, PartialEq)]
pub struct ProtocolVersion {
pub major: u16,
pub minor: u16,
}
impl ProtocolVersion {
pub fn new(major: u16, minor: u16) -> Self {
Self { major, minor }
}
}
#[derive(Debug, PartialEq)]
pub enum FrontendMessage {
PasswordMessage(PasswordMessage),
Query(Query),
Parse(Parse),
Bind(Bind),
Describe(Describe),
/// Close connection
Terminate,
/// Finish
Sync,
}
/// https://www.postgresql.org/docs/14/errcodes-appendix.html
pub enum ErrorCode {
// 0A — Feature Not Supported
FeatureNotSupported,
// 28 - Invalid Authorization Specification
InvalidAuthorizationSpecification,
InvalidPassword,
// XX - Internal Error
InternalError,
}
impl Display for ErrorCode {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let string = match self {
Self::FeatureNotSupported => "0A000",
Self::InvalidAuthorizationSpecification => "28000",
Self::InvalidPassword => "28P01",
Self::InternalError => "XX000",
};
write!(f, "{}", string)
}
}
pub enum ErrorSeverity {
// https://www.postgresql.org/docs/14/protocol-error-fields.html
Error,
Fatal,
// Panic,
}
impl Display for ErrorSeverity {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let string = match self {
Self::Error => "ERROR",
Self::Fatal => "FATAL",
// Self::Panic => "PANIC",
};
write!(f, "{}", string)
}
}
pub enum TransactionStatus {
Idle,
// InTransactionBlock,
// InFailedTransactionBlock,
}
impl TransactionStatus {
pub fn to_byte(&self) -> u8 {
match self {
Self::Idle => b'I',
// Self::InTransactionBlock => b'T',
// Self::InFailedTransactionBlock => b'E',
}
}
}
pub enum CommandCompleteTag {
Select,
}
impl Display for CommandCompleteTag {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let string = match self {
Self::Select => "SELECT",
};
write!(f, "{}", string)
}
}
pub enum AuthenticationRequest {
Ok,
CleartextPassword,
}
impl AuthenticationRequest {
pub fn to_bytes(&self) -> Vec<u8> {
self.to_code().to_be_bytes().to_vec()
}
pub fn to_code(&self) -> u32 {
match self {
Self::Ok => 0,
Self::CleartextPassword => 3,
}
}
}
pub trait Serialize {
const CODE: u8;
fn serialize(&self) -> Option<Vec<u8>>;
fn code(&self) -> u8 {
Self::CODE
}
}
#[async_trait]
pub trait Deserialize {
async fn deserialize(mut buffer: Cursor<Vec<u8>>) -> Result<Self, Error>
where
Self: Sized;
}
#[cfg(test)]
mod tests {
use crate::{sql::postgres::buffer::read_message, CubeError};
use std::io::Cursor;
use super::*;
fn parse_hex_dump(input: String) -> Vec<u8> {
let mut result: Vec<Vec<u8>> = vec![];
for line in input.trim().split("\n") {
let splitted = line.trim().split(" ").collect::<Vec<&str>>();
let row = splitted.first().unwrap().to_string().replace(" ", "");
let tmp = hex::decode(row).unwrap();
result.push(tmp);
}
result.concat()
}
#[tokio::test]
async fn test_frontend_message_parse_parse() -> Result<(), CubeError> {
let buffer = parse_hex_dump(
r#"
50 00 00 00 77 6e 61 6d 65 64 2d 73 74 6d 74 00 P...wnamed-stmt.
0a 20 20 20 20 20 20 53 45 4c 45 43 54 20 6e 75 . SELECT nu
6d 2c 20 73 74 72 2c 20 62 6f 6f 6c 0a 20 20 20 m, str, bool.
20 20 20 46 52 4f 4d 20 74 65 73 74 64 61 74 61 FROM testdata
0a 20 20 20 20 20 20 57 48 45 52 45 20 6e 75 6d . WHERE num
20 3d 20 24 31 20 41 4e 44 20 73 74 72 20 3d 20 = $1 AND str =
24 32 20 41 4e 44 20 62 6f 6f 6c 20 3d 20 24 33 $2 AND bool = $3
0a 20 20 20 20 00 00 00 . ...
"#
.to_string(),
);
let mut cursor = Cursor::new(buffer);
let message = read_message(&mut cursor).await?;
match message {
FrontendMessage::Parse(parse) => {
assert_eq!(
parse,
Parse {
name: "named-stmt".to_string(),
query: "\n SELECT num, str, bool\n FROM testdata\n WHERE num = $1 AND str = $2 AND bool = $3\n ".to_string(),
param_types: vec![],
},
)
}
_ => panic!("Wrong message, must be Parse"),
}
Ok(())
}
#[tokio::test]
async fn test_frontend_message_parse_bind() -> Result<(), CubeError> {
let buffer = parse_hex_dump(
r#"
42 00 00 00 2d 00 6e 61 6d 65 64 2d 73 74 6d 74 B...-.named-stmt
00 00 00 00 03 00 00 00 01 35 00 00 00 04 74 65 .........5....te
73 74 00 00 00 04 74 72 75 65 00 01 00 00 st....true....
"#
.to_string(),
);
let mut cursor = Cursor::new(buffer);
let message = read_message(&mut cursor).await?;
match message {
FrontendMessage::Bind(bind) => {
assert_eq!(
bind,
Bind {
portal: "".to_string(),
statement: "named-stmt".to_string(),
parameter_formats: vec![],
parameter_values: vec![
Some(vec![53]),
Some(vec![116, 101, 115, 116]),
Some(vec![116, 114, 117, 101]),
],
result_formats: vec![]
},
)
}
_ => panic!("Wrong message, must be Bind"),
}
Ok(())
}
#[tokio::test]
async fn test_frontend_message_parse_describe() -> Result<(), CubeError> {
let buffer = parse_hex_dump(
r#"
44 00 00 00 08 53 73 30 00 D....Ss0.
"#
.to_string(),
);
let mut cursor = Cursor::new(buffer);
let message = read_message(&mut cursor).await?;
match message {
FrontendMessage::Describe(desc) => {
assert_eq!(
desc,
Describe {
typ: DescribeType::Statement,
name: "s0".to_string(),
},
)
}
_ => panic!("Wrong message, must be Describe"),
}
Ok(())
}
#[tokio::test]
async fn test_frontend_message_parse_password_message() -> Result<(), CubeError> {
let buffer = parse_hex_dump(
r#"
70 00 00 00 09 74 65 73 74 00 p....test.
"#
.to_string(),
);
let mut cursor = Cursor::new(buffer);
let message = read_message(&mut cursor).await?;
match message {
FrontendMessage::PasswordMessage(body) => {
assert_eq!(
body,
PasswordMessage {
password: "test".to_string()
},
)
}
_ => panic!("Wrong message, must be Describe"),
}
Ok(())
}
#[tokio::test]
async fn test_frontend_message_parse_sequence_sync() -> Result<(), CubeError> {
let buffer = parse_hex_dump(
r#"
53 00 00 00 04 S....
53 00 00 00 04 S....
"#
.to_string(),
);
let mut cursor = Cursor::new(buffer);
// This test demonstrates that protocol can decode two
// simple messages without body in sequence
read_message(&mut cursor).await?;
read_message(&mut cursor).await?;
Ok(())
}
}
| 26.33109 | 151 | 0.53716 |
4a8ea64ba2aa7cd56cabc29370a9e22b75814d94 | 72,553 | #![allow(bad_style)]
#![allow(dead_code)]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage, Align>
where
Storage: AsRef<[u8]> + AsMut<[u8]>,
{
storage: Storage,
align: [Align; 0],
}
impl<Storage, Align> __BindgenBitfieldUnit<Storage, Align>
where
Storage: AsRef<[u8]> + AsMut<[u8]>,
{
#[inline]
pub fn new(storage: Storage) -> Self {
Self { storage, align: [] }
}
#[inline]
pub fn get_bit(&self, index: usize) -> bool {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = self.storage.as_ref()[byte_index];
let bit_index = index % 8;
let mask = 1 << bit_index;
byte & mask == mask
}
#[inline]
pub fn set_bit(&mut self, index: usize, val: bool) {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = &mut self.storage.as_mut()[byte_index];
let bit_index = index % 8;
let mask = 1 << bit_index;
if val {
*byte |= mask;
} else {
*byte &= !mask;
}
}
#[inline]
pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len());
let mut val = 0;
for i in 0..(bit_width as usize) {
if self.get_bit(i + bit_offset) {
val |= 1 << i;
}
}
val
}
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len());
for i in 0..(bit_width as usize) {
let mask = 1 << i;
let val_bit_is_set = val & mask == mask;
self.set_bit(i + bit_offset, val_bit_is_set);
}
}
}
pub type wchar_t = ::std::os::raw::c_ushort;
pub type ULONG = ::std::os::raw::c_ulong;
pub type PULONG = *mut ULONG;
pub type USHORT = ::std::os::raw::c_ushort;
pub type DWORD = ::std::os::raw::c_ulong;
pub type BYTE = ::std::os::raw::c_uchar;
pub type INT = ::std::os::raw::c_int;
pub type UINT8 = ::std::os::raw::c_uchar;
pub type UINT32 = ::std::os::raw::c_uint;
pub type ULONG64 = ::std::os::raw::c_ulonglong;
pub type PVOID = *mut ::std::os::raw::c_void;
pub type CHAR = ::std::os::raw::c_char;
pub type WCHAR = wchar_t;
pub type PWCHAR = *mut WCHAR;
pub type PCHAR = *mut CHAR;
pub type ULONGLONG = ::std::os::raw::c_ulonglong;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _GUID {
pub Data1: ::std::os::raw::c_ulong,
pub Data2: ::std::os::raw::c_ushort,
pub Data3: ::std::os::raw::c_ushort,
pub Data4: [::std::os::raw::c_uchar; 8usize],
}
#[test]
fn bindgen_test_layout__GUID() {
assert_eq!(
::std::mem::size_of::<_GUID>(),
16usize,
concat!("Size of: ", stringify!(_GUID))
);
assert_eq!(
::std::mem::align_of::<_GUID>(),
4usize,
concat!("Alignment of ", stringify!(_GUID))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_GUID>())).Data1 as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_GUID),
"::",
stringify!(Data1)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_GUID>())).Data2 as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(_GUID),
"::",
stringify!(Data2)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_GUID>())).Data3 as *const _ as usize },
6usize,
concat!(
"Offset of field: ",
stringify!(_GUID),
"::",
stringify!(Data3)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_GUID>())).Data4 as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_GUID),
"::",
stringify!(Data4)
)
);
}
pub type GUID = _GUID;
pub type ADDRESS_FAMILY = USHORT;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct sockaddr {
pub sa_family: ADDRESS_FAMILY,
pub sa_data: [CHAR; 14usize],
}
#[test]
fn bindgen_test_layout_sockaddr() {
assert_eq!(
::std::mem::size_of::<sockaddr>(),
16usize,
concat!("Size of: ", stringify!(sockaddr))
);
assert_eq!(
::std::mem::align_of::<sockaddr>(),
2usize,
concat!("Alignment of ", stringify!(sockaddr))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<sockaddr>())).sa_family as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(sockaddr),
"::",
stringify!(sa_family)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<sockaddr>())).sa_data as *const _ as usize },
2usize,
concat!(
"Offset of field: ",
stringify!(sockaddr),
"::",
stringify!(sa_data)
)
);
}
pub type LPSOCKADDR = *mut sockaddr;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _SOCKET_ADDRESS {
pub lpSockaddr: LPSOCKADDR,
pub iSockaddrLength: INT,
}
#[test]
fn bindgen_test_layout__SOCKET_ADDRESS() {
assert_eq!(
::std::mem::size_of::<_SOCKET_ADDRESS>(),
16usize,
concat!("Size of: ", stringify!(_SOCKET_ADDRESS))
);
assert_eq!(
::std::mem::align_of::<_SOCKET_ADDRESS>(),
8usize,
concat!("Alignment of ", stringify!(_SOCKET_ADDRESS))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_SOCKET_ADDRESS>())).lpSockaddr as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_SOCKET_ADDRESS),
"::",
stringify!(lpSockaddr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_SOCKET_ADDRESS>())).iSockaddrLength as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_SOCKET_ADDRESS),
"::",
stringify!(iSockaddrLength)
)
);
}
pub type SOCKET_ADDRESS = _SOCKET_ADDRESS;
pub type IFTYPE = ULONG;
pub type NET_IF_COMPARTMENT_ID = UINT32;
pub type NET_IF_NETWORK_GUID = GUID;
#[repr(C)]
#[derive(Copy, Clone)]
pub union _NET_LUID_LH {
pub Value: ULONG64,
pub Info: _NET_LUID_LH__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _NET_LUID_LH__bindgen_ty_1 {
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize], u32>,
pub __bindgen_align: [u64; 0usize],
}
#[test]
fn bindgen_test_layout__NET_LUID_LH__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_NET_LUID_LH__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(_NET_LUID_LH__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<_NET_LUID_LH__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(_NET_LUID_LH__bindgen_ty_1))
);
}
impl _NET_LUID_LH__bindgen_ty_1 {
#[inline]
pub fn Reserved(&self) -> ULONG64 {
unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 24u8) as u64) }
}
#[inline]
pub fn set_Reserved(&mut self, val: ULONG64) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(0usize, 24u8, val as u64)
}
}
#[inline]
pub fn NetLuidIndex(&self) -> ULONG64 {
unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 24u8) as u64) }
}
#[inline]
pub fn set_NetLuidIndex(&mut self, val: ULONG64) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(24usize, 24u8, val as u64)
}
}
#[inline]
pub fn IfType(&self) -> ULONG64 {
unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u64) }
}
#[inline]
pub fn set_IfType(&mut self, val: ULONG64) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(48usize, 16u8, val as u64)
}
}
#[inline]
pub fn new_bitfield_1(
Reserved: ULONG64,
NetLuidIndex: ULONG64,
IfType: ULONG64,
) -> __BindgenBitfieldUnit<[u8; 8usize], u32> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize], u32> =
Default::default();
__bindgen_bitfield_unit.set(0usize, 24u8, {
let Reserved: u64 = unsafe { ::std::mem::transmute(Reserved) };
Reserved as u64
});
__bindgen_bitfield_unit.set(24usize, 24u8, {
let NetLuidIndex: u64 = unsafe { ::std::mem::transmute(NetLuidIndex) };
NetLuidIndex as u64
});
__bindgen_bitfield_unit.set(48usize, 16u8, {
let IfType: u64 = unsafe { ::std::mem::transmute(IfType) };
IfType as u64
});
__bindgen_bitfield_unit
}
}
#[test]
fn bindgen_test_layout__NET_LUID_LH() {
assert_eq!(
::std::mem::size_of::<_NET_LUID_LH>(),
8usize,
concat!("Size of: ", stringify!(_NET_LUID_LH))
);
assert_eq!(
::std::mem::align_of::<_NET_LUID_LH>(),
8usize,
concat!("Alignment of ", stringify!(_NET_LUID_LH))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_NET_LUID_LH>())).Value as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_NET_LUID_LH),
"::",
stringify!(Value)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_NET_LUID_LH>())).Info as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_NET_LUID_LH),
"::",
stringify!(Info)
)
);
}
pub type NET_LUID_LH = _NET_LUID_LH;
pub type NET_LUID = NET_LUID_LH;
pub type IF_LUID = NET_LUID;
pub type NET_IFINDEX = ULONG;
pub type IF_INDEX = NET_IFINDEX;
pub const _NET_IF_CONNECTION_TYPE_NET_IF_CONNECTION_DEDICATED: _NET_IF_CONNECTION_TYPE = 1;
pub const _NET_IF_CONNECTION_TYPE_NET_IF_CONNECTION_PASSIVE: _NET_IF_CONNECTION_TYPE = 2;
pub const _NET_IF_CONNECTION_TYPE_NET_IF_CONNECTION_DEMAND: _NET_IF_CONNECTION_TYPE = 3;
pub const _NET_IF_CONNECTION_TYPE_NET_IF_CONNECTION_MAXIMUM: _NET_IF_CONNECTION_TYPE = 4;
pub type _NET_IF_CONNECTION_TYPE = i32;
pub use self::_NET_IF_CONNECTION_TYPE as NET_IF_CONNECTION_TYPE;
pub const TUNNEL_TYPE_TUNNEL_TYPE_NONE: TUNNEL_TYPE = 0;
pub const TUNNEL_TYPE_TUNNEL_TYPE_OTHER: TUNNEL_TYPE = 1;
pub const TUNNEL_TYPE_TUNNEL_TYPE_DIRECT: TUNNEL_TYPE = 2;
pub const TUNNEL_TYPE_TUNNEL_TYPE_6TO4: TUNNEL_TYPE = 11;
pub const TUNNEL_TYPE_TUNNEL_TYPE_ISATAP: TUNNEL_TYPE = 13;
pub const TUNNEL_TYPE_TUNNEL_TYPE_TEREDO: TUNNEL_TYPE = 14;
pub const TUNNEL_TYPE_TUNNEL_TYPE_IPHTTPS: TUNNEL_TYPE = 15;
pub type TUNNEL_TYPE = i32;
pub const IF_OPER_STATUS_IfOperStatusUp: IF_OPER_STATUS = 1;
pub const IF_OPER_STATUS_IfOperStatusDown: IF_OPER_STATUS = 2;
pub const IF_OPER_STATUS_IfOperStatusTesting: IF_OPER_STATUS = 3;
pub const IF_OPER_STATUS_IfOperStatusUnknown: IF_OPER_STATUS = 4;
pub const IF_OPER_STATUS_IfOperStatusDormant: IF_OPER_STATUS = 5;
pub const IF_OPER_STATUS_IfOperStatusNotPresent: IF_OPER_STATUS = 6;
pub const IF_OPER_STATUS_IfOperStatusLowerLayerDown: IF_OPER_STATUS = 7;
pub type IF_OPER_STATUS = i32;
pub const NL_PREFIX_ORIGIN_IpPrefixOriginOther: NL_PREFIX_ORIGIN = 0;
pub const NL_PREFIX_ORIGIN_IpPrefixOriginManual: NL_PREFIX_ORIGIN = 1;
pub const NL_PREFIX_ORIGIN_IpPrefixOriginWellKnown: NL_PREFIX_ORIGIN = 2;
pub const NL_PREFIX_ORIGIN_IpPrefixOriginDhcp: NL_PREFIX_ORIGIN = 3;
pub const NL_PREFIX_ORIGIN_IpPrefixOriginRouterAdvertisement: NL_PREFIX_ORIGIN = 4;
pub const NL_PREFIX_ORIGIN_IpPrefixOriginUnchanged: NL_PREFIX_ORIGIN = 16;
pub type NL_PREFIX_ORIGIN = i32;
pub const NL_SUFFIX_ORIGIN_NlsoOther: NL_SUFFIX_ORIGIN = 0;
pub const NL_SUFFIX_ORIGIN_NlsoManual: NL_SUFFIX_ORIGIN = 1;
pub const NL_SUFFIX_ORIGIN_NlsoWellKnown: NL_SUFFIX_ORIGIN = 2;
pub const NL_SUFFIX_ORIGIN_NlsoDhcp: NL_SUFFIX_ORIGIN = 3;
pub const NL_SUFFIX_ORIGIN_NlsoLinkLayerAddress: NL_SUFFIX_ORIGIN = 4;
pub const NL_SUFFIX_ORIGIN_NlsoRandom: NL_SUFFIX_ORIGIN = 5;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginOther: NL_SUFFIX_ORIGIN = 0;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginManual: NL_SUFFIX_ORIGIN = 1;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginWellKnown: NL_SUFFIX_ORIGIN = 2;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginDhcp: NL_SUFFIX_ORIGIN = 3;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginLinkLayerAddress: NL_SUFFIX_ORIGIN = 4;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginRandom: NL_SUFFIX_ORIGIN = 5;
pub const NL_SUFFIX_ORIGIN_IpSuffixOriginUnchanged: NL_SUFFIX_ORIGIN = 16;
pub type NL_SUFFIX_ORIGIN = i32;
pub const NL_DAD_STATE_NldsInvalid: NL_DAD_STATE = 0;
pub const NL_DAD_STATE_NldsTentative: NL_DAD_STATE = 1;
pub const NL_DAD_STATE_NldsDuplicate: NL_DAD_STATE = 2;
pub const NL_DAD_STATE_NldsDeprecated: NL_DAD_STATE = 3;
pub const NL_DAD_STATE_NldsPreferred: NL_DAD_STATE = 4;
pub const NL_DAD_STATE_IpDadStateInvalid: NL_DAD_STATE = 0;
pub const NL_DAD_STATE_IpDadStateTentative: NL_DAD_STATE = 1;
pub const NL_DAD_STATE_IpDadStateDuplicate: NL_DAD_STATE = 2;
pub const NL_DAD_STATE_IpDadStateDeprecated: NL_DAD_STATE = 3;
pub const NL_DAD_STATE_IpDadStatePreferred: NL_DAD_STATE = 4;
pub type NL_DAD_STATE = i32;
pub use self::NL_PREFIX_ORIGIN as IP_PREFIX_ORIGIN;
pub use self::NL_SUFFIX_ORIGIN as IP_SUFFIX_ORIGIN;
pub use self::NL_DAD_STATE as IP_DAD_STATE;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_UNICAST_ADDRESS_LH {
pub __bindgen_anon_1: _IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_UNICAST_ADDRESS_LH,
pub Address: SOCKET_ADDRESS,
pub PrefixOrigin: IP_PREFIX_ORIGIN,
pub SuffixOrigin: IP_SUFFIX_ORIGIN,
pub DadState: IP_DAD_STATE,
pub ValidLifetime: ULONG,
pub PreferredLifetime: ULONG,
pub LeaseLifetime: ULONG,
pub OnLinkPrefixLength: UINT8,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Flags: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>()))
.Length as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>()))
.Flags as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Flags)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1>())).Alignment
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_UNICAST_ADDRESS_LH() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_UNICAST_ADDRESS_LH>(),
64usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_UNICAST_ADDRESS_LH>(),
8usize,
concat!("Alignment of ", stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).Next as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).Address as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(Address)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).PrefixOrigin as *const _
as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(PrefixOrigin)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).SuffixOrigin as *const _
as usize
},
36usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(SuffixOrigin)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).DadState as *const _ as usize
},
40usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(DadState)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).ValidLifetime as *const _
as usize
},
44usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(ValidLifetime)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).PreferredLifetime as *const _
as usize
},
48usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(PreferredLifetime)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).LeaseLifetime as *const _
as usize
},
52usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(LeaseLifetime)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_UNICAST_ADDRESS_LH>())).OnLinkPrefixLength
as *const _ as usize
},
56usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_UNICAST_ADDRESS_LH),
"::",
stringify!(OnLinkPrefixLength)
)
);
}
pub type PIP_ADAPTER_UNICAST_ADDRESS_LH = *mut _IP_ADAPTER_UNICAST_ADDRESS_LH;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_ANYCAST_ADDRESS_XP {
pub __bindgen_anon_1: _IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_ANYCAST_ADDRESS_XP,
pub Address: SOCKET_ADDRESS,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Flags: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>()))
.Length as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>()))
.Flags as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Flags)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1>())).Alignment
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ANYCAST_ADDRESS_XP() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ANYCAST_ADDRESS_XP>(),
32usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ANYCAST_ADDRESS_XP>(),
8usize,
concat!("Alignment of ", stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ANYCAST_ADDRESS_XP>())).Next as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ANYCAST_ADDRESS_XP>())).Address as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ANYCAST_ADDRESS_XP),
"::",
stringify!(Address)
)
);
}
pub type PIP_ADAPTER_ANYCAST_ADDRESS_XP = *mut _IP_ADAPTER_ANYCAST_ADDRESS_XP;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_MULTICAST_ADDRESS_XP {
pub __bindgen_anon_1: _IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_MULTICAST_ADDRESS_XP,
pub Address: SOCKET_ADDRESS,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Flags: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>()))
.Length as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>()))
.Flags as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Flags)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1>())).Alignment
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_MULTICAST_ADDRESS_XP() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_MULTICAST_ADDRESS_XP>(),
32usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_MULTICAST_ADDRESS_XP>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_MULTICAST_ADDRESS_XP>())).Next as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_MULTICAST_ADDRESS_XP>())).Address as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_MULTICAST_ADDRESS_XP),
"::",
stringify!(Address)
)
);
}
pub type PIP_ADAPTER_MULTICAST_ADDRESS_XP = *mut _IP_ADAPTER_MULTICAST_ADDRESS_XP;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_DNS_SERVER_ADDRESS_XP {
pub __bindgen_anon_1: _IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_DNS_SERVER_ADDRESS_XP,
pub Address: SOCKET_ADDRESS,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Reserved: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(
))).Length as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1>(
))).Reserved as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Reserved)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1>())).Alignment
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_DNS_SERVER_ADDRESS_XP() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP>(),
32usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP>())).Next as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_DNS_SERVER_ADDRESS_XP>())).Address as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SERVER_ADDRESS_XP),
"::",
stringify!(Address)
)
);
}
pub type PIP_ADAPTER_DNS_SERVER_ADDRESS_XP = *mut _IP_ADAPTER_DNS_SERVER_ADDRESS_XP;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_WINS_SERVER_ADDRESS_LH {
pub __bindgen_anon_1: _IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_WINS_SERVER_ADDRESS_LH,
pub Address: SOCKET_ADDRESS,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Reserved: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(
))).Length as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(
))).Reserved as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Reserved)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1>())).Alignment
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_WINS_SERVER_ADDRESS_LH() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH>(),
32usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH>())).Next as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_WINS_SERVER_ADDRESS_LH>())).Address as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_WINS_SERVER_ADDRESS_LH),
"::",
stringify!(Address)
)
);
}
pub type PIP_ADAPTER_WINS_SERVER_ADDRESS_LH = *mut _IP_ADAPTER_WINS_SERVER_ADDRESS_LH;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_GATEWAY_ADDRESS_LH {
pub __bindgen_anon_1: _IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_GATEWAY_ADDRESS_LH,
pub Address: SOCKET_ADDRESS,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Reserved: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>()))
.Length as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1>()))
.Reserved as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Reserved)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1>())).Alignment
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_GATEWAY_ADDRESS_LH() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_GATEWAY_ADDRESS_LH>(),
32usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_GATEWAY_ADDRESS_LH>(),
8usize,
concat!("Alignment of ", stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_GATEWAY_ADDRESS_LH>())).Next as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_GATEWAY_ADDRESS_LH>())).Address as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_GATEWAY_ADDRESS_LH),
"::",
stringify!(Address)
)
);
}
pub type PIP_ADAPTER_GATEWAY_ADDRESS_LH = *mut _IP_ADAPTER_GATEWAY_ADDRESS_LH;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_PREFIX_XP {
pub __bindgen_anon_1: _IP_ADAPTER_PREFIX_XP__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_PREFIX_XP,
pub Address: SOCKET_ADDRESS,
pub PrefixLength: ULONG,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_PREFIX_XP__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub Flags: DWORD,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1>())).Length
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1>())).Flags
as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Flags)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_PREFIX_XP__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_PREFIX_XP__bindgen_ty_1>())).Alignment as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_PREFIX_XP__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_PREFIX_XP() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_PREFIX_XP>(),
40usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_PREFIX_XP))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_PREFIX_XP>(),
8usize,
concat!("Alignment of ", stringify!(_IP_ADAPTER_PREFIX_XP))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_PREFIX_XP>())).Next as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_PREFIX_XP),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_PREFIX_XP>())).Address as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_PREFIX_XP),
"::",
stringify!(Address)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_PREFIX_XP>())).PrefixLength as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_PREFIX_XP),
"::",
stringify!(PrefixLength)
)
);
}
pub type PIP_ADAPTER_PREFIX_XP = *mut _IP_ADAPTER_PREFIX_XP;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_DNS_SUFFIX {
pub Next: *mut _IP_ADAPTER_DNS_SUFFIX,
pub String: [WCHAR; 256usize],
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_DNS_SUFFIX() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_DNS_SUFFIX>(),
520usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_DNS_SUFFIX))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_DNS_SUFFIX>(),
8usize,
concat!("Alignment of ", stringify!(_IP_ADAPTER_DNS_SUFFIX))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_DNS_SUFFIX>())).Next as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SUFFIX),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_DNS_SUFFIX>())).String as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_DNS_SUFFIX),
"::",
stringify!(String)
)
);
}
pub type PIP_ADAPTER_DNS_SUFFIX = *mut _IP_ADAPTER_DNS_SUFFIX;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _IP_ADAPTER_ADDRESSES_LH {
pub __bindgen_anon_1: _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1,
pub Next: *mut _IP_ADAPTER_ADDRESSES_LH,
pub AdapterName: PCHAR,
pub FirstUnicastAddress: PIP_ADAPTER_UNICAST_ADDRESS_LH,
pub FirstAnycastAddress: PIP_ADAPTER_ANYCAST_ADDRESS_XP,
pub FirstMulticastAddress: PIP_ADAPTER_MULTICAST_ADDRESS_XP,
pub FirstDnsServerAddress: PIP_ADAPTER_DNS_SERVER_ADDRESS_XP,
pub DnsSuffix: PWCHAR,
pub Description: PWCHAR,
pub FriendlyName: PWCHAR,
pub PhysicalAddress: [BYTE; 8usize],
pub PhysicalAddressLength: ULONG,
pub __bindgen_anon_2: _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2,
pub Mtu: ULONG,
pub IfType: IFTYPE,
pub OperStatus: IF_OPER_STATUS,
pub Ipv6IfIndex: IF_INDEX,
pub ZoneIndices: [ULONG; 16usize],
pub FirstPrefix: PIP_ADAPTER_PREFIX_XP,
pub TransmitLinkSpeed: ULONG64,
pub ReceiveLinkSpeed: ULONG64,
pub FirstWinsServerAddress: PIP_ADAPTER_WINS_SERVER_ADDRESS_LH,
pub FirstGatewayAddress: PIP_ADAPTER_GATEWAY_ADDRESS_LH,
pub Ipv4Metric: ULONG,
pub Ipv6Metric: ULONG,
pub Luid: IF_LUID,
pub Dhcpv4Server: SOCKET_ADDRESS,
pub CompartmentId: NET_IF_COMPARTMENT_ID,
pub NetworkGuid: NET_IF_NETWORK_GUID,
pub ConnectionType: NET_IF_CONNECTION_TYPE,
pub TunnelType: TUNNEL_TYPE,
pub Dhcpv6Server: SOCKET_ADDRESS,
pub Dhcpv6ClientDuid: [BYTE; 130usize],
pub Dhcpv6ClientDuidLength: ULONG,
pub Dhcpv6Iaid: ULONG,
pub FirstDnsSuffix: PIP_ADAPTER_DNS_SUFFIX,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1 {
pub Alignment: ULONGLONG,
pub __bindgen_anon_1: _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1 {
pub Length: ULONG,
pub IfIndex: IF_INDEX,
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1>())).Length
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(Length)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1>())).IfIndex
as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(IfIndex)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1>())).Alignment as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_1),
"::",
stringify!(Alignment)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2 {
pub Flags: ULONG,
pub __bindgen_anon_1: _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1,
_bindgen_union_align: u32,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1 {
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize], u8>,
pub __bindgen_padding_0: u16,
pub __bindgen_align: [u32; 0usize],
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1>(),
4usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1)
)
);
}
impl _IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2__bindgen_ty_1 {
#[inline]
pub fn DdnsEnabled(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) }
}
#[inline]
pub fn set_DdnsEnabled(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(0usize, 1u8, val as u64)
}
}
#[inline]
pub fn RegisterAdapterSuffix(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) }
}
#[inline]
pub fn set_RegisterAdapterSuffix(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(1usize, 1u8, val as u64)
}
}
#[inline]
pub fn Dhcpv4Enabled(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) }
}
#[inline]
pub fn set_Dhcpv4Enabled(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(2usize, 1u8, val as u64)
}
}
#[inline]
pub fn ReceiveOnly(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) }
}
#[inline]
pub fn set_ReceiveOnly(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(3usize, 1u8, val as u64)
}
}
#[inline]
pub fn NoMulticast(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) }
}
#[inline]
pub fn set_NoMulticast(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(4usize, 1u8, val as u64)
}
}
#[inline]
pub fn Ipv6OtherStatefulConfig(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) }
}
#[inline]
pub fn set_Ipv6OtherStatefulConfig(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(5usize, 1u8, val as u64)
}
}
#[inline]
pub fn NetbiosOverTcpipEnabled(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) }
}
#[inline]
pub fn set_NetbiosOverTcpipEnabled(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(6usize, 1u8, val as u64)
}
}
#[inline]
pub fn Ipv4Enabled(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) }
}
#[inline]
pub fn set_Ipv4Enabled(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(7usize, 1u8, val as u64)
}
}
#[inline]
pub fn Ipv6Enabled(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) }
}
#[inline]
pub fn set_Ipv6Enabled(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(8usize, 1u8, val as u64)
}
}
#[inline]
pub fn Ipv6ManagedAddressConfigurationSupported(&self) -> ULONG {
unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) }
}
#[inline]
pub fn set_Ipv6ManagedAddressConfigurationSupported(&mut self, val: ULONG) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(9usize, 1u8, val as u64)
}
}
#[inline]
pub fn new_bitfield_1(
DdnsEnabled: ULONG,
RegisterAdapterSuffix: ULONG,
Dhcpv4Enabled: ULONG,
ReceiveOnly: ULONG,
NoMulticast: ULONG,
Ipv6OtherStatefulConfig: ULONG,
NetbiosOverTcpipEnabled: ULONG,
Ipv4Enabled: ULONG,
Ipv6Enabled: ULONG,
Ipv6ManagedAddressConfigurationSupported: ULONG,
) -> __BindgenBitfieldUnit<[u8; 2usize], u8> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize], u8> =
Default::default();
__bindgen_bitfield_unit.set(0usize, 1u8, {
let DdnsEnabled: u32 = unsafe { ::std::mem::transmute(DdnsEnabled) };
DdnsEnabled as u64
});
__bindgen_bitfield_unit.set(1usize, 1u8, {
let RegisterAdapterSuffix: u32 =
unsafe { ::std::mem::transmute(RegisterAdapterSuffix) };
RegisterAdapterSuffix as u64
});
__bindgen_bitfield_unit.set(2usize, 1u8, {
let Dhcpv4Enabled: u32 = unsafe { ::std::mem::transmute(Dhcpv4Enabled) };
Dhcpv4Enabled as u64
});
__bindgen_bitfield_unit.set(3usize, 1u8, {
let ReceiveOnly: u32 = unsafe { ::std::mem::transmute(ReceiveOnly) };
ReceiveOnly as u64
});
__bindgen_bitfield_unit.set(4usize, 1u8, {
let NoMulticast: u32 = unsafe { ::std::mem::transmute(NoMulticast) };
NoMulticast as u64
});
__bindgen_bitfield_unit.set(5usize, 1u8, {
let Ipv6OtherStatefulConfig: u32 =
unsafe { ::std::mem::transmute(Ipv6OtherStatefulConfig) };
Ipv6OtherStatefulConfig as u64
});
__bindgen_bitfield_unit.set(6usize, 1u8, {
let NetbiosOverTcpipEnabled: u32 =
unsafe { ::std::mem::transmute(NetbiosOverTcpipEnabled) };
NetbiosOverTcpipEnabled as u64
});
__bindgen_bitfield_unit.set(7usize, 1u8, {
let Ipv4Enabled: u32 = unsafe { ::std::mem::transmute(Ipv4Enabled) };
Ipv4Enabled as u64
});
__bindgen_bitfield_unit.set(8usize, 1u8, {
let Ipv6Enabled: u32 = unsafe { ::std::mem::transmute(Ipv6Enabled) };
Ipv6Enabled as u64
});
__bindgen_bitfield_unit.set(9usize, 1u8, {
let Ipv6ManagedAddressConfigurationSupported: u32 =
unsafe { ::std::mem::transmute(Ipv6ManagedAddressConfigurationSupported) };
Ipv6ManagedAddressConfigurationSupported as u64
});
__bindgen_bitfield_unit
}
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2>(),
4usize,
concat!(
"Size of: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2)
)
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2>(),
4usize,
concat!(
"Alignment of ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2>())).Flags as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH__bindgen_ty_2),
"::",
stringify!(Flags)
)
);
}
#[test]
fn bindgen_test_layout__IP_ADAPTER_ADDRESSES_LH() {
assert_eq!(
::std::mem::size_of::<_IP_ADAPTER_ADDRESSES_LH>(),
448usize,
concat!("Size of: ", stringify!(_IP_ADAPTER_ADDRESSES_LH))
);
assert_eq!(
::std::mem::align_of::<_IP_ADAPTER_ADDRESSES_LH>(),
8usize,
concat!("Alignment of ", stringify!(_IP_ADAPTER_ADDRESSES_LH))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Next as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).AdapterName as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(AdapterName)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstUnicastAddress as *const _
as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstUnicastAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstAnycastAddress as *const _
as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstAnycastAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstMulticastAddress as *const _
as usize
},
40usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstMulticastAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstDnsServerAddress as *const _
as usize
},
48usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstDnsServerAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).DnsSuffix as *const _ as usize
},
56usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(DnsSuffix)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Description as *const _ as usize
},
64usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Description)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FriendlyName as *const _ as usize
},
72usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FriendlyName)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).PhysicalAddress as *const _
as usize
},
80usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(PhysicalAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).PhysicalAddressLength as *const _
as usize
},
88usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(PhysicalAddressLength)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Mtu as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Mtu)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).IfType as *const _ as usize },
100usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(IfType)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).OperStatus as *const _ as usize
},
104usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(OperStatus)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Ipv6IfIndex as *const _ as usize
},
108usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Ipv6IfIndex)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).ZoneIndices as *const _ as usize
},
112usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(ZoneIndices)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstPrefix as *const _ as usize
},
176usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstPrefix)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).TransmitLinkSpeed as *const _
as usize
},
184usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(TransmitLinkSpeed)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).ReceiveLinkSpeed as *const _
as usize
},
192usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(ReceiveLinkSpeed)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstWinsServerAddress as *const _
as usize
},
200usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstWinsServerAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstGatewayAddress as *const _
as usize
},
208usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstGatewayAddress)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Ipv4Metric as *const _ as usize
},
216usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Ipv4Metric)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Ipv6Metric as *const _ as usize
},
220usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Ipv6Metric)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Luid as *const _ as usize },
224usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Luid)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Dhcpv4Server as *const _ as usize
},
232usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Dhcpv4Server)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).CompartmentId as *const _ as usize
},
248usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(CompartmentId)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).NetworkGuid as *const _ as usize
},
252usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(NetworkGuid)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).ConnectionType as *const _ as usize
},
268usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(ConnectionType)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).TunnelType as *const _ as usize
},
272usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(TunnelType)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Dhcpv6Server as *const _ as usize
},
280usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Dhcpv6Server)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Dhcpv6ClientDuid as *const _
as usize
},
296usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Dhcpv6ClientDuid)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Dhcpv6ClientDuidLength as *const _
as usize
},
428usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Dhcpv6ClientDuidLength)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).Dhcpv6Iaid as *const _ as usize
},
432usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(Dhcpv6Iaid)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_IP_ADAPTER_ADDRESSES_LH>())).FirstDnsSuffix as *const _ as usize
},
440usize,
concat!(
"Offset of field: ",
stringify!(_IP_ADAPTER_ADDRESSES_LH),
"::",
stringify!(FirstDnsSuffix)
)
);
}
pub type IP_ADAPTER_ADDRESSES_LH = _IP_ADAPTER_ADDRESSES_LH;
pub type PIP_ADAPTER_ADDRESSES = *mut IP_ADAPTER_ADDRESSES_LH;
extern "C" {
pub fn GetAdaptersAddresses(
Family: ULONG,
Flags: ULONG,
Reserved: PVOID,
AdapterAddresses: PIP_ADAPTER_ADDRESSES,
SizePointer: PULONG,
) -> ULONG;
}
| 31.178771 | 100 | 0.584387 |
481eab563c6d0d0be0f1264758cc36b04260b8e5 | 829 | //! Tests auto-converted from "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/04_variable_double.hrx"
#[allow(unused)]
fn runner() -> crate::TestRunner {
super::runner()
}
#[test]
fn test() {
assert_eq!(
runner().ok("$input: gamma, \"\'\"delta\"\'\";\
\n.result {\
\n output: #{#{$input}};\
\n output: #{\"[#{$input}]\"};\
\n output: #{\"#{$input}\"};\
\n output: #{\'#{$input}\'};\
\n output: #{\"[\'#{$input}\']\"};\
\n}\n"),
".result {\
\n output: gamma, \' delta \';\
\n output: [gamma, \' delta \'];\
\n output: gamma, \' delta \';\
\n output: gamma, \' delta \';\
\n output: [\'gamma, \' delta \'\'];\
\n}\n"
);
}
| 29.607143 | 125 | 0.429433 |
1a4358e5ccd80df60bc9a31e3aaa0cde7f4e52c8 | 2,600 | use crate::encoding::*;
use crate::storage::bigquery_storage::*;
use crate::storage::git_storage::*;
use crate::storage::hive_table_storage::*;
use crate::storage::inline_blob_storage::*;
use crate::storage::local_file_storage::*;
use crate::storage::postgres_storage::*;
use crate::storage::remote_storage::*;
use crate::storage::s3_storage::*;
use crate::storage::sqlite_storage::*;
use abi_stable::std_types::ROption;
use aorist_concept::{aorist, Constrainable};
use aorist_paste::paste;
use aorist_primitives::AOption;
use aorist_primitives::AUuid;
use aorist_primitives::AoristRef;
use aorist_primitives::{AString, AVec, AoristConcept, AoristConceptBase, ConceptEnum};
#[cfg(feature = "python")]
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
#[aorist]
pub enum Storage {
#[constrainable]
RemoteStorage(AoristRef<RemoteStorage>),
#[constrainable]
GitStorage(AoristRef<GitStorage>),
#[constrainable]
HiveTableStorage(AoristRef<HiveTableStorage>),
#[constrainable]
LocalFileStorage(AoristRef<LocalFileStorage>),
#[constrainable]
SQLiteStorage(AoristRef<SQLiteStorage>),
#[constrainable]
PostgresStorage(AoristRef<PostgresStorage>),
#[constrainable]
BigQueryStorage(AoristRef<BigQueryStorage>),
#[constrainable]
InlineBlobStorage(AoristRef<InlineBlobStorage>),
#[constrainable]
S3Storage(AoristRef<S3Storage>),
}
impl Storage {
pub fn get_encoding(&self) -> AOption<AoristRef<Encoding>> {
match &self {
Self::RemoteStorage(x) => AOption(ROption::RSome(x.0.read().encoding.clone())),
Self::HiveTableStorage(x) => AOption(ROption::RSome(x.0.read().encoding.clone())),
Self::LocalFileStorage(x) => AOption(ROption::RSome(x.0.read().encoding.clone())),
Self::GitStorage(x) => AOption(ROption::RSome(x.0.read().encoding.clone())),
Self::InlineBlobStorage(x) => AOption(ROption::RSome(x.0.read().encoding.clone())),
Self::S3Storage(x) => AOption(ROption::RSome(x.0.read().encoding.clone())),
Self::SQLiteStorage(_) => AOption(ROption::RNone),
Self::PostgresStorage(_) => AOption(ROption::RNone),
Self::BigQueryStorage(_) => AOption(ROption::RNone),
}
}
}
#[cfg(feature = "python")]
#[pymethods]
impl PyStorage {
#[getter]
pub fn encoding(&self) -> Option<PyEncoding> {
match self.inner.0.read().get_encoding() {
AOption(ROption::RSome(x)) => Some(PyEncoding { inner: x }),
AOption(ROption::RNone) => None,
}
}
}
| 36.111111 | 95 | 0.674231 |
db30796bf017fc4d4329e39e601e9ea35fe6c9d7 | 2,352 | #[doc = "Register `CODESIZE` reader"]
pub struct R(crate::R<CODESIZE_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CODESIZE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CODESIZE_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CODESIZE_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Code memory size in number of pages\n\nValue on reset: 256"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum CODESIZE_A {
#[doc = "256: 256 pages"]
P256 = 256,
}
impl From<CODESIZE_A> for u32 {
#[inline(always)]
fn from(variant: CODESIZE_A) -> Self {
variant as _
}
}
#[doc = "Field `CODESIZE` reader - Code memory size in number of pages"]
pub struct CODESIZE_R(crate::FieldReader<u32, CODESIZE_A>);
impl CODESIZE_R {
pub(crate) fn new(bits: u32) -> Self {
CODESIZE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<CODESIZE_A> {
match self.bits {
256 => Some(CODESIZE_A::P256),
_ => None,
}
}
#[doc = "Checks if the value of the field is `P256`"]
#[inline(always)]
pub fn is_p256(&self) -> bool {
**self == CODESIZE_A::P256
}
}
impl core::ops::Deref for CODESIZE_R {
type Target = crate::FieldReader<u32, CODESIZE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:31 - Code memory size in number of pages"]
#[inline(always)]
pub fn codesize(&self) -> CODESIZE_R {
CODESIZE_R::new((self.bits & 0xffff_ffff) as u32)
}
}
#[doc = "Code memory size\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [codesize](index.html) module"]
pub struct CODESIZE_SPEC;
impl crate::RegisterSpec for CODESIZE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [codesize::R](R) reader structure"]
impl crate::Readable for CODESIZE_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets CODESIZE to value 0x0100"]
impl crate::Resettable for CODESIZE_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x0100
}
}
| 29.772152 | 227 | 0.616071 |
3889da81954be065f5116eccf26a64eb78b520b4 | 1,040 | use std::thread;
use std::time::Duration;
use futures::executor::block_on;
async fn wash_your_face(){
thread::sleep(Duration::from_secs(2));
println!("Wash Your Face 3 times");
}
async fn hands_with_elbow(){
thread::sleep(Duration::from_secs(2));
println!("Wash Your Hands Including Elbow 3 Times");
}
async fn wipe_your_head(){
thread::sleep(Duration::from_secs(2));
println!("Wipe Your Head's Forth Part Once")
}
async fn wash_your_feet(){
thread::sleep(Duration::from_secs(2));
println!("Wash Your Feet Including Ankle 3 Times");
}
async fn duties_of_ablution (){
let thread_one = wash_your_face();
let thread_two = hands_with_elbow();
let thread_three =wipe_your_head();
let thread_four =wash_your_feet();
futures::join!(thread_one,thread_two,thread_three,thread_four);
}
fn main() {
println!("Duties of Ablution ");
block_on(duties_of_ablution());
} | 18.909091 | 67 | 0.617308 |
28ecbf49fb9dedd50b9e2fb3542b6b1cf55975e4 | 2,865 | use crate::priv_prelude::*;
use future_utils;
mod latency;
mod packet_loss;
pub use self::latency::*;
pub use self::packet_loss::*;
#[derive(Debug)]
/// Bidirectional network plug that can be used to exchange data between two devices.
/// Anything written to the plub will be readable on the other side.
pub struct Plug<T: fmt::Debug + 'static> {
/// The sender
pub tx: UnboundedSender<T>,
/// The receiver.
pub rx: UnboundedReceiver<T>,
}
impl<T: fmt::Debug + Send + 'static> Plug<T> {
/// Create a new connection connecting the two returned plugs.
pub fn new_pair() -> (Plug<T>, Plug<T>) {
let (a_tx, b_rx) = future_utils::mpsc::unbounded();
let (b_tx, a_rx) = future_utils::mpsc::unbounded();
let a = Plug {
tx: a_tx,
rx: a_rx,
};
let b = Plug {
tx: b_tx,
rx: b_rx,
};
(a, b)
}
/// Add latency to the end of this connection.
///
/// `min_latency` is the baseline for the amount of delay added to a packet travelling on this
/// connection. `mean_additional_latency` controls the amount of extra, random latency added to
/// any given packet on this connection. A non-zero `mean_additional_latency` can cause packets
/// to be re-ordered.
pub fn with_latency(
self,
handle: &NetworkHandle,
min_latency: Duration,
mean_additional_latency: Duration,
) -> Plug<T> {
let (plug_0, plug_1) = Plug::new_pair();
Latency::spawn(handle, min_latency, mean_additional_latency, self, plug_0);
plug_1
}
/// Add packet loss to the connection. Loss happens in burst, rather than on an individual
/// packet basis. `mean_loss_duration` controls the burstiness of the loss.
pub fn with_packet_loss(
self,
handle: &NetworkHandle,
loss_rate: f64,
mean_loss_duration: Duration,
) -> Plug<T> {
let (plug_0, plug_1) = Plug::new_pair();
PacketLoss::spawn(handle, loss_rate, mean_loss_duration, self, plug_0);
plug_1
}
/// Returns sender and receiver handles used to interact with the other side of the plug.
pub fn split(self) -> (UnboundedSender<T>, UnboundedReceiver<T>) {
(self.tx, self.rx)
}
}
impl<T: fmt::Debug + 'static> Stream for Plug<T> {
type Item = T;
type Error = Void;
fn poll(&mut self) -> Result<Async<Option<T>>, Void> {
self.rx.poll()
}
}
impl<T: fmt::Debug + 'static> Sink for Plug<T> {
type SinkItem = T;
type SinkError = Void;
fn start_send(&mut self, item: T) -> Result<AsyncSink<T>, Void> {
Ok(self.tx.start_send(item).unwrap_or(AsyncSink::Ready))
}
fn poll_complete(&mut self) -> Result<Async<()>, Void> {
Ok(self.tx.poll_complete().unwrap_or(Async::Ready(())))
}
}
| 30.478723 | 99 | 0.61466 |
1de544b90721995960a529fe017b208879dddb92 | 712 | use text_grid::*;
fn main() {}
// fn f_error() {
// let s = String::from("ABC");
// let _cell_a = cell!("{}", &s); // `s` moved into `_cell_a` here
// let _cell_b = cell!("{}", &s); // ERROR : `s` used here after move
// }
pub fn f_ok() {
let s = String::from("ABC");
let s = &s;
let _cell_a = cell!("{}", s);
let _cell_b = cell!("{}", s); // OK
}
pub fn f_write() {
use std::fmt::Write;
let s = String::from("ABC");
let _cell_a = cell_by(|w| write!(w, "{}", &s));
let _cell_b = cell_by(|w| write!(w, "{}", &s));
}
pub fn f_format() {
let s = String::from("ABC");
let _cell_a = cell(format!("--{}--", &s));
let _cell_b = cell(format!("--{}--", &s));
}
| 24.551724 | 73 | 0.485955 |
e9501700784931c25ac97277fafa0b825ceac596 | 4,343 | use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::higher;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_hir::intravisit::{self as visit, Visitor};
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for `Mutex::lock` calls in `if let` expression
/// with lock calls in any of the else blocks.
///
/// ### Why is this bad?
/// The Mutex lock remains held for the whole
/// `if let ... else` block and deadlocks.
///
/// ### Example
/// ```rust,ignore
/// if let Ok(thing) = mutex.lock() {
/// do_thing();
/// } else {
/// mutex.lock();
/// }
/// ```
/// Should be written
/// ```rust,ignore
/// let locked = mutex.lock();
/// if let Ok(thing) = locked {
/// do_thing(thing);
/// } else {
/// use_locked(locked);
/// }
/// ```
#[clippy::version = "1.45.0"]
pub IF_LET_MUTEX,
correctness,
"locking a `Mutex` in an `if let` block can cause deadlocks"
}
declare_lint_pass!(IfLetMutex => [IF_LET_MUTEX]);
impl<'tcx> LateLintPass<'tcx> for IfLetMutex {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
let mut arm_visit = ArmVisitor {
mutex_lock_called: false,
found_mutex: None,
cx,
};
let mut op_visit = OppVisitor {
mutex_lock_called: false,
found_mutex: None,
cx,
};
if let Some(higher::IfLet {
let_expr,
if_then,
if_else: Some(if_else),
..
}) = higher::IfLet::hir(cx, expr)
{
op_visit.visit_expr(let_expr);
if op_visit.mutex_lock_called {
arm_visit.visit_expr(if_then);
arm_visit.visit_expr(if_else);
if arm_visit.mutex_lock_called && arm_visit.same_mutex(cx, op_visit.found_mutex.unwrap()) {
span_lint_and_help(
cx,
IF_LET_MUTEX,
expr.span,
"calling `Mutex::lock` inside the scope of another `Mutex::lock` causes a deadlock",
None,
"move the lock call outside of the `if let ...` expression",
);
}
}
}
}
}
/// Checks if `Mutex::lock` is called in the `if let` expr.
pub struct OppVisitor<'a, 'tcx> {
mutex_lock_called: bool,
found_mutex: Option<&'tcx Expr<'tcx>>,
cx: &'a LateContext<'tcx>,
}
impl<'tcx> Visitor<'tcx> for OppVisitor<'_, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
if let Some(mutex) = is_mutex_lock_call(self.cx, expr) {
self.found_mutex = Some(mutex);
self.mutex_lock_called = true;
return;
}
visit::walk_expr(self, expr);
}
}
/// Checks if `Mutex::lock` is called in any of the branches.
pub struct ArmVisitor<'a, 'tcx> {
mutex_lock_called: bool,
found_mutex: Option<&'tcx Expr<'tcx>>,
cx: &'a LateContext<'tcx>,
}
impl<'tcx> Visitor<'tcx> for ArmVisitor<'_, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
if let Some(mutex) = is_mutex_lock_call(self.cx, expr) {
self.found_mutex = Some(mutex);
self.mutex_lock_called = true;
return;
}
visit::walk_expr(self, expr);
}
}
impl<'tcx, 'l> ArmVisitor<'tcx, 'l> {
fn same_mutex(&self, cx: &LateContext<'_>, op_mutex: &Expr<'_>) -> bool {
self.found_mutex
.map_or(false, |arm_mutex| SpanlessEq::new(cx).eq_expr(op_mutex, arm_mutex))
}
}
fn is_mutex_lock_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
if_chain! {
if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind;
if path.ident.as_str() == "lock";
let ty = cx.typeck_results().expr_ty(self_arg);
if is_type_diagnostic_item(cx, ty, sym::Mutex);
then {
Some(self_arg)
} else {
None
}
}
}
| 30.801418 | 108 | 0.54985 |
48cf0c57e60fcbe0e42dfd8ae8e16886ce884d9b | 4,138 | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::fs::File;
use std::io::{stderr, Read};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::panic::{self, PanicInfo};
use std::process::abort;
use std::string::String;
use libc::{close, dup, dup2, pipe2, O_NONBLOCK, STDERR_FILENO};
use sys_util::error;
// Opens a pipe and puts the write end into the stderr FD slot. On success, returns the read end of
// the pipe and the old stderr as a pair of files.
fn redirect_stderr() -> Option<(File, File)> {
let mut fds = [-1, -1];
unsafe {
// Trivially safe because the return value is checked.
let old_stderr = dup(STDERR_FILENO);
if old_stderr == -1 {
return None;
}
// Safe because pipe2 will only ever write two integers to our array and we check output.
let mut ret = pipe2(fds.as_mut_ptr(), O_NONBLOCK);
if ret != 0 {
// Leaks FDs, but not important right before abort.
return None;
}
// Safe because the FD we are duplicating is owned by us.
ret = dup2(fds[1], STDERR_FILENO);
if ret == -1 {
// Leaks FDs, but not important right before abort.
return None;
}
// The write end is no longer needed.
close(fds[1]);
// Safe because each of the fds was the result of a successful FD creation syscall.
Some((File::from_raw_fd(fds[0]), File::from_raw_fd(old_stderr)))
}
}
// Sets stderr to the given file. Returns true on success.
fn restore_stderr(stderr: File) -> bool {
let fd = stderr.into_raw_fd();
// Safe because fd is guaranteed to be valid and replacing stderr should be an atomic operation.
unsafe { dup2(fd, STDERR_FILENO) != -1 }
}
// Sends as much information about the panic as possible to syslog.
fn log_panic_info(default_panic: &(dyn Fn(&PanicInfo) + Sync + Send + 'static), info: &PanicInfo) {
// Grab a lock of stderr to prevent concurrent threads from trampling on our stderr capturing
// procedure. The default_panic procedure likely uses stderr.lock as well, but the mutex inside
// stderr is reentrant, so it will not dead-lock on this thread.
let stderr = stderr();
let _stderr_lock = stderr.lock();
// Redirect stderr to a pipe we can read from later.
let (mut read_file, old_stderr) = match redirect_stderr() {
Some(f) => f,
None => {
error!("failed to capture stderr during panic");
return;
}
};
// Only through the default panic handler can we get a stacktrace. It only ever prints to
// stderr, hence all the previous code to redirect it to a pipe we can read.
env::set_var("RUST_BACKTRACE", "1");
default_panic(info);
// Closes the write end of the pipe so that we can reach EOF in read_to_string. Also allows
// others to write to stderr without failure.
if !restore_stderr(old_stderr) {
error!("failed to restore stderr during panic");
return;
}
drop(_stderr_lock);
let mut panic_output = String::new();
// Ignore errors and print what we got.
let _ = read_file.read_to_string(&mut panic_output);
// Split by line because the logging facilities do not handle embedded new lines well.
for line in panic_output.lines() {
error!("{}", line);
}
}
/// The intent of our panic hook is to get panic info and a stacktrace into the syslog, even for
/// jailed subprocesses. It will always abort on panic to ensure a minidump is generated.
///
/// Note that jailed processes will usually have a stacktrace of <unknown> because the backtrace
/// routines attempt to open this binary and are unable to do so in a jail.
pub fn set_panic_hook() {
let default_panic = panic::take_hook();
panic::set_hook(Box::new(move |info| {
log_panic_info(default_panic.as_ref(), info);
// Abort to trigger the crash reporter so that a minidump is generated.
abort();
}));
}
| 39.788462 | 100 | 0.657322 |
0e0851a3a1085744495ad694071d9e41ac1976fd | 13,403 | #[doc = "Register `i2c_config` reader"]
pub struct R(crate::R<I2C_CONFIG_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<I2C_CONFIG_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<I2C_CONFIG_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<I2C_CONFIG_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `i2c_config` writer"]
pub struct W(crate::W<I2C_CONFIG_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<I2C_CONFIG_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<I2C_CONFIG_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<I2C_CONFIG_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `cr_i2c_deg_cnt` reader - "]
pub struct CR_I2C_DEG_CNT_R(crate::FieldReader<u8, u8>);
impl CR_I2C_DEG_CNT_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
CR_I2C_DEG_CNT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_DEG_CNT_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_deg_cnt` writer - "]
pub struct CR_I2C_DEG_CNT_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_DEG_CNT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 28)) | ((value as u32 & 0x0f) << 28);
self.w
}
}
#[doc = "Field `cr_i2c_pkt_len` reader - "]
pub struct CR_I2C_PKT_LEN_R(crate::FieldReader<u8, u8>);
impl CR_I2C_PKT_LEN_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
CR_I2C_PKT_LEN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_PKT_LEN_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_pkt_len` writer - "]
pub struct CR_I2C_PKT_LEN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_PKT_LEN_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 16)) | ((value as u32 & 0xff) << 16);
self.w
}
}
#[doc = "Field `cr_i2c_slv_addr` reader - "]
pub struct CR_I2C_SLV_ADDR_R(crate::FieldReader<u8, u8>);
impl CR_I2C_SLV_ADDR_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
CR_I2C_SLV_ADDR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_SLV_ADDR_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_slv_addr` writer - "]
pub struct CR_I2C_SLV_ADDR_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_SLV_ADDR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 8)) | ((value as u32 & 0x7f) << 8);
self.w
}
}
#[doc = "Field `cr_i2c_sub_addr_bc` reader - "]
pub struct CR_I2C_SUB_ADDR_BC_R(crate::FieldReader<u8, u8>);
impl CR_I2C_SUB_ADDR_BC_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
CR_I2C_SUB_ADDR_BC_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_SUB_ADDR_BC_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_sub_addr_bc` writer - "]
pub struct CR_I2C_SUB_ADDR_BC_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_SUB_ADDR_BC_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 5)) | ((value as u32 & 0x03) << 5);
self.w
}
}
#[doc = "Field `cr_i2c_sub_addr_en` reader - "]
pub struct CR_I2C_SUB_ADDR_EN_R(crate::FieldReader<bool, bool>);
impl CR_I2C_SUB_ADDR_EN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CR_I2C_SUB_ADDR_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_SUB_ADDR_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_sub_addr_en` writer - "]
pub struct CR_I2C_SUB_ADDR_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_SUB_ADDR_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Field `cr_i2c_scl_sync_en` reader - "]
pub struct CR_I2C_SCL_SYNC_EN_R(crate::FieldReader<bool, bool>);
impl CR_I2C_SCL_SYNC_EN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CR_I2C_SCL_SYNC_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_SCL_SYNC_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_scl_sync_en` writer - "]
pub struct CR_I2C_SCL_SYNC_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_SCL_SYNC_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Field `cr_i2c_deg_en` reader - "]
pub struct CR_I2C_DEG_EN_R(crate::FieldReader<bool, bool>);
impl CR_I2C_DEG_EN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CR_I2C_DEG_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_DEG_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_deg_en` writer - "]
pub struct CR_I2C_DEG_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_DEG_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2);
self.w
}
}
#[doc = "Field `cr_i2c_pkt_dir` reader - "]
pub struct CR_I2C_PKT_DIR_R(crate::FieldReader<bool, bool>);
impl CR_I2C_PKT_DIR_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CR_I2C_PKT_DIR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_PKT_DIR_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_pkt_dir` writer - "]
pub struct CR_I2C_PKT_DIR_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_PKT_DIR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Field `cr_i2c_m_en` reader - "]
pub struct CR_I2C_M_EN_R(crate::FieldReader<bool, bool>);
impl CR_I2C_M_EN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CR_I2C_M_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR_I2C_M_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `cr_i2c_m_en` writer - "]
pub struct CR_I2C_M_EN_W<'a> {
w: &'a mut W,
}
impl<'a> CR_I2C_M_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bits 28:31"]
#[inline(always)]
pub fn cr_i2c_deg_cnt(&self) -> CR_I2C_DEG_CNT_R {
CR_I2C_DEG_CNT_R::new(((self.bits >> 28) & 0x0f) as u8)
}
#[doc = "Bits 16:23"]
#[inline(always)]
pub fn cr_i2c_pkt_len(&self) -> CR_I2C_PKT_LEN_R {
CR_I2C_PKT_LEN_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 8:14"]
#[inline(always)]
pub fn cr_i2c_slv_addr(&self) -> CR_I2C_SLV_ADDR_R {
CR_I2C_SLV_ADDR_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bits 5:6"]
#[inline(always)]
pub fn cr_i2c_sub_addr_bc(&self) -> CR_I2C_SUB_ADDR_BC_R {
CR_I2C_SUB_ADDR_BC_R::new(((self.bits >> 5) & 0x03) as u8)
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn cr_i2c_sub_addr_en(&self) -> CR_I2C_SUB_ADDR_EN_R {
CR_I2C_SUB_ADDR_EN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn cr_i2c_scl_sync_en(&self) -> CR_I2C_SCL_SYNC_EN_R {
CR_I2C_SCL_SYNC_EN_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn cr_i2c_deg_en(&self) -> CR_I2C_DEG_EN_R {
CR_I2C_DEG_EN_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn cr_i2c_pkt_dir(&self) -> CR_I2C_PKT_DIR_R {
CR_I2C_PKT_DIR_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn cr_i2c_m_en(&self) -> CR_I2C_M_EN_R {
CR_I2C_M_EN_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 28:31"]
#[inline(always)]
pub fn cr_i2c_deg_cnt(&mut self) -> CR_I2C_DEG_CNT_W {
CR_I2C_DEG_CNT_W { w: self }
}
#[doc = "Bits 16:23"]
#[inline(always)]
pub fn cr_i2c_pkt_len(&mut self) -> CR_I2C_PKT_LEN_W {
CR_I2C_PKT_LEN_W { w: self }
}
#[doc = "Bits 8:14"]
#[inline(always)]
pub fn cr_i2c_slv_addr(&mut self) -> CR_I2C_SLV_ADDR_W {
CR_I2C_SLV_ADDR_W { w: self }
}
#[doc = "Bits 5:6"]
#[inline(always)]
pub fn cr_i2c_sub_addr_bc(&mut self) -> CR_I2C_SUB_ADDR_BC_W {
CR_I2C_SUB_ADDR_BC_W { w: self }
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn cr_i2c_sub_addr_en(&mut self) -> CR_I2C_SUB_ADDR_EN_W {
CR_I2C_SUB_ADDR_EN_W { w: self }
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn cr_i2c_scl_sync_en(&mut self) -> CR_I2C_SCL_SYNC_EN_W {
CR_I2C_SCL_SYNC_EN_W { w: self }
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn cr_i2c_deg_en(&mut self) -> CR_I2C_DEG_EN_W {
CR_I2C_DEG_EN_W { w: self }
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn cr_i2c_pkt_dir(&mut self) -> CR_I2C_PKT_DIR_W {
CR_I2C_PKT_DIR_W { w: self }
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn cr_i2c_m_en(&mut self) -> CR_I2C_M_EN_W {
CR_I2C_M_EN_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "i2c_config.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_config](index.html) module"]
pub struct I2C_CONFIG_SPEC;
impl crate::RegisterSpec for I2C_CONFIG_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [i2c_config::R](R) reader structure"]
impl crate::Readable for I2C_CONFIG_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [i2c_config::W](W) writer structure"]
impl crate::Writable for I2C_CONFIG_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets i2c_config to value 0"]
impl crate::Resettable for I2C_CONFIG_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.784444 | 402 | 0.58845 |
e2e203c5aa6b6292ed02408c20b30a6bd419112a | 3,094 | extern crate libc;
extern crate nix;
use nix::sys::ptrace::{ptrace, ptrace_setoptions};
use nix::sys::wait::waitpid;
use nix::sys::wait::WaitStatus;
use std::env;
use std::io::Write;
use std::io;
use std::mem;
use std::ptr;
const CMD_NAME: &'static str = "procout";
fn main() {
std::process::exit(match run() {
Ok(_) => 0,
Err(err) => {
eprintln!("{}: {}", CMD_NAME, err);
1
}
});
}
fn run() -> Result<(), String> {
match env::args().nth(1).and_then(|x| x.parse().ok()) {
Some(pid) => procout(nix::unistd::Pid::from_raw(pid)),
None => Err(String::from("specify pid")),
}
}
fn procout(pid: nix::unistd::Pid) -> Result<(), String> {
ptrace(ptrace::PTRACE_ATTACH, pid, ptr::null_mut(), ptr::null_mut()).map_err(|e| format!("failed to ptrace attach {} ({})", pid, e))?;
ptrace_setoptions(pid, ptrace::PTRACE_O_TRACESYSGOOD).map_err(|e| format!("failed to ptrace setoptions {} ({})", pid, e))?;
let mut regs: libc::user_regs_struct = unsafe { mem::zeroed() };
let regs_ptr: *mut libc::user_regs_struct = &mut regs;
let mut is_enter_stop: bool = false;
let mut prev_orig_rax: u64 = 0;
loop {
match waitpid(pid, None) {
Err(_) | Ok(WaitStatus::Exited(_, _)) => break,
Ok(WaitStatus::PtraceSyscall(_)) => {
ptrace(ptrace::PTRACE_GETREGS, pid, ptr::null_mut(), regs_ptr as *mut libc::c_void)
.map_err(|e| format!("failed to ptrace getregs {} ({})", pid, e))?;
is_enter_stop = if prev_orig_rax == regs.orig_rax { !is_enter_stop } else { true };
prev_orig_rax = regs.orig_rax;
if regs.orig_rax == libc::SYS_write as u64 && is_enter_stop {
output(peek_bytes(pid, regs.rsi, regs.rdx), regs.rdi)?;
}
}
_ => {}
}
ptrace(ptrace::PTRACE_SYSCALL, pid, ptr::null_mut(), ptr::null_mut()).map_err(|e| format!("failed to ptrace syscall {} ({})", pid, e))?;
}
Ok(())
}
fn peek_bytes(pid: nix::unistd::Pid, addr: u64, size: u64) -> Vec<u8> {
let mut vec = (0..(size + 7) / 8)
.filter_map(|i| {
ptrace(
ptrace::PTRACE_PEEKDATA,
pid,
(addr + 8 * i) as *mut libc::c_void,
ptr::null_mut(),
).map(|l| unsafe { mem::transmute(l) })
.ok()
})
.collect::<Vec<[u8; 8]>>()
.concat();
vec.truncate(size as usize);
vec
}
fn output(bs: Vec<u8>, fd: u64) -> Result<(), String> {
match fd {
1 => {
io::stdout().write_all(bs.as_slice()).map_err(|_| "failed to write to stdout")?;
io::stdout().flush().map_err(|_| "failed to flush stdout")?;
}
2 => {
io::stderr().write_all(bs.as_slice()).map_err(|_| "failed to write to stderr")?;
io::stderr().flush().map_err(|_| "failed to flush stderr")?;
}
_ => {
// sometimes want to print for debug?
}
}
Ok(())
}
| 34 | 144 | 0.523917 |
03726724e3a92f98a4e45c5a986eeba8fa6383b8 | 2,908 | extern crate hmac;
extern crate jwt;
extern crate sha2;
use hmac::{Hmac, NewMac};
use jwt::{Header, Token, VerifyWithKey};
use jwt::SignWithKey;
use sha2::Sha256;
use std::collections::BTreeMap;
/// Holds parameters that were encoded in the JSON web token.
///
/// # Attributes
/// * user_id (i32): the ID of a user
pub struct JwtToken {
pub user_id: i32,
pub body: String
}
impl JwtToken {
/// Creates a JSON web token.
///
/// # Arguments
/// * user_id (i32): ID of the user to be encoded into the token.
///
/// # Returns
/// (String): The token with all arguments encoded into it
pub fn encode(user_id: i32) -> String {
let key: Hmac<Sha256> = Hmac::new_varkey(b"secret").unwrap();
let mut claims = BTreeMap::new();
claims.insert("user_id", user_id);
let token_str: String = claims.sign_with_key(&key).unwrap();
return token_str
}
/// Extracts the user ID from the encoded JSON web token.
///
/// # Arguments
/// * encoded_token (String): The JSON web token to be decoded.
///
/// # Returns
/// (Result<JwtToken, &'static str>): struct containing parameters from the token
pub fn decode(encoded_token: String) -> Result<JwtToken, &'static str> {
let key: Hmac<Sha256> = Hmac::new_varkey(b"secret").unwrap();
let token_str: &str = encoded_token.as_str();
let token: Result<Token<Header, BTreeMap<String, i32>, _>, _> = VerifyWithKey::verify_with_key(token_str, &key);
match token {
Ok(token) => {
let _header = token.header();
let claims = token.claims();
return Ok(JwtToken { user_id: claims["user_id"], body: encoded_token})
}
Err(_) => return Err("Could not decode")
}
}
}
#[cfg(test)]
mod jwt_tests {
use super::JwtToken;
use actix_web::test;
#[test]
fn encode_decode() {
let encoded_token: String = JwtToken::encode(32);
let decoded_token: JwtToken = JwtToken::decode(encoded_token).unwrap();
assert_eq!(32, decoded_token.user_id);
}
#[test]
fn decode_incorrect_token() {
let encoded_token: String = String::from("test");
match JwtToken::decode(encoded_token) {
Err(message) => assert_eq!("Could not decode", message),
_ => panic!("Incorrect token should not be able to be encoded")
}
}
#[test]
fn decode_from_request_with_correct_token() {
let encoded_token: String = JwtToken::encode(32);
let request = test::TestRequest::with_header("user-token", encoded_token).to_http_request();
let out_come = JwtToken::decode_from_request(request);
match out_come {
Ok(token) => assert_eq!(32, token.user_id),
_ => panic!("Token is not returned when it should be")
}
}
}
| 29.979381 | 120 | 0.604883 |
03dbac6179d7c5abc72e29216670def34a6d24d9 | 3,552 | // ignore-tidy-linelength
// We specify -C incremental here because we want to test the partitioning for
// incremental compilation
// compile-flags:-Zprint-mono-items=lazy -Cincremental=tmp/partitioning-tests/vtable-through-const
// compile-flags:-Zinline-in-all-cgus
// This test case makes sure, that references made through constants are
// recorded properly in the InliningMap.
#![feature(start)]
mod mod1 {
pub trait Trait1 {
fn do_something(&self) {}
fn do_something_else(&self) {}
}
impl Trait1 for u32 {}
pub trait Trait1Gen<T> {
fn do_something(&self, x: T) -> T;
fn do_something_else(&self, x: T) -> T;
}
impl<T> Trait1Gen<T> for u32 {
fn do_something(&self, x: T) -> T { x }
fn do_something_else(&self, x: T) -> T { x }
}
//~ MONO_ITEM fn mod1::id::<i64> @@ vtable_through_const-mod1.volatile[Internal]
fn id<T>(x: T) -> T { x }
// These are referenced, so they produce mono-items (see start())
pub const TRAIT1_REF: &'static Trait1 = &0u32 as &Trait1;
pub const TRAIT1_GEN_REF: &'static Trait1Gen<u8> = &0u32 as &Trait1Gen<u8>;
pub const ID_CHAR: fn(char) -> char = id::<char>;
pub trait Trait2 {
fn do_something(&self) {}
fn do_something_else(&self) {}
}
//~ MONO_ITEM fn <u32 as mod1::Trait2>::do_something @@ vtable_through_const-mod1.volatile[Internal]
//~ MONO_ITEM fn <u32 as mod1::Trait2>::do_something_else @@ vtable_through_const-mod1.volatile[Internal]
impl Trait2 for u32 {}
pub trait Trait2Gen<T> {
fn do_something(&self, x: T) -> T;
fn do_something_else(&self, x: T) -> T;
}
impl<T> Trait2Gen<T> for u32 {
fn do_something(&self, x: T) -> T { x }
fn do_something_else(&self, x: T) -> T { x }
}
// These are not referenced, so they do not produce mono-items
pub const TRAIT2_REF: &'static Trait2 = &0u32 as &Trait2;
pub const TRAIT2_GEN_REF: &'static Trait2Gen<u8> = &0u32 as &Trait2Gen<u8>;
pub const ID_I64: fn(i64) -> i64 = id::<i64>;
}
//~ MONO_ITEM fn start
#[start]
fn start(_: isize, _: *const *const u8) -> isize {
//~ MONO_ITEM fn std::intrinsics::drop_in_place::<u32> - shim(None) @@ vtable_through_const[Internal]
// Since Trait1::do_something() is instantiated via its default implementation,
// it is considered a generic and is instantiated here only because it is
// referenced in this module.
//~ MONO_ITEM fn <u32 as mod1::Trait1>::do_something_else @@ vtable_through_const-mod1.volatile[External]
// Although it is never used, Trait1::do_something_else() has to be
// instantiated locally here too, otherwise the <&u32 as &Trait1> vtable
// could not be fully constructed.
//~ MONO_ITEM fn <u32 as mod1::Trait1>::do_something @@ vtable_through_const-mod1.volatile[External]
mod1::TRAIT1_REF.do_something();
// Same as above
//~ MONO_ITEM fn <u32 as mod1::Trait1Gen<u8>>::do_something @@ vtable_through_const-mod1.volatile[External]
//~ MONO_ITEM fn <u32 as mod1::Trait1Gen<u8>>::do_something_else @@ vtable_through_const-mod1.volatile[External]
//~ MONO_ITEM fn <u32 as mod1::Trait2Gen<u8>>::do_something @@ vtable_through_const-mod1.volatile[Internal]
//~ MONO_ITEM fn <u32 as mod1::Trait2Gen<u8>>::do_something_else @@ vtable_through_const-mod1.volatile[Internal]
mod1::TRAIT1_GEN_REF.do_something(0u8);
//~ MONO_ITEM fn mod1::id::<char> @@ vtable_through_const-mod1.volatile[External]
mod1::ID_CHAR('x');
0
}
| 37.787234 | 116 | 0.665822 |
f7e23ad0dd10cd5fe7a89af48c1a5020879768e3 | 9,631 | // Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_datavalues::DataSchemaRef;
use crate::plan_broadcast::BroadcastPlan;
use crate::plan_subqueries_set::SubQueriesSetPlan;
use crate::plan_user_stage_create::CreateUserStagePlan;
use crate::plan_user_udf_alter::AlterUDFPlan;
use crate::plan_user_udf_create::CreateUDFPlan;
use crate::plan_user_udf_drop::DropUDFPlan;
use crate::plan_user_udf_show::ShowUDFPlan;
use crate::AggregatorFinalPlan;
use crate::AggregatorPartialPlan;
use crate::AlterUserPlan;
use crate::CopyPlan;
use crate::CreateDatabasePlan;
use crate::CreateTablePlan;
use crate::CreateUserPlan;
use crate::DescribeStagePlan;
use crate::DescribeTablePlan;
use crate::DropDatabasePlan;
use crate::DropTablePlan;
use crate::DropUserPlan;
use crate::DropUserStagePlan;
use crate::EmptyPlan;
use crate::ExplainPlan;
use crate::ExpressionPlan;
use crate::FilterPlan;
use crate::GrantPrivilegePlan;
use crate::HavingPlan;
use crate::InsertPlan;
use crate::KillPlan;
use crate::LimitByPlan;
use crate::LimitPlan;
use crate::OptimizeTablePlan;
use crate::ProjectionPlan;
use crate::ReadDataSourcePlan;
use crate::RemotePlan;
use crate::RevokePrivilegePlan;
use crate::SelectPlan;
use crate::SettingPlan;
use crate::ShowCreateDatabasePlan;
use crate::ShowCreateTablePlan;
use crate::ShowGrantsPlan;
use crate::SinkPlan;
use crate::SortPlan;
use crate::StagePlan;
use crate::TruncateTablePlan;
use crate::UseDatabasePlan;
#[allow(clippy::large_enum_variant)]
#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq)]
pub enum PlanNode {
Empty(EmptyPlan),
Stage(StagePlan),
Broadcast(BroadcastPlan),
Remote(RemotePlan),
Projection(ProjectionPlan),
Expression(ExpressionPlan),
AggregatorPartial(AggregatorPartialPlan),
AggregatorFinal(AggregatorFinalPlan),
Filter(FilterPlan),
Having(HavingPlan),
Sort(SortPlan),
Limit(LimitPlan),
LimitBy(LimitByPlan),
ReadSource(ReadDataSourcePlan),
Sink(SinkPlan),
Select(SelectPlan),
Explain(ExplainPlan),
CreateDatabase(CreateDatabasePlan),
DropDatabase(DropDatabasePlan),
ShowCreateDatabase(ShowCreateDatabasePlan),
CreateTable(CreateTablePlan),
DescribeTable(DescribeTablePlan),
DropTable(DropTablePlan),
OptimizeTable(OptimizeTablePlan),
TruncateTable(TruncateTablePlan),
UseDatabase(UseDatabasePlan),
SetVariable(SettingPlan),
Insert(InsertPlan),
Copy(CopyPlan),
ShowCreateTable(ShowCreateTablePlan),
SubQueryExpression(SubQueriesSetPlan),
Kill(KillPlan),
CreateUser(CreateUserPlan),
AlterUser(AlterUserPlan),
DropUser(DropUserPlan),
GrantPrivilege(GrantPrivilegePlan),
RevokePrivilege(RevokePrivilegePlan),
CreateUserStage(CreateUserStagePlan),
DropUserStage(DropUserStagePlan),
DescribeStage(DescribeStagePlan),
ShowGrants(ShowGrantsPlan),
CreateUDF(CreateUDFPlan),
DropUDF(DropUDFPlan),
ShowUDF(ShowUDFPlan),
AlterUDF(AlterUDFPlan),
}
impl PlanNode {
/// Get a reference to the logical plan's schema
pub fn schema(&self) -> DataSchemaRef {
match self {
PlanNode::Empty(v) => v.schema(),
PlanNode::Stage(v) => v.schema(),
PlanNode::Broadcast(v) => v.schema(),
PlanNode::Remote(v) => v.schema(),
PlanNode::Projection(v) => v.schema(),
PlanNode::Expression(v) => v.schema(),
PlanNode::AggregatorPartial(v) => v.schema(),
PlanNode::AggregatorFinal(v) => v.schema(),
PlanNode::Filter(v) => v.schema(),
PlanNode::Having(v) => v.schema(),
PlanNode::Limit(v) => v.schema(),
PlanNode::LimitBy(v) => v.schema(),
PlanNode::ReadSource(v) => v.schema(),
PlanNode::Select(v) => v.schema(),
PlanNode::Explain(v) => v.schema(),
PlanNode::CreateDatabase(v) => v.schema(),
PlanNode::DropDatabase(v) => v.schema(),
PlanNode::CreateTable(v) => v.schema(),
PlanNode::DropTable(v) => v.schema(),
PlanNode::DescribeTable(v) => v.schema(),
PlanNode::OptimizeTable(v) => v.schema(),
PlanNode::DescribeStage(v) => v.schema(),
PlanNode::TruncateTable(v) => v.schema(),
PlanNode::SetVariable(v) => v.schema(),
PlanNode::Sort(v) => v.schema(),
PlanNode::UseDatabase(v) => v.schema(),
PlanNode::Insert(v) => v.schema(),
PlanNode::ShowCreateTable(v) => v.schema(),
PlanNode::SubQueryExpression(v) => v.schema(),
PlanNode::Kill(v) => v.schema(),
PlanNode::CreateUser(v) => v.schema(),
PlanNode::AlterUser(v) => v.schema(),
PlanNode::DropUser(v) => v.schema(),
PlanNode::GrantPrivilege(v) => v.schema(),
PlanNode::RevokePrivilege(v) => v.schema(),
PlanNode::Sink(v) => v.schema(),
PlanNode::Copy(v) => v.schema(),
PlanNode::CreateUserStage(v) => v.schema(),
PlanNode::DropUserStage(v) => v.schema(),
PlanNode::ShowGrants(v) => v.schema(),
PlanNode::ShowCreateDatabase(v) => v.schema(),
PlanNode::CreateUDF(v) => v.schema(),
PlanNode::DropUDF(v) => v.schema(),
PlanNode::ShowUDF(v) => v.schema(),
PlanNode::AlterUDF(v) => v.schema(),
}
}
pub fn name(&self) -> &str {
match self {
PlanNode::Empty(_) => "EmptyPlan",
PlanNode::Stage(_) => "StagePlan",
PlanNode::Broadcast(_) => "BroadcastPlan",
PlanNode::Remote(_) => "RemotePlan",
PlanNode::Projection(_) => "ProjectionPlan",
PlanNode::Expression(_) => "ExpressionPlan",
PlanNode::AggregatorPartial(_) => "AggregatorPartialPlan",
PlanNode::AggregatorFinal(_) => "AggregatorFinalPlan",
PlanNode::Filter(_) => "FilterPlan",
PlanNode::Having(_) => "HavingPlan",
PlanNode::Limit(_) => "LimitPlan",
PlanNode::LimitBy(_) => "LimitByPlan",
PlanNode::ReadSource(_) => "ReadSourcePlan",
PlanNode::Select(_) => "SelectPlan",
PlanNode::Explain(_) => "ExplainPlan",
PlanNode::CreateDatabase(_) => "CreateDatabasePlan",
PlanNode::DropDatabase(_) => "DropDatabasePlan",
PlanNode::CreateTable(_) => "CreateTablePlan",
PlanNode::DescribeTable(_) => "DescribeTablePlan",
PlanNode::OptimizeTable(_) => "OptimizeTablePlan",
PlanNode::DescribeStage(_) => "DescribeStagePlan",
PlanNode::DropTable(_) => "DropTablePlan",
PlanNode::TruncateTable(_) => "TruncateTablePlan",
PlanNode::SetVariable(_) => "SetVariablePlan",
PlanNode::Sort(_) => "SortPlan",
PlanNode::UseDatabase(_) => "UseDatabasePlan",
PlanNode::Insert(_) => "InsertPlan",
PlanNode::ShowCreateTable(_) => "ShowCreateTablePlan",
PlanNode::SubQueryExpression(_) => "CreateSubQueriesSets",
PlanNode::Kill(_) => "KillQuery",
PlanNode::CreateUser(_) => "CreateUser",
PlanNode::AlterUser(_) => "AlterUser",
PlanNode::DropUser(_) => "DropUser",
PlanNode::GrantPrivilege(_) => "GrantPrivilegePlan",
PlanNode::RevokePrivilege(_) => "RevokePrivilegePlan",
PlanNode::Sink(_) => "SinkPlan",
PlanNode::Copy(_) => "CopyPlan",
PlanNode::CreateUserStage(_) => "CreateUserStagePlan",
PlanNode::DropUserStage(_) => "DropUserStagePlan",
PlanNode::ShowGrants(_) => "ShowGrantsPlan",
PlanNode::ShowCreateDatabase(_) => "ShowCreateDatabasePlan",
PlanNode::CreateUDF(_) => "CreateUDFPlan",
PlanNode::DropUDF(_) => "DropUDFPlan",
PlanNode::ShowUDF(_) => "ShowUDF",
PlanNode::AlterUDF(_) => "AlterUDF",
}
}
pub fn inputs(&self) -> Vec<Arc<PlanNode>> {
match self {
PlanNode::Stage(v) => vec![v.input.clone()],
PlanNode::Broadcast(v) => vec![v.input.clone()],
PlanNode::Projection(v) => vec![v.input.clone()],
PlanNode::Expression(v) => vec![v.input.clone()],
PlanNode::AggregatorPartial(v) => vec![v.input.clone()],
PlanNode::AggregatorFinal(v) => vec![v.input.clone()],
PlanNode::Filter(v) => vec![v.input.clone()],
PlanNode::Having(v) => vec![v.input.clone()],
PlanNode::Limit(v) => vec![v.input.clone()],
PlanNode::Explain(v) => vec![v.input.clone()],
PlanNode::Select(v) => vec![v.input.clone()],
PlanNode::Sort(v) => vec![v.input.clone()],
PlanNode::SubQueryExpression(v) => v.get_inputs(),
PlanNode::Sink(v) => vec![v.input.clone()],
_ => vec![],
}
}
pub fn input(&self, n: usize) -> Arc<PlanNode> {
self.inputs()[n].clone()
}
}
| 39.797521 | 75 | 0.622677 |
fe8698b0ebf6084992a080eff2f7f4c915ac9481 | 2,044 | use base64;
use cpu::Registers;
use screen::Screen;
use serde::{Serialize, Serializer};
use serde::ser::SerializeStruct;
pub enum MemorySnapshot {
NoChange(u64), // If no change, just send the hash.
Updated(u64, Vec<u8>), // Updated, send hash and memory
}
pub struct CpuSnapshot<S: Screen + Serialize> {
registers: Registers,
memory: MemorySnapshot,
cycles: u64,
screen: S,
}
impl<S: Screen + Serialize> CpuSnapshot<S> {
pub fn new(mem_snapshot: MemorySnapshot, registers: Registers, screen: S, cycles: u64) -> Self {
CpuSnapshot {
registers: registers,
memory: mem_snapshot,
cycles: cycles,
screen: screen,
}
}
}
impl Serialize for MemorySnapshot {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match *self {
MemorySnapshot::NoChange(hash) => {
let mut state = serializer.serialize_struct("Memory", 2)?;
state.serialize_field("state", "NoChange")?;
state.serialize_field("hash", &hash)?;
state.end()
}
MemorySnapshot::Updated(hash, ref memory) => {
let base64 = base64::encode(&memory);
let mut state = serializer.serialize_struct("Memory", 3)?;
state.serialize_field("state", "Updated")?;
state.serialize_field("hash", &hash)?;
state.serialize_field("base64", &base64)?;
state.end()
}
}
}
}
impl<Scr: Screen + Serialize> Serialize for CpuSnapshot<Scr> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut state = serializer.serialize_struct("CpuSnapshot", 4)?;
state.serialize_field("registers", &self.registers)?;
state.serialize_field("memory", &self.memory)?;
state.serialize_field("cycles", &self.cycles)?;
state.serialize_field("screen", &self.screen)?;
state.end()
}
}
| 33.508197 | 100 | 0.584638 |
efc6548a03ee3465552f87489f609ead8101437b | 1,846 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use aptos_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
PrivateKey, Uniform,
};
use aptos_types::{account_address::AccountAddress, transaction::authenticator::AuthenticationKey};
use rand::{
rngs::{OsRng, StdRng},
Rng, SeedableRng,
};
/// Ed25519 key generator.
#[derive(Debug)]
pub struct KeyGen(StdRng);
impl KeyGen {
/// Constructs a key generator with a specific seed.
pub fn from_seed(seed: [u8; 32]) -> Self {
Self(StdRng::from_seed(seed))
}
/// Constructs a key generator with a random seed.
/// The random seed itself is generated using the OS rng.
pub fn from_os_rng() -> Self {
let mut seed_rng = OsRng;
let seed: [u8; 32] = seed_rng.gen();
Self::from_seed(seed)
}
/// Generate an Ed25519 key pair.
pub fn generate_keypair(&mut self) -> (Ed25519PrivateKey, Ed25519PublicKey) {
let private_key = Ed25519PrivateKey::generate(&mut self.0);
let public_key = private_key.public_key();
(private_key, public_key)
}
/// Same as `generate_keypair`, but returns a tuple of (private_key, auth_key_prefix, account_addr) instead.
pub fn generate_credentials_for_account_creation(
&mut self,
) -> (Ed25519PrivateKey, Vec<u8>, AccountAddress) {
let (private_key, public_key) = self.generate_keypair();
let auth_key = AuthenticationKey::ed25519(&public_key).to_vec();
const AUTH_KEY_PREFIX_LENGTH: usize = AuthenticationKey::LENGTH - AccountAddress::LENGTH;
let auth_key_prefix = auth_key[..AUTH_KEY_PREFIX_LENGTH].to_vec();
let account_addr = AccountAddress::from_bytes(&auth_key[AUTH_KEY_PREFIX_LENGTH..]).unwrap();
(private_key, auth_key_prefix, account_addr)
}
}
| 36.196078 | 112 | 0.683099 |
3a10cca32fd727134c832acc4ae56c2924e94722 | 2,015 | use std::{collections::HashMap, fmt};
/// Represents a point in space.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Coordinate {
/// X-component of this [Coordinate].
pub x: i32,
/// Y-component of this [Coordinate].
pub y: i32,
}
impl fmt::Debug for Coordinate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self, f)
}
}
impl fmt::Display for Coordinate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
/// Represents multiple points in space.
#[derive(Clone, Debug, PartialEq)]
pub struct Coordinates(Vec<Coordinate>);
impl Coordinates {
/// Returns a [HashMap] relating each [Coordinate] to a count of how many
/// copies of that [Coordinate] exist in this [Coordinates].
pub fn aggregate(&self) -> HashMap<Coordinate, usize> {
let mut coordinate_counts = HashMap::<Coordinate, usize>::new();
for coordinate in self.0.iter() {
coordinate_counts.insert(
*coordinate,
*coordinate_counts.get(coordinate).unwrap_or(&0) + 1,
);
}
coordinate_counts
}
}
impl From<Vec<Coordinate>> for Coordinates {
fn from(coordinates: Vec<Coordinate>) -> Self {
Coordinates(coordinates)
}
}
impl FromIterator<Coordinate> for Coordinates {
fn from_iter<T: IntoIterator<Item = Coordinate>>(iter: T) -> Self {
Coordinates(iter.into_iter().collect())
}
}
impl FromIterator<Vec<Coordinate>> for Coordinates {
fn from_iter<T: IntoIterator<Item = Vec<Coordinate>>>(iter: T) -> Self {
Coordinates(iter.into_iter().flatten().collect())
}
}
impl FromIterator<Coordinates> for Coordinates {
fn from_iter<T: IntoIterator<Item = Coordinates>>(iter: T) -> Self {
Coordinates(
iter.into_iter()
.map(|coordinates| coordinates.0)
.flatten()
.collect(),
)
}
}
| 27.60274 | 77 | 0.604963 |
72427ea449d6183c7bd8979b9024c13e2072f1c7 | 6,104 | #![cfg(feature = "conform")]
#![allow(non_snake_case)]
extern crate env_logger;
#[macro_use]
extern crate log;
#[macro_use]
extern crate proptest;
extern crate protobuf;
extern crate tract_core;
extern crate tract_tensorflow;
mod utils;
use crate::utils::*;
use ndarray::prelude::*;
use proptest::prelude::*;
use protobuf::Message;
use tract_core::ndarray;
use tract_core::prelude::*;
use tract_tensorflow::conform::*;
use tract_tensorflow::tfpb;
use tract_tensorflow::tfpb::types::DataType::DT_FLOAT;
fn convolution_pb(stride: usize, valid: bool, k: &Tensor) -> Result<Vec<u8>> {
let conv = tfpb::node()
.name("conv")
.op("DepthwiseConv2dNative")
.input("data")
.input("kernel")
.attr("strides", vec![1, stride as i64, stride as i64, 1])
.attr("dilations", vec![1, 1, 1, 1])
.attr("padding", if valid { "VALID" } else { "SAME" })
.attr("T", DT_FLOAT);
let graph = tfpb::graph().node(placeholder_f32("data")).node(const_f32("kernel", k)).node(conv);
Ok(graph.write_to_bytes()?)
}
fn img_and_ker() -> BoxedStrategy<(Array4<f32>, Array4<f32>, usize)> {
(1usize..3, 1usize..3, 1usize..3, 1usize..3, 1usize..3)
.prop_flat_map(|(ic, kh, kw, q, s)| {
(
1usize..3,
(kh + s..2 * kh + 4 * s),
(kw + s..2 * kw + 4 * s),
Just((ic, kh, kw, q, s)),
)
})
.prop_flat_map(|(ib, ih, iw, (ic, kh, kw, q, s))| {
let i_size = ib * iw * ih * ic;
let k_size = kw * kh * ic * q;
(
Just((ib, ih, iw, ic)),
Just((kh, kw, ic, q)),
::proptest::collection::vec(-9i32..9, i_size..i_size + 1),
::proptest::collection::vec(-9i32..9, k_size..k_size + 1),
Just(s),
)
})
.prop_map(|(img_shape, ker_shape, img, ker, stride)| {
(
Array::from_vec(img.into_iter().map(|i| i as f32).collect())
.into_shape(img_shape)
.unwrap(),
Array::from_vec(ker.into_iter().map(|i| i as f32).collect())
.into_shape(ker_shape)
.unwrap(),
stride,
)
})
.boxed()
}
proptest! {
#[test]
fn conv_compare((ref i, ref k, stride) in img_and_ker(),
valid in ::proptest::bool::ANY) {
let k = Tensor::from(k.clone());
let model = convolution_pb(stride, valid, &k).unwrap();
compare(&model, vec!(("data", i.clone().into()), ), "conv")?;
}
}
proptest! {
#[test]
fn conv_infer_facts((ref i, ref k, stride) in img_and_ker(),
valid in ::proptest::bool::ANY) {
let k = Tensor::from(k.clone());
let model = convolution_pb(stride, valid, &k).unwrap();
infer(&model, vec!(("data", i.clone().into())), "conv")?;
}
}
#[test]
fn conv_infer_facts_1() {
let i: Tensor = ArrayD::<f32>::zeros(vec![1, 2, 2, 2]).into();
let k: Tensor = ArrayD::<f32>::zeros(vec![2, 2, 2, 1]).into();
let model = convolution_pb(1, false, &k).unwrap();
infer(&model, vec![("data", i.clone().into())], "conv").unwrap();
}
#[test]
fn conv_eval_1() {
let i: Tensor = Tensor::from(arr4(&[[[[0.0f32, 0.0], [1.0, 0.0]]]]));
let k: Tensor = Tensor::from(arr4(&[[[[0.0f32], [0.0]], [[1.0], [0.0]]]]));
let model = convolution_pb(1, false, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_2() {
let i: Tensor = Tensor::from(arr4::<f32, _, _, _>(&[[[[-1.0], [0.0]]]]));
let k: Tensor = Tensor::from(arr4(&[[[[1.0f32]]]]));
let model = convolution_pb(2, false, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_3() {
let i: Tensor =
Tensor::from(Array::from_shape_fn((1, 112, 112, 48), |_| rand::random::<f32>()));
let k: Tensor = Tensor::from(Array::from_shape_fn((3, 3, 48, 1), |_| rand::random::<f32>()));
let conv = tfpb::node()
.name("conv")
.op("DepthwiseConv2dNative")
.input("data")
.input("kernel")
.attr("strides", vec![1, 1, 1, 1])
.attr("dilations", vec![1, 1, 1, 1])
.attr("padding", "SAME")
.attr("T", DT_FLOAT);
let graph =
tfpb::graph().node(placeholder_f32("data")).node(const_f32("kernel", &k)).node(conv);
let model = graph.write_to_bytes().unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_4() {
let i: Tensor = Tensor::from(arr4(&[[[[0.0f32], [0.0]], [[0.0], [-1.0]]]]));
let k: Tensor = Tensor::from(arr4(&[[[[0.0f32, -1.0]]]]));
let model = convolution_pb(1, false, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_5() {
let i: Tensor = Tensor::from(arr4(&[[[[0.0f32, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 1.0]]]]));
let k: Tensor = Tensor::from(arr4(&[[[[0.0f32, 0.0], [1.0, 0.0]]]]));
let model = convolution_pb(1, false, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_6() {
let i: Tensor = Tensor::from(arr4(&[[[[0.0f32, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 1.0]]]]));
let k: Tensor = Tensor::from(arr4(&[[[[0.0f32], [1.0]]]]));
let model = convolution_pb(1, true, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_7() {
let i: Tensor = tensor4(&[[[[1.0f32, 2.0]]]]);
let k: Tensor = tensor4(&[[[[3.0f32, 5.0], [7.0, 11.0]]]]);
let model = convolution_pb(1, false, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
#[test]
fn conv_eval_8() {
let i: Tensor =
tensor4(&[[[[0.0f32], [0.0]], [[0.0], [0.0]]], [[[0.0], [0.0]], [[0.0], [0.0]]]]);
let k: Tensor = tensor4(&[[[[0.0f32, 0.0]]]]);
let model = convolution_pb(1, true, &k).unwrap();
compare(&model, vec![("data", i.into())], "conv").unwrap();
}
| 33.723757 | 100 | 0.516383 |
505085bf294069adb779f4bf242555bab634b591 | 4,406 | use std::sync::Arc;
use swc_common::{SourceMap, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_fold_type, Fold};
use crate::{config::LintConfig, rule::Rule};
mod const_assign;
mod duplicate_bindings;
mod duplicate_exports;
mod no_dupe_args;
mod utils;
#[cfg(feature = "non_critical_lints")]
#[path = ""]
pub(crate) mod non_critical_lints {
pub mod default_param_last;
pub mod dot_notation;
pub mod eqeqeq;
pub mod no_alert;
pub mod no_bitwise;
pub mod no_console;
pub mod no_debugger;
pub mod no_empty_function;
pub mod no_empty_pattern;
pub mod no_loop_func;
pub mod no_new;
pub mod no_new_symbol;
pub mod no_restricted_syntax;
pub mod no_use_before_define;
pub mod prefer_regex_literals;
pub mod quotes;
pub mod radix;
pub mod use_is_nan;
pub mod valid_typeof;
pub mod yoda;
}
#[cfg(feature = "non_critical_lints")]
use non_critical_lints::*;
pub struct LintParams<'a> {
pub program: &'a Program,
pub lint_config: &'a LintConfig,
pub top_level_ctxt: SyntaxContext,
pub es_version: EsVersion,
pub source_map: Arc<SourceMap>,
}
pub fn all(lint_params: LintParams) -> Vec<Box<dyn Rule>> {
let mut rules = vec![
const_assign::const_assign(),
duplicate_bindings::duplicate_bindings(),
duplicate_exports::duplicate_exports(),
no_dupe_args::no_dupe_args(),
];
#[cfg(feature = "non_critical_lints")]
{
let LintParams {
program,
lint_config,
top_level_ctxt,
es_version,
source_map,
} = lint_params;
rules.extend(no_use_before_define::no_use_before_define(
&lint_params.lint_config.no_use_before_define,
));
rules.extend(no_console::no_console(
&lint_config.no_console,
top_level_ctxt,
));
rules.extend(no_alert::no_alert(
program,
&lint_config.no_alert,
top_level_ctxt,
es_version,
));
rules.extend(no_debugger::no_debugger(&lint_config.no_debugger));
rules.extend(quotes::quotes(&lint_config.quotes));
rules.extend(prefer_regex_literals::prefer_regex_literals(
program,
&source_map,
&lint_config.prefer_regex_literals,
top_level_ctxt,
es_version,
));
rules.extend(dot_notation::dot_notation(
program,
&lint_config.dot_notation,
));
rules.extend(no_empty_function::no_empty_function(
&source_map,
&lint_config.no_empty_function,
));
rules.extend(no_empty_pattern::no_empty_pattern(
&lint_config.no_empty_pattern,
));
rules.extend(eqeqeq::eqeqeq(&lint_config.eqeqeq));
rules.extend(no_loop_func::no_loop_func(&lint_config.no_loop_func));
rules.extend(no_new::no_new(&lint_config.no_new));
rules.extend(no_restricted_syntax::no_restricted_syntax(
&lint_config.no_restricted_syntax,
));
rules.extend(radix::radix(
program,
&source_map,
top_level_ctxt,
&lint_config.radix,
));
rules.extend(no_bitwise::no_bitwise(&lint_config.no_bitwise));
rules.extend(default_param_last::default_param_last(
&lint_config.default_param_last,
));
rules.extend(yoda::yoda(&lint_config.yoda));
rules.extend(no_new_symbol::no_new_symbol(
program,
top_level_ctxt,
&lint_config.no_new_symbol,
));
rules.extend(use_is_nan::use_is_nan(
program,
top_level_ctxt,
&lint_config.use_isnan,
));
rules.extend(valid_typeof::valid_typeof(&lint_config.valid_typeof));
}
rules
}
pub fn lint_to_fold<R>(r: R) -> impl Fold
where
R: Rule,
{
LintFolder(r)
}
struct LintFolder<R>(R)
where
R: Rule;
impl<R> Fold for LintFolder<R>
where
R: Rule,
{
noop_fold_type!();
#[inline(always)]
fn fold_module(&mut self, program: Module) -> Module {
self.0.lint_module(&program);
program
}
#[inline(always)]
fn fold_script(&mut self, program: Script) -> Script {
self.0.lint_script(&program);
program
}
}
| 23.816216 | 76 | 0.617794 |
d6e9c479c9b8dad1d1e5fb87763a8a406a480af4 | 2,598 | //! Various data structures used by the Rust compiler. The intention
//! is that code in here should be not be *specific* to rustc, so that
//! it can be easily unit tested and so forth.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(in_band_lifetimes)]
#![feature(unboxed_closures)]
#![feature(generators)]
#![feature(generator_trait)]
#![feature(fn_traits)]
#![feature(unsize)]
#![feature(specialization)]
#![feature(optin_builtin_traits)]
#![feature(nll)]
#![feature(allow_internal_unstable)]
#![feature(hash_raw_entry)]
#![feature(stmt_expr_attributes)]
#![feature(core_intrinsics)]
#![feature(integer_atomics)]
#![feature(test)]
#![feature(associated_type_bounds)]
#![cfg_attr(unix, feature(libc))]
#![allow(rustc::default_hash_types)]
#[macro_use]
extern crate log;
#[cfg(unix)]
extern crate libc;
#[macro_use]
extern crate cfg_if;
pub use rustc_serialize::hex::ToHex;
#[inline(never)]
#[cold]
pub fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
f()
}
#[macro_export]
macro_rules! likely {
($e:expr) => {
#[allow(unused_unsafe)]
{
unsafe { std::intrinsics::likely($e) }
}
}
}
#[macro_export]
macro_rules! unlikely {
($e:expr) => {
#[allow(unused_unsafe)]
{
unsafe { std::intrinsics::unlikely($e) }
}
}
}
pub mod macros;
pub mod svh;
pub mod base_n;
pub mod binary_search_util;
pub mod bit_set;
pub mod box_region;
pub mod const_cstr;
pub mod flock;
pub mod fx;
pub mod stable_map;
pub mod graph;
pub mod indexed_vec;
pub mod jobserver;
pub mod obligation_forest;
pub mod owning_ref;
pub mod ptr_key;
pub mod sip128;
pub mod small_c_str;
pub mod snapshot_map;
pub use ena::snapshot_vec;
pub mod sorted_map;
pub mod stable_set;
#[macro_use] pub mod stable_hasher;
pub mod sync;
pub mod sharded;
pub mod tiny_list;
pub mod thin_vec;
pub mod transitive_relation;
pub use ena::unify;
pub mod vec_linked_list;
pub mod work_queue;
pub mod fingerprint;
pub struct OnDrop<F: Fn()>(pub F);
impl<F: Fn()> OnDrop<F> {
/// Forgets the function which prevents it from running.
/// Ensure that the function owns no memory, otherwise it will be leaked.
#[inline]
pub fn disable(self) {
std::mem::forget(self);
}
}
impl<F: Fn()> Drop for OnDrop<F> {
#[inline]
fn drop(&mut self) {
(self.0)();
}
}
// See comments in src/librustc/lib.rs
#[doc(hidden)]
pub fn __noop_fix_for_27438() {}
| 21.471074 | 79 | 0.655504 |
fc26005bea228da2d5c828199707d0b02f0e709a | 8,699 | use std::rc::Rc;
use scheme::LispResult;
use scheme::value::Sexp;
use scheme::value::Sexp::*;
use scheme::env::Environment;
use scheme::error::LispError::*;
use scheme::value::HostFunction2;
use scheme::value::Transformer;
use std::collections::HashMap;
use std::collections::vec_deque::VecDeque;
use scheme::ELLIPSIS;
use scheme::UNDERSCORE;
pub struct LispMachine {
pub exp: Option<Sexp>,
pub env: Environment,
pub val: Option<Sexp>,
pub argl: Vec<Sexp>,
pub unev: Option<Sexp>,
}
impl LispMachine {
pub fn new(env: Environment) -> Self {
LispMachine {
exp: None,
env,
val: None,
argl: vec![],
unev: None,
}
}
pub fn eval(&mut self, expr: &Sexp) -> LispResult<Sexp> {
match expr {
Nil => return Err(ApplyError("missing procedure expression".to_owned())),
Symbol(name) => if let Some(val) = self.env.lookup(&name) {
let val = val.borrow().clone();
match &val {
// 语法关键字如果不位于列表头部是无效的
Syntax { name, .. } => syntax_error!(name, "bad syntax"),
DefineSyntax { keyword, .. } => syntax_error!(keyword, "bad syntax"),
_ => Ok(val)
}
} else {
Err(Undefined(name.to_string()))
}
List(xs) => self.eval_list(&*xs),
_ => Ok(expr.clone()),
}
}
// 对列表中的第一个元素求值
fn eval_head(&mut self, expr: &Sexp) -> LispResult<Sexp> {
use self::Sexp::*;
match expr {
Symbol(name) => if let Some(val) = self.env.lookup(&name) {
Ok(val.borrow().clone())
} else {
Err(Undefined(name.to_string()))
}
_ => self.eval(expr),
}
}
// 对列表求值
fn eval_list(&mut self, exprs: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
let (head, tail) = exprs.split_first().unwrap();
let proc = self.eval_head(head)?;
match proc {
DefineSyntax { keyword, transformer } => {
let expr = List(Box::new(exprs.to_vec()));
self.apply_transformer(&keyword, transformer, &expr)
}
Syntax { func, .. } => self.apply_keyword(func, tail),
_ => {
let (last, init) = tail.split_last().unwrap();
if *last != Nil {
syntax_error!("apply", "bad syntax")
}
let args: Result<Vec<_>, _> = init.iter().map(|e| self.eval(e)).collect();
if args.is_err() {
return Err(args.unwrap_err());
}
self.apply(&proc, &args.unwrap())
}
}
}
pub fn apply(&mut self, proc: &Sexp, exprs: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
match proc {
Function { func, .. } => func(exprs),
Procedure { func, .. } => func(self, exprs),
Closure { name, params, vararg, body, env } => {
let func_name = if name.is_empty() {
"#<procedure>"
} else {
name
};
let args = exprs;
let nparams = params.len();
let nargs = args.len();
let mut ctx = Environment::new(Some(Rc::new(env.clone())));
match vararg {
Some(ref name) => {
if nargs < nparams {
// FIXME expected least nparams...
return Err(ArityMismatch(func_name.to_string(), nparams, nargs));
}
let (pos, rest) = args.split_at(nparams);
ctx.insert_many(params, pos);
let varg = if nargs == nparams {
Nil
} else {
let mut xs = rest.to_vec();
xs.push(Nil);
List(Box::new(xs))
};
ctx.insert(name, &varg);
}
_ => {
if nargs != nparams {
return Err(ArityMismatch(func_name.to_string(), nparams, nargs));
}
ctx.insert_many(params, &args);
}
}
let old_ctx = self.env.clone();
self.env = ctx;
// FIXME tail call optimization
let (last, init) = body.split_last().unwrap();
for expr in init {
self.eval(expr)?;
}
let res = self.eval(last);
self.env = old_ctx;
res
}
_ => Err(ApplyError(format!("not a procedure: {}", proc))),
}
}
fn apply_transformer(&mut self, keyword: &str, transformer: Transformer, form: &Sexp) -> LispResult<Sexp> {
let mut rules = transformer.rules.clone();
for rule in &mut rules {
println!("{}", rule.pattern);
if let Some(bindings) = Self::match_syntax_rule(&rule.pattern, form) {
// dbg!(&bindings);
let expr = self.render_template(&bindings, &rule.template);
println!("{}", expr);
return self.eval(&expr);
}
}
syntax_error!(keyword, "bad syntax")
}
fn apply_keyword(&mut self, func: HostFunction2, exprs: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
let (last, init) = exprs.split_last().unwrap();
let args = if *last == Nil {
init
} else {
exprs
};
func(self, args)
}
fn render_template(&mut self, bindings: &HashMap<String, Sexp>, template: &Sexp) -> Sexp {
use self::Sexp::*;
let mut q = VecDeque::new();
let mut r: Sexp = Nil;
q.push_back(template);
loop {
let list: &Sexp = if let Some(list) = q.pop_front() {
list
} else {
return r;
};
for (index, item) in list.into_iter().enumerate() {
if let Symbol(ident) = &item {
if let Some(val) = bindings.get(ident) {
r = list.clone();
r.set_nth(index, val);
}
} else if item.is_pair() {
q.push_back(item)
}
}
r = list.clone();
}
}
fn match_syntax_rule(pat: &Sexp, form: &Sexp) -> Option<HashMap<String, Sexp>> {
use self::Sexp::*;
let mut q: VecDeque<(&Sexp, &Sexp)> = VecDeque::new();
let mut bindings = HashMap::new();
q.push_back((pat, form));
loop {
let (p, f): (&Sexp, &Sexp) = if let Some((a, b)) = q.pop_front() {
(a, b)
} else {
return Some(bindings);
};
if p.is_list() != f.is_list() {
return None;
}
let mut index_b = 0;
for (index, a) in p.as_slice().unwrap().iter().enumerate() {
if let Symbol(ident) = a {
if ident == ELLIPSIS {
if f.list_count() < p.list_count() - 2 {
return None;
}
} else if ident != UNDERSCORE {
if let Some(b) = f.nth(index) {
index_b += 1;
bindings.insert(ident.clone(), b.clone());
continue;
}
return None;
}
} else if a.is_pair() {
if let Some(b) = f.nth(index) {
index_b += 1;
if b.is_pair() {
q.push_back((a, b));
continue;
}
}
return None;
} else {
if let Some(b) = f.nth(index) {
index_b += 1;
if a == b {
continue;
}
}
return None;
}
}
if index_b + 1 != f.list_count() {
return None;
}
}
}
}
| 33.717054 | 111 | 0.411657 |
1ab461a9421291ed788c7d36f37d728f5459b722 | 1,872 | /*!
Rust MIR: a lowered representation of Rust.
*/
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(control_flow_enum)]
#![feature(crate_visibility_modifier)]
#![feature(decl_macro)]
#![feature(exact_size_is_empty)]
#![feature(let_else)]
#![feature(map_try_insert)]
#![feature(min_specialization)]
#![feature(slice_ptr_get)]
#![feature(option_get_or_insert_default)]
#![feature(never_type)]
#![feature(trait_alias)]
#![feature(trusted_len)]
#![feature(trusted_step)]
#![feature(try_blocks)]
#![recursion_limit = "256"]
#![allow(rustc::potential_query_instability)]
#[macro_use]
extern crate tracing;
#[macro_use]
extern crate rustc_middle;
pub mod const_eval;
pub mod interpret;
pub mod transform;
pub mod util;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::ParamEnv;
pub fn provide(providers: &mut Providers) {
const_eval::provide(providers);
providers.eval_to_const_value_raw = const_eval::eval_to_const_value_raw_provider;
providers.eval_to_allocation_raw = const_eval::eval_to_allocation_raw_provider;
providers.const_caller_location = const_eval::const_caller_location;
providers.try_destructure_const = |tcx, param_env_and_value| {
let (param_env, value) = param_env_and_value.into_parts();
const_eval::try_destructure_const(tcx, param_env, value).ok()
};
providers.const_to_valtree = |tcx, param_env_and_value| {
let (param_env, raw) = param_env_and_value.into_parts();
const_eval::const_to_valtree(tcx, param_env, raw)
};
providers.valtree_to_const_val = |tcx, (ty, valtree)| {
const_eval::valtree_to_const_value(tcx, ParamEnv::empty().and(ty), valtree)
};
providers.deref_const = |tcx, param_env_and_value| {
let (param_env, value) = param_env_and_value.into_parts();
const_eval::deref_const(tcx, param_env, value)
};
}
| 31.2 | 85 | 0.736111 |
ddad276f8a7c832b252d94aaf9ae042b42b476f3 | 59,707 | //! # Categorization
//!
//! The job of the categorization module is to analyze an expression to
//! determine what kind of memory is used in evaluating it (for example,
//! where dereferences occur and what kind of pointer is dereferenced;
//! whether the memory is mutable, etc.).
//!
//! Categorization effectively transforms all of our expressions into
//! expressions of the following forms (the actual enum has many more
//! possibilities, naturally, but they are all variants of these base
//! forms):
//!
//! E = rvalue // some computed rvalue
//! | x // address of a local variable or argument
//! | *E // deref of a ptr
//! | E.comp // access to an interior component
//!
//! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
//! address where the result is to be found. If Expr is a place, then this
//! is the address of the place. If `Expr` is an rvalue, this is the address of
//! some temporary spot in memory where the result is stored.
//!
//! Now, `cat_expr()` classifies the expression `Expr` and the address `A = ToAddr(Expr)`
//! as follows:
//!
//! - `cat`: what kind of expression was this? This is a subset of the
//! full expression forms which only includes those that we care about
//! for the purpose of the analysis.
//! - `mutbl`: mutability of the address `A`.
//! - `ty`: the type of data found at the address `A`.
//!
//! The resulting categorization tree differs somewhat from the expressions
//! themselves. For example, auto-derefs are explicit. Also, an index a[b] is
//! decomposed into two operations: a dereference to reach the array data and
//! then an index to jump forward to the relevant item.
//!
//! ## By-reference upvars
//!
//! One part of the codegen which may be non-obvious is that we translate
//! closure upvars into the dereference of a borrowed pointer; this more closely
//! resembles the runtime codegen. So, for example, if we had:
//!
//! let mut x = 3;
//! let y = 5;
//! let inc = || x += y;
//!
//! Then when we categorize `x` (*within* the closure) we would yield a
//! result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
//! tied to `x`. The type of `x'` will be a borrowed pointer.
#![allow(non_camel_case_types)]
pub use self::PointerKind::*;
pub use self::InteriorKind::*;
pub use self::MutabilityCategory::*;
pub use self::AliasableReason::*;
pub use self::Note::*;
use self::Aliasability::*;
use crate::middle::region;
use crate::hir::def_id::{DefId, LocalDefId};
use crate::hir::Node;
use crate::infer::InferCtxt;
use crate::hir::def::{CtorOf, Res, DefKind, CtorKind};
use crate::ty::adjustment;
use crate::ty::{self, DefIdTree, Ty, TyCtxt};
use crate::ty::fold::TypeFoldable;
use crate::hir::{MutImmutable, MutMutable, PatKind};
use crate::hir::pat_util::EnumerateAndAdjustIterator;
use crate::hir;
use syntax::ast::{self, Name};
use syntax::symbol::sym;
use syntax_pos::Span;
use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use rustc_data_structures::fx::FxIndexMap;
use std::rc::Rc;
use crate::util::nodemap::ItemLocalSet;
#[derive(Clone, Debug, PartialEq)]
pub enum Categorization<'tcx> {
Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
ThreadLocal(ty::Region<'tcx>), // value that cannot move, but still restricted in scope
StaticItem,
Upvar(Upvar), // upvar referenced by closure env
Local(hir::HirId), // local variable
Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
// (*1) downcast is only required if the enum has more than one variant
}
// Represents any kind of upvar
#[derive(Clone, Copy, PartialEq)]
pub struct Upvar {
pub id: ty::UpvarId,
pub kind: ty::ClosureKind
}
// different kinds of pointers:
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PointerKind<'tcx> {
/// `Box<T>`
Unique,
/// `&T`
BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
/// `*T`
UnsafePtr(hir::Mutability),
}
// We use the term "interior" to mean "something reachable from the
// base without a pointer dereference", e.g., a field
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum InteriorKind {
InteriorField(FieldIndex),
InteriorElement(InteriorOffsetKind),
}
// Contains index of a field that is actually used for loan path comparisons and
// string representation of the field that should be used only for diagnostics.
#[derive(Clone, Copy, Eq)]
pub struct FieldIndex(pub usize, pub Name);
impl PartialEq for FieldIndex {
fn eq(&self, rhs: &Self) -> bool {
self.0 == rhs.0
}
}
impl Hash for FieldIndex {
fn hash<H: Hasher>(&self, h: &mut H) {
self.0.hash(h)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum InteriorOffsetKind {
Index, // e.g., `array_expr[index_expr]`
Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }`
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum MutabilityCategory {
McImmutable, // Immutable.
McDeclared, // Directly declared as mutable.
McInherited, // Inherited from the fact that owner is mutable.
}
// A note about the provenance of a `cmt`. This is used for
// special-case handling of upvars such as mutability inference.
// Upvar categorization can generate a variable number of nested
// derefs. The note allows detecting them without deep pattern
// matching on the categorization.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Note {
NoteClosureEnv(ty::UpvarId), // Deref through closure env
NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
NoteIndex, // Deref as part of desugaring `x[]` into its two components
NoteNone // Nothing special
}
// `cmt`: "Category, Mutability, and Type".
//
// a complete categorization of a value indicating where it originated
// and how it is located, as well as the mutability of the memory in
// which the value is stored.
//
// *WARNING* The field `cmt.type` is NOT necessarily the same as the
// result of `node_type(cmt.id)`.
//
// (FIXME: rewrite the following comment given that `@x` managed
// pointers have been obsolete for quite some time.)
//
// This is because the `id` is always the `id` of the node producing the
// type; in an expression like `*x`, the type of this deref node is the
// deref'd type (`T`), but in a pattern like `@x`, the `@x` pattern is
// again a dereference, but its type is the type *before* the
// dereference (`@T`). So use `cmt.ty` to find the type of the value in
// a consistent fashion. For more details, see the method `cat_pattern`
#[derive(Clone, Debug, PartialEq)]
pub struct cmt_<'tcx> {
pub hir_id: hir::HirId, // HIR id of expr/pat producing this value
pub span: Span, // span of same expr/pat
pub cat: Categorization<'tcx>, // categorization of expr
pub mutbl: MutabilityCategory, // mutability of expr as place
pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
pub note: Note, // Note about the provenance of this cmt
}
pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
pub trait HirNode {
fn hir_id(&self) -> hir::HirId;
fn span(&self) -> Span;
}
impl HirNode for hir::Expr {
fn hir_id(&self) -> hir::HirId { self.hir_id }
fn span(&self) -> Span { self.span }
}
impl HirNode for hir::Pat {
fn hir_id(&self) -> hir::HirId { self.hir_id }
fn span(&self) -> Span { self.span }
}
#[derive(Clone)]
pub struct MemCategorizationContext<'a, 'tcx> {
pub tcx: TyCtxt<'tcx>,
pub body_owner: DefId,
pub upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
pub region_scope_tree: &'a region::ScopeTree,
pub tables: &'a ty::TypeckTables<'tcx>,
rvalue_promotable_map: Option<&'tcx ItemLocalSet>,
infcx: Option<&'a InferCtxt<'a, 'tcx>>,
}
pub type McResult<T> = Result<T, ()>;
impl MutabilityCategory {
pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
let ret = match m {
MutImmutable => McImmutable,
MutMutable => McDeclared
};
debug!("MutabilityCategory::{}({:?}) => {:?}",
"from_mutbl", m, ret);
ret
}
pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
let ret = match borrow_kind {
ty::ImmBorrow => McImmutable,
ty::UniqueImmBorrow => McImmutable,
ty::MutBorrow => McDeclared,
};
debug!("MutabilityCategory::{}({:?}) => {:?}",
"from_borrow_kind", borrow_kind, ret);
ret
}
fn from_pointer_kind(base_mutbl: MutabilityCategory,
ptr: PointerKind<'_>) -> MutabilityCategory {
let ret = match ptr {
Unique => {
base_mutbl.inherit()
}
BorrowedPtr(borrow_kind, _) => {
MutabilityCategory::from_borrow_kind(borrow_kind)
}
UnsafePtr(m) => {
MutabilityCategory::from_mutbl(m)
}
};
debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
"from_pointer_kind", base_mutbl, ptr, ret);
ret
}
fn from_local(
tcx: TyCtxt<'_>,
tables: &ty::TypeckTables<'_>,
id: hir::HirId,
) -> MutabilityCategory {
let ret = match tcx.hir().get(id) {
Node::Binding(p) => match p.node {
PatKind::Binding(..) => {
let bm = *tables.pat_binding_modes()
.get(p.hir_id)
.expect("missing binding mode");
if bm == ty::BindByValue(hir::MutMutable) {
McDeclared
} else {
McImmutable
}
}
_ => span_bug!(p.span, "expected identifier pattern")
},
_ => span_bug!(tcx.hir().span(id), "expected identifier pattern")
};
debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
"from_local", id, ret);
ret
}
pub fn inherit(&self) -> MutabilityCategory {
let ret = match *self {
McImmutable => McImmutable,
McDeclared => McInherited,
McInherited => McInherited,
};
debug!("{:?}.inherit() => {:?}", self, ret);
ret
}
pub fn is_mutable(&self) -> bool {
let ret = match *self {
McImmutable => false,
McInherited => true,
McDeclared => true,
};
debug!("{:?}.is_mutable() => {:?}", self, ret);
ret
}
pub fn is_immutable(&self) -> bool {
let ret = match *self {
McImmutable => true,
McDeclared | McInherited => false
};
debug!("{:?}.is_immutable() => {:?}", self, ret);
ret
}
pub fn to_user_str(&self) -> &'static str {
match *self {
McDeclared | McInherited => "mutable",
McImmutable => "immutable",
}
}
}
impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
pub fn new(
tcx: TyCtxt<'tcx>,
body_owner: DefId,
region_scope_tree: &'a region::ScopeTree,
tables: &'a ty::TypeckTables<'tcx>,
rvalue_promotable_map: Option<&'tcx ItemLocalSet>,
) -> MemCategorizationContext<'a, 'tcx> {
MemCategorizationContext {
tcx,
body_owner,
upvars: tcx.upvars(body_owner),
region_scope_tree,
tables,
rvalue_promotable_map,
infcx: None
}
}
}
impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
/// Creates a `MemCategorizationContext` during type inference.
/// This is used during upvar analysis and a few other places.
/// Because the typeck tables are not yet complete, the results
/// from the analysis must be used with caution:
///
/// - rvalue promotions are not known, so the lifetimes of
/// temporaries may be overly conservative;
/// - similarly, as the results of upvar analysis are not yet
/// known, the results around upvar accesses may be incorrect.
pub fn with_infer(
infcx: &'a InferCtxt<'a, 'tcx>,
body_owner: DefId,
region_scope_tree: &'a region::ScopeTree,
tables: &'a ty::TypeckTables<'tcx>,
) -> MemCategorizationContext<'a, 'tcx> {
let tcx = infcx.tcx;
// Subtle: we can't do rvalue promotion analysis until the
// typeck phase is complete, which means that you can't trust
// the rvalue lifetimes that result, but that's ok, since we
// don't need to know those during type inference.
let rvalue_promotable_map = None;
MemCategorizationContext {
tcx,
body_owner,
upvars: tcx.upvars(body_owner),
region_scope_tree,
tables,
rvalue_promotable_map,
infcx: Some(infcx),
}
}
pub fn type_is_copy_modulo_regions(
&self,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
span: Span,
) -> bool {
self.infcx.map(|infcx| infcx.type_is_copy_modulo_regions(param_env, ty, span))
.or_else(|| {
if (param_env, ty).has_local_value() {
None
} else {
Some(ty.is_copy_modulo_regions(self.tcx, param_env, span))
}
})
.unwrap_or(true)
}
fn resolve_vars_if_possible<T>(&self, value: &T) -> T
where T: TypeFoldable<'tcx>
{
self.infcx.map(|infcx| infcx.resolve_vars_if_possible(value))
.unwrap_or_else(|| value.clone())
}
fn is_tainted_by_errors(&self) -> bool {
self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
}
fn resolve_type_vars_or_error(&self,
id: hir::HirId,
ty: Option<Ty<'tcx>>)
-> McResult<Ty<'tcx>> {
match ty {
Some(ty) => {
let ty = self.resolve_vars_if_possible(&ty);
if ty.references_error() || ty.is_ty_var() {
debug!("resolve_type_vars_or_error: error from {:?}", ty);
Err(())
} else {
Ok(ty)
}
}
// FIXME
None if self.is_tainted_by_errors() => Err(()),
None => {
bug!("no type for node {}: {} in mem_categorization",
id, self.tcx.hir().node_to_string(id));
}
}
}
pub fn node_ty(&self,
hir_id: hir::HirId)
-> McResult<Ty<'tcx>> {
self.resolve_type_vars_or_error(hir_id,
self.tables.node_type_opt(hir_id))
}
pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
}
pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
}
/// Returns the type of value that this pattern matches against.
/// Some non-obvious cases:
///
/// - a `ref x` binding matches against a value of type `T` and gives
/// `x` the type `&T`; we return `T`.
/// - a pattern with implicit derefs (thanks to default binding
/// modes #42640) may look like `Some(x)` but in fact have
/// implicit deref patterns attached (e.g., it is really
/// `&Some(x)`). In that case, we return the "outermost" type
/// (e.g., `&Option<T>).
pub fn pat_ty_adjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
// Check for implicit `&` types wrapping the pattern; note
// that these are never attached to binding patterns, so
// actually this is somewhat "disjoint" from the code below
// that aims to account for `ref x`.
if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
if let Some(first_ty) = vec.first() {
debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
return Ok(first_ty);
}
}
self.pat_ty_unadjusted(pat)
}
/// Like `pat_ty`, but ignores implicit `&` patterns.
fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
let base_ty = self.node_ty(pat.hir_id)?;
debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
// This code detects whether we are looking at a `ref x`,
// and if so, figures out what the type *being borrowed* is.
let ret_ty = match pat.node {
PatKind::Binding(..) => {
let bm = *self.tables
.pat_binding_modes()
.get(pat.hir_id)
.expect("missing binding mode");
if let ty::BindByReference(_) = bm {
// a bind-by-ref means that the base_ty will be the type of the ident itself,
// but what we want here is the type of the underlying value being borrowed.
// So peel off one-level, turning the &T into T.
match base_ty.builtin_deref(false) {
Some(t) => t.ty,
None => {
debug!("By-ref binding of non-derefable type {:?}", base_ty);
return Err(());
}
}
} else {
base_ty
}
}
_ => base_ty,
};
debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
Ok(ret_ty)
}
pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
// This recursion helper avoids going through *too many*
// adjustments, since *only* non-overloaded deref recurses.
fn helper<'a, 'tcx>(
mc: &MemCategorizationContext<'a, 'tcx>,
expr: &hir::Expr,
adjustments: &[adjustment::Adjustment<'tcx>],
) -> McResult<cmt_<'tcx>> {
match adjustments.split_last() {
None => mc.cat_expr_unadjusted(expr),
Some((adjustment, previous)) => {
mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
}
}
}
helper(self, expr, self.tables.expr_adjustments(expr))
}
pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
previous: cmt_<'tcx>,
adjustment: &adjustment::Adjustment<'tcx>)
-> McResult<cmt_<'tcx>> {
self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
}
fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
previous: F,
adjustment: &adjustment::Adjustment<'tcx>)
-> McResult<cmt_<'tcx>>
where F: FnOnce() -> McResult<cmt_<'tcx>>
{
debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
let target = self.resolve_vars_if_possible(&adjustment.target);
match adjustment.kind {
adjustment::Adjust::Deref(overloaded) => {
// Equivalent to *expr or something similar.
let base = Rc::new(if let Some(deref) = overloaded {
let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
ty: target,
mutbl: deref.mutbl,
});
self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty)
} else {
previous()?
});
self.cat_deref(expr, base, NoteNone)
}
adjustment::Adjust::NeverToAny |
adjustment::Adjust::Pointer(_) |
adjustment::Adjust::Borrow(_) => {
// Result is an rvalue.
Ok(self.cat_rvalue_node(expr.hir_id, expr.span, target))
}
}
}
pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr);
let expr_ty = self.expr_ty(expr)?;
match expr.node {
hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
if self.tables.is_method_call(expr) {
self.cat_overloaded_place(expr, e_base, NoteNone)
} else {
let base_cmt = Rc::new(self.cat_expr(&e_base)?);
self.cat_deref(expr, base_cmt, NoteNone)
}
}
hir::ExprKind::Field(ref base, f_ident) => {
let base_cmt = Rc::new(self.cat_expr(&base)?);
debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
expr.hir_id,
expr,
base_cmt);
let f_index = self.tcx.field_index(expr.hir_id, self.tables);
Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
}
hir::ExprKind::Index(ref base, _) => {
if self.tables.is_method_call(expr) {
// If this is an index implemented by a method call, then it
// will include an implicit deref of the result.
// The call to index() returns a `&T` value, which
// is an rvalue. That is what we will be
// dereferencing.
self.cat_overloaded_place(expr, base, NoteIndex)
} else {
let base_cmt = Rc::new(self.cat_expr(&base)?);
self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
}
}
hir::ExprKind::Path(ref qpath) => {
let res = self.tables.qpath_res(qpath, expr.hir_id);
self.cat_res(expr.hir_id, expr.span, expr_ty, res)
}
hir::ExprKind::Type(ref e, _) => {
self.cat_expr(&e)
}
hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) |
hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) |
hir::ExprKind::Binary(..) |
hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Err => {
Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
}
}
}
pub fn cat_res(&self,
hir_id: hir::HirId,
span: Span,
expr_ty: Ty<'tcx>,
res: Res)
-> McResult<cmt_<'tcx>> {
debug!("cat_res: id={:?} expr={:?} def={:?}",
hir_id, expr_ty, res);
match res {
Res::Def(DefKind::Ctor(..), _)
| Res::Def(DefKind::Const, _)
| Res::Def(DefKind::ConstParam, _)
| Res::Def(DefKind::AssocConst, _)
| Res::Def(DefKind::Fn, _)
| Res::Def(DefKind::Method, _)
| Res::SelfCtor(..) => {
Ok(self.cat_rvalue_node(hir_id, span, expr_ty))
}
Res::Def(DefKind::Static, def_id) => {
// `#[thread_local]` statics may not outlive the current function, but
// they also cannot be moved out of.
let is_thread_local = self.tcx.get_attrs(def_id)[..]
.iter()
.any(|attr| attr.check_name(sym::thread_local));
let cat = if is_thread_local {
let re = self.temporary_scope(hir_id.local_id);
Categorization::ThreadLocal(re)
} else {
Categorization::StaticItem
};
Ok(cmt_ {
hir_id,
span,
cat,
mutbl: match self.tcx.static_mutability(def_id).unwrap() {
hir::MutImmutable => McImmutable,
hir::MutMutable => McDeclared,
},
ty:expr_ty,
note: NoteNone
})
}
Res::Local(var_id) => {
if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) {
self.cat_upvar(hir_id, span, var_id)
} else {
Ok(cmt_ {
hir_id,
span,
cat: Categorization::Local(var_id),
mutbl: MutabilityCategory::from_local(self.tcx, self.tables, var_id),
ty: expr_ty,
note: NoteNone
})
}
}
def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
}
}
// Categorize an upvar, complete with invisible derefs of closure
// environment and upvar reference as appropriate.
fn cat_upvar(
&self,
hir_id: hir::HirId,
span: Span,
var_id: hir::HirId,
) -> McResult<cmt_<'tcx>> {
// An upvar can have up to 3 components. We translate first to a
// `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
// field from the environment.
//
// `Categorization::Upvar`. Next, we add a deref through the implicit
// environment pointer with an anonymous free region 'env and
// appropriate borrow kind for closure kinds that take self by
// reference. Finally, if the upvar was captured
// by-reference, we add a deref through that reference. The
// region of this reference is an inference variable 'up that
// was previously generated and recorded in the upvar borrow
// map. The borrow kind bk is inferred by based on how the
// upvar is used.
//
// This results in the following table for concrete closure
// types:
//
// | move | ref
// ---------------+----------------------+-------------------------------
// Fn | copied -> &'env | upvar -> &'env -> &'up bk
// FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
// FnOnce | copied | upvar -> &'up bk
let closure_expr_def_id = self.body_owner;
let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(
LocalDefId::from_def_id(closure_expr_def_id),
);
let ty = self.node_ty(fn_hir_id)?;
let kind = match ty.sty {
ty::Generator(..) => ty::ClosureKind::FnOnce,
ty::Closure(closure_def_id, closure_substs) => {
match self.infcx {
// During upvar inference we may not know the
// closure kind, just use the LATTICE_BOTTOM value.
Some(infcx) =>
infcx.closure_kind(closure_def_id, closure_substs)
.unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
None =>
closure_substs.closure_kind(closure_def_id, self.tcx.global_tcx()),
}
}
_ => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", ty),
};
let upvar_id = ty::UpvarId {
var_path: ty::UpvarPath { hir_id: var_id },
closure_expr_id: closure_expr_def_id.to_local(),
};
let var_ty = self.node_ty(var_id)?;
// Mutability of original variable itself
let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
// Construct the upvar. This represents access to the field
// from the environment (perhaps we should eventually desugar
// this field further, but it will do for now).
let cmt_result = cmt_ {
hir_id,
span,
cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
mutbl: var_mutbl,
ty: var_ty,
note: NoteNone
};
// If this is a `FnMut` or `Fn` closure, then the above is
// conceptually a `&mut` or `&` reference, so we have to add a
// deref.
let cmt_result = match kind {
ty::ClosureKind::FnOnce => {
cmt_result
}
ty::ClosureKind::FnMut => {
self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
}
ty::ClosureKind::Fn => {
self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
}
};
// If this is a by-ref capture, then the upvar we loaded is
// actually a reference, so we have to add an implicit deref
// for that.
let upvar_capture = self.tables.upvar_capture(upvar_id);
let cmt_result = match upvar_capture {
ty::UpvarCapture::ByValue => {
cmt_result
}
ty::UpvarCapture::ByRef(upvar_borrow) => {
let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
cmt_ {
hir_id,
span,
cat: Categorization::Deref(Rc::new(cmt_result), ptr),
mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
ty: var_ty,
note: NoteUpvarRef(upvar_id)
}
}
};
let ret = cmt_result;
debug!("cat_upvar ret={:?}", ret);
Ok(ret)
}
fn env_deref(&self,
hir_id: hir::HirId,
span: Span,
upvar_id: ty::UpvarId,
upvar_mutbl: MutabilityCategory,
env_borrow_kind: ty::BorrowKind,
cmt_result: cmt_<'tcx>)
-> cmt_<'tcx>
{
// Region of environment pointer
let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
// The environment of a closure is guaranteed to
// outlive any bindings introduced in the body of the
// closure itself.
scope: upvar_id.closure_expr_id.to_def_id(),
bound_region: ty::BrEnv
}));
let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
let var_ty = cmt_result.ty;
// We need to add the env deref. This means
// that the above is actually immutable and
// has a ref type. However, nothing should
// actually look at the type, so we can get
// away with stuffing a `Error` in there
// instead of bothering to construct a proper
// one.
let cmt_result = cmt_ {
mutbl: McImmutable,
ty: self.tcx.types.err,
..cmt_result
};
let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
// Issue #18335. If variable is declared as immutable, override the
// mutability from the environment and substitute an `&T` anyway.
match upvar_mutbl {
McImmutable => { deref_mutbl = McImmutable; }
McDeclared | McInherited => { }
}
let ret = cmt_ {
hir_id,
span,
cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
mutbl: deref_mutbl,
ty: var_ty,
note: NoteClosureEnv(upvar_id)
};
debug!("env_deref ret {:?}", ret);
ret
}
/// Returns the lifetime of a temporary created by expr with id `id`.
/// This could be `'static` if `id` is part of a constant expression.
pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
let scope = self.region_scope_tree.temporary_scope(id);
self.tcx.mk_region(match scope {
Some(scope) => ty::ReScope(scope),
None => ty::ReStatic
})
}
pub fn cat_rvalue_node(&self,
hir_id: hir::HirId,
span: Span,
expr_ty: Ty<'tcx>)
-> cmt_<'tcx> {
debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
hir_id, span, expr_ty);
let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
.unwrap_or(false);
debug!("cat_rvalue_node: promotable = {:?}", promotable);
// Always promote `[T; 0]` (even when e.g., borrowed mutably).
let promotable = match expr_ty.sty {
ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true,
_ => promotable,
};
debug!("cat_rvalue_node: promotable = {:?} (2)", promotable);
// Compute maximum lifetime of this rvalue. This is 'static if
// we can promote to a constant, otherwise equal to enclosing temp
// lifetime.
let re = if promotable {
self.tcx.lifetimes.re_static
} else {
self.temporary_scope(hir_id.local_id)
};
let ret = self.cat_rvalue(hir_id, span, re, expr_ty);
debug!("cat_rvalue_node ret {:?}", ret);
ret
}
pub fn cat_rvalue(&self,
cmt_hir_id: hir::HirId,
span: Span,
temp_scope: ty::Region<'tcx>,
expr_ty: Ty<'tcx>) -> cmt_<'tcx> {
let ret = cmt_ {
hir_id: cmt_hir_id,
span:span,
cat:Categorization::Rvalue(temp_scope),
mutbl:McDeclared,
ty:expr_ty,
note: NoteNone
};
debug!("cat_rvalue ret {:?}", ret);
ret
}
pub fn cat_field<N: HirNode>(&self,
node: &N,
base_cmt: cmt<'tcx>,
f_index: usize,
f_ident: ast::Ident,
f_ty: Ty<'tcx>)
-> cmt_<'tcx> {
let ret = cmt_ {
hir_id: node.hir_id(),
span: node.span(),
mutbl: base_cmt.mutbl.inherit(),
cat: Categorization::Interior(base_cmt,
InteriorField(FieldIndex(f_index, f_ident.name))),
ty: f_ty,
note: NoteNone
};
debug!("cat_field ret {:?}", ret);
ret
}
fn cat_overloaded_place(
&self,
expr: &hir::Expr,
base: &hir::Expr,
note: Note,
) -> McResult<cmt_<'tcx>> {
debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
expr,
base,
note);
// Reconstruct the output assuming it's a reference with the
// same region and mutability as the receiver. This holds for
// `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
let place_ty = self.expr_ty(expr)?;
let base_ty = self.expr_ty_adjusted(base)?;
let (region, mutbl) = match base_ty.sty {
ty::Ref(region, _, mutbl) => (region, mutbl),
_ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
};
let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
ty: place_ty,
mutbl,
});
let base_cmt = Rc::new(self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty));
self.cat_deref(expr, base_cmt, note)
}
pub fn cat_deref(
&self,
node: &impl HirNode,
base_cmt: cmt<'tcx>,
note: Note,
) -> McResult<cmt_<'tcx>> {
debug!("cat_deref: base_cmt={:?}", base_cmt);
let base_cmt_ty = base_cmt.ty;
let deref_ty = match base_cmt_ty.builtin_deref(true) {
Some(mt) => mt.ty,
None => {
debug!("Explicit deref of non-derefable type: {:?}", base_cmt_ty);
return Err(());
}
};
let ptr = match base_cmt.ty.sty {
ty::Adt(def, ..) if def.is_box() => Unique,
ty::RawPtr(ref mt) => UnsafePtr(mt.mutbl),
ty::Ref(r, _, mutbl) => {
let bk = ty::BorrowKind::from_mutbl(mutbl);
BorrowedPtr(bk, r)
}
_ => bug!("unexpected type in cat_deref: {:?}", base_cmt.ty)
};
let ret = cmt_ {
hir_id: node.hir_id(),
span: node.span(),
// For unique ptrs, we inherit mutability from the owning reference.
mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
cat: Categorization::Deref(base_cmt, ptr),
ty: deref_ty,
note: note,
};
debug!("cat_deref ret {:?}", ret);
Ok(ret)
}
fn cat_index<N: HirNode>(&self,
elt: &N,
base_cmt: cmt<'tcx>,
element_ty: Ty<'tcx>,
context: InteriorOffsetKind)
-> McResult<cmt_<'tcx>> {
//! Creates a cmt for an indexing operation (`[]`).
//!
//! One subtle aspect of indexing that may not be
//! immediately obvious: for anything other than a fixed-length
//! vector, an operation like `x[y]` actually consists of two
//! disjoint (from the point of view of borrowck) operations.
//! The first is a deref of `x` to create a pointer `p` that points
//! at the first element in the array. The second operation is
//! an index which adds `y*sizeof(T)` to `p` to obtain the
//! pointer to `x[y]`. `cat_index` will produce a resulting
//! cmt containing both this deref and the indexing,
//! presuming that `base_cmt` is not of fixed-length type.
//!
//! # Parameters
//! - `elt`: the HIR node being indexed
//! - `base_cmt`: the cmt of `elt`
let interior_elem = InteriorElement(context);
let ret = self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
debug!("cat_index ret {:?}", ret);
return Ok(ret);
}
pub fn cat_imm_interior<N:HirNode>(&self,
node: &N,
base_cmt: cmt<'tcx>,
interior_ty: Ty<'tcx>,
interior: InteriorKind)
-> cmt_<'tcx> {
let ret = cmt_ {
hir_id: node.hir_id(),
span: node.span(),
mutbl: base_cmt.mutbl.inherit(),
cat: Categorization::Interior(base_cmt, interior),
ty: interior_ty,
note: NoteNone
};
debug!("cat_imm_interior ret={:?}", ret);
ret
}
pub fn cat_downcast_if_needed<N:HirNode>(&self,
node: &N,
base_cmt: cmt<'tcx>,
variant_did: DefId)
-> cmt<'tcx> {
// univariant enums do not need downcasts
let base_did = self.tcx.parent(variant_did).unwrap();
if self.tcx.adt_def(base_did).variants.len() != 1 {
let base_ty = base_cmt.ty;
let ret = Rc::new(cmt_ {
hir_id: node.hir_id(),
span: node.span(),
mutbl: base_cmt.mutbl.inherit(),
cat: Categorization::Downcast(base_cmt, variant_did),
ty: base_ty,
note: NoteNone
});
debug!("cat_downcast ret={:?}", ret);
ret
} else {
debug!("cat_downcast univariant={:?}", base_cmt);
base_cmt
}
}
pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
where F: FnMut(cmt<'tcx>, &hir::Pat),
{
self.cat_pattern_(cmt, pat, &mut op)
}
// FIXME(#19596) This is a workaround, but there should be a better way to do this
fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
where F : FnMut(cmt<'tcx>, &hir::Pat)
{
// Here, `cmt` is the categorization for the value being
// matched and pat is the pattern it is being matched against.
//
// In general, the way that this works is that we walk down
// the pattern, constructing a cmt that represents the path
// that will be taken to reach the value being matched.
//
// When we encounter named bindings, we take the cmt that has
// been built up and pass it off to guarantee_valid() so that
// we can be sure that the binding will remain valid for the
// duration of the arm.
//
// (*2) There is subtlety concerning the correspondence between
// pattern ids and types as compared to *expression* ids and
// types. This is explained briefly. on the definition of the
// type `cmt`, so go off and read what it says there, then
// come back and I'll dive into a bit more detail here. :) OK,
// back?
//
// In general, the id of the cmt should be the node that
// "produces" the value---patterns aren't executable code
// exactly, but I consider them to "execute" when they match a
// value, and I consider them to produce the value that was
// matched. So if you have something like:
//
// (FIXME: `@@3` is not legal code anymore!)
//
// let x = @@3;
// match x {
// @@y { ... }
// }
//
// In this case, the cmt and the relevant ids would be:
//
// CMT Id Type of Id Type of cmt
//
// local(x)->@->@
// ^~~~~~~^ `x` from discr @@int @@int
// ^~~~~~~~~~^ `@@y` pattern node @@int @int
// ^~~~~~~~~~~~~^ `@y` pattern node @int int
//
// You can see that the types of the id and the cmt are in
// sync in the first line, because that id is actually the id
// of an expression. But once we get to pattern ids, the types
// step out of sync again. So you'll see below that we always
// get the type of the *subpattern* and use that.
debug!("cat_pattern(pat={:?}, cmt={:?})", pat, cmt);
// If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
// `cmt`s are constructed differently from patterns. For example, in
//
// ```
// match foo {
// &&Some(x, ) => { ... },
// _ => { ... },
// }
// ```
//
// the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
// corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
// pattern, try to answer the question: given the address of `foo`, how is `x` reached?
//
// `&&Some(x,)` `cmt_foo`
// `&Some(x,)` `deref { cmt_foo}`
// `Some(x,)` `deref { deref { cmt_foo }}`
// (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
//
// The above example has no adjustments. If the code were instead the (after adjustments,
// equivalent) version
//
// ```
// match foo {
// Some(x, ) => { ... },
// _ => { ... },
// }
// ```
//
// Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
// instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
// though its assigned type is that of `&&Some(x,)`.
for _ in 0..self.tables
.pat_adjustments()
.get(pat.hir_id)
.map(|v| v.len())
.unwrap_or(0)
{
debug!("cat_pattern: applying adjustment to cmt={:?}", cmt);
cmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
}
let cmt = cmt; // lose mutability
debug!("cat_pattern: applied adjustment derefs to get cmt={:?}", cmt);
// Invoke the callback, but only now, after the `cmt` has adjusted.
//
// To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
// case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
// don't want to call `op` with these incompatible values. As written, what happens instead
// is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
// `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
// result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
// that (where the `ref` on `x` is implied).
op(cmt.clone(), pat);
match pat.node {
PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
let res = self.tables.qpath_res(qpath, pat.hir_id);
let (cmt, expected_len) = match res {
Res::Err => {
debug!("access to unresolvable pattern {:?}", pat);
return Err(())
}
Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), variant_ctor_did) => {
let variant_did = self.tcx.parent(variant_ctor_did).unwrap();
let enum_did = self.tcx.parent(variant_did).unwrap();
(self.cat_downcast_if_needed(pat, cmt, variant_did),
self.tcx.adt_def(enum_did)
.variant_with_ctor_id(variant_ctor_did).fields.len())
}
Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
| Res::SelfCtor(..) => {
let ty = self.pat_ty_unadjusted(&pat)?;
match ty.sty {
ty::Adt(adt_def, _) => {
(cmt, adt_def.non_enum_variant().fields.len())
}
_ => {
span_bug!(pat.span,
"tuple struct pattern unexpected type {:?}", ty);
}
}
}
def => {
debug!(
"tuple struct pattern didn't resolve to variant or struct {:?} at {:?}",
def,
pat.span,
);
self.tcx.sess.delay_span_bug(pat.span, &format!(
"tuple struct pattern didn't resolve to variant or struct {:?}",
def,
));
return Err(());
}
};
for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
let interior = InteriorField(FieldIndex(i, sym::integer(i)));
let subcmt = Rc::new(
self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
self.cat_pattern_(subcmt, &subpat, op)?;
}
}
PatKind::Struct(ref qpath, ref field_pats, _) => {
// {f1: p1, ..., fN: pN}
let res = self.tables.qpath_res(qpath, pat.hir_id);
let cmt = match res {
Res::Err => {
debug!("access to unresolvable pattern {:?}", pat);
return Err(())
}
Res::Def(DefKind::Ctor(CtorOf::Variant, _), variant_ctor_did) => {
let variant_did = self.tcx.parent(variant_ctor_did).unwrap();
self.cat_downcast_if_needed(pat, cmt, variant_did)
}
Res::Def(DefKind::Variant, variant_did) => {
self.cat_downcast_if_needed(pat, cmt, variant_did)
}
_ => cmt,
};
for fp in field_pats {
let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
let f_index = self.tcx.field_index(fp.node.hir_id, self.tables);
let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
fp.node.ident, field_ty));
self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
}
}
PatKind::Binding(.., Some(ref subpat)) => {
self.cat_pattern_(cmt, &subpat, op)?;
}
PatKind::Tuple(ref subpats, ddpos) => {
// (p1, ..., pN)
let ty = self.pat_ty_unadjusted(&pat)?;
let expected_len = match ty.sty {
ty::Tuple(ref tys) => tys.len(),
_ => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
};
for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
let interior = InteriorField(FieldIndex(i, sym::integer(i)));
let subcmt = Rc::new(
self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
self.cat_pattern_(subcmt, &subpat, op)?;
}
}
PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
// box p1, &p1, &mut p1. we can ignore the mutability of
// PatKind::Ref since that information is already contained
// in the type.
let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
self.cat_pattern_(subcmt, &subpat, op)?;
}
PatKind::Slice(ref before, ref slice, ref after) => {
let element_ty = match cmt.ty.builtin_index() {
Some(ty) => ty,
None => {
debug!("Explicit index of non-indexable type {:?}", cmt);
return Err(());
}
};
let context = InteriorOffsetKind::Pattern;
let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
for before_pat in before {
self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
}
if let Some(ref slice_pat) = *slice {
self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
}
for after_pat in after {
self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
}
}
PatKind::Path(_) | PatKind::Binding(.., None) |
PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
// always ok
}
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub enum Aliasability {
FreelyAliasable(AliasableReason),
NonAliasable,
ImmutableUnique(Box<Aliasability>),
}
#[derive(Copy, Clone, Debug)]
pub enum AliasableReason {
AliasableBorrowed,
AliasableStatic,
AliasableStaticMut,
}
impl<'tcx> cmt_<'tcx> {
pub fn guarantor(&self) -> cmt_<'tcx> {
//! Returns `self` after stripping away any derefs or
//! interior content. The return value is basically the `cmt` which
//! determines how long the value in `self` remains live.
match self.cat {
Categorization::Rvalue(..) |
Categorization::StaticItem |
Categorization::ThreadLocal(..) |
Categorization::Local(..) |
Categorization::Deref(_, UnsafePtr(..)) |
Categorization::Deref(_, BorrowedPtr(..)) |
Categorization::Upvar(..) => {
(*self).clone()
}
Categorization::Downcast(ref b, _) |
Categorization::Interior(ref b, _) |
Categorization::Deref(ref b, Unique) => {
b.guarantor()
}
}
}
/// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
pub fn freely_aliasable(&self) -> Aliasability {
// Maybe non-obvious: copied upvars can only be considered
// non-aliasable in once closures, since any other kind can be
// aliased and eventually recused.
match self.cat {
Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
Categorization::Deref(ref b, Unique) |
Categorization::Downcast(ref b, _) |
Categorization::Interior(ref b, _) => {
// Aliasability depends on base cmt
b.freely_aliasable()
}
Categorization::Rvalue(..) |
Categorization::ThreadLocal(..) |
Categorization::Local(..) |
Categorization::Upvar(..) |
Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
NonAliasable
}
Categorization::StaticItem => {
if self.mutbl.is_mutable() {
FreelyAliasable(AliasableStaticMut)
} else {
FreelyAliasable(AliasableStatic)
}
}
Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) => {
FreelyAliasable(AliasableBorrowed)
}
}
}
// Digs down through one or two layers of deref and grabs the
// Categorization of the cmt for the upvar if a note indicates there is
// one.
pub fn upvar_cat(&self) -> Option<&Categorization<'tcx>> {
match self.note {
NoteClosureEnv(..) | NoteUpvarRef(..) => {
Some(match self.cat {
Categorization::Deref(ref inner, _) => {
match inner.cat {
Categorization::Deref(ref inner, _) => &inner.cat,
Categorization::Upvar(..) => &inner.cat,
_ => bug!()
}
}
_ => bug!()
})
}
NoteIndex | NoteNone => None
}
}
pub fn descriptive_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
match self.cat {
Categorization::StaticItem => {
"static item".into()
}
Categorization::ThreadLocal(..) => {
"thread-local static item".into()
}
Categorization::Rvalue(..) => {
"non-place".into()
}
Categorization::Local(vid) => {
if tcx.hir().is_argument(vid) {
"argument"
} else {
"local variable"
}.into()
}
Categorization::Deref(_, pk) => {
match self.upvar_cat() {
Some(&Categorization::Upvar(ref var)) => {
var.to_string().into()
}
Some(_) => bug!(),
None => {
match pk {
Unique => {
"`Box` content"
}
UnsafePtr(..) => {
"dereference of raw pointer"
}
BorrowedPtr(..) => {
match self.note {
NoteIndex => "indexed content",
_ => "borrowed content"
}
}
}.into()
}
}
}
Categorization::Interior(_, InteriorField(..)) => {
"field".into()
}
Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
"indexed content".into()
}
Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
"pattern-bound indexed content".into()
}
Categorization::Upvar(ref var) => {
var.to_string().into()
}
Categorization::Downcast(ref cmt, _) => {
cmt.descriptive_string(tcx).into()
}
}
}
}
pub fn ptr_sigil(ptr: PointerKind<'_>) -> &'static str {
match ptr {
Unique => "Box",
BorrowedPtr(ty::ImmBorrow, _) => "&",
BorrowedPtr(ty::MutBorrow, _) => "&mut",
BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
UnsafePtr(_) => "*",
}
}
impl fmt::Debug for InteriorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
InteriorField(FieldIndex(_, info)) => write!(f, "{}", info),
InteriorElement(..) => write!(f, "[]"),
}
}
}
impl fmt::Debug for Upvar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}/{:?}", self.id, self.kind)
}
}
impl fmt::Display for Upvar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self.kind {
ty::ClosureKind::Fn => "Fn",
ty::ClosureKind::FnMut => "FnMut",
ty::ClosureKind::FnOnce => "FnOnce",
};
write!(f, "captured outer variable in an `{}` closure", kind)
}
}
| 38.770779 | 100 | 0.507997 |
141531b635c393ce60579bd3433e3c4e7d3b869f | 17,573 | // Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! An implementation of a key-value map.
//!
//! `MapIndex` requires that keys implement the [`StorageKey`] trait and values implement
//! the [`StorageValue`] trait. The given section contains methods related to
//! `MapIndex` and iterators over the items of this map.
use std::{borrow::Borrow, marker::PhantomData};
use super::{
base_index::{BaseIndex, BaseIndexIter}, indexes_metadata::IndexType, Fork, Snapshot,
StorageKey, StorageValue,
};
/// A map of keys and values. Access to the elements of this map is obtained using the keys.
///
/// `MapIndex` requires that keys implement the [`StorageKey`] trait and values implement
/// the [`StorageValue`] trait.
///
/// [`StorageKey`]: ../trait.StorageKey.html
/// [`StorageValue`]: ../trait.StorageValue.html
#[derive(Debug)]
pub struct MapIndex<T, K, V> {
base: BaseIndex<T>,
_k: PhantomData<K>,
_v: PhantomData<V>,
}
/// Returns an iterator over the entries of a `MapIndex`.
///
/// This struct is created by the [`iter`] or
/// [`iter_from`] method on [`MapIndex`]. See its documentation for additional details.
///
/// [`iter`]: struct.MapIndex.html#method.iter
/// [`iter_from`]: struct.MapIndex.html#method.iter_from
/// [`MapIndex`]: struct.MapIndex.html
#[derive(Debug)]
pub struct MapIndexIter<'a, K, V> {
base_iter: BaseIndexIter<'a, K, V>,
}
/// Returns an iterator over the keys of a `MapIndex`.
///
/// This struct is created by the [`keys`] or
/// [`keys_from`] method on [`MapIndex`]. See its documentation for additional details.
///
/// [`keys`]: struct.MapIndex.html#method.keys
/// [`keys_from`]: struct.MapIndex.html#method.keys_from
/// [`MapIndex`]: struct.MapIndex.html
#[derive(Debug)]
pub struct MapIndexKeys<'a, K> {
base_iter: BaseIndexIter<'a, K, ()>,
}
/// Returns an iterator over the values of a `MapIndex`.
///
/// This struct is created by the [`values`] or
/// [`values_from`] method on [`MapIndex`]. See its documentation for additional details.
///
/// [`values`]: struct.MapIndex.html#method.values
/// [`values_from`]: struct.MapIndex.html#method.values_from
/// [`MapIndex`]: struct.MapIndex.html
#[derive(Debug)]
pub struct MapIndexValues<'a, V> {
base_iter: BaseIndexIter<'a, (), V>,
}
impl<T, K, V> MapIndex<T, K, V>
where
T: AsRef<dyn Snapshot>,
K: StorageKey,
V: StorageValue,
{
/// Creates a new index representation based on the name and storage view.
///
/// Storage view can be specified as [`&Snapshot`] or [`&mut Fork`]. In the first case, only
/// immutable methods are available. In the second case, both immutable and mutable methods are
/// available.
///
/// [`&Snapshot`]: ../trait.Snapshot.html
/// [`&mut Fork`]: ../struct.Fork.html
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
/// ```
pub fn new<S: AsRef<str>>(index_name: S, view: T) -> Self {
Self {
base: BaseIndex::new(index_name, IndexType::Map, view),
_k: PhantomData,
_v: PhantomData,
}
}
/// Creates a new index representation based on the name, index ID in family
/// and storage view.
///
/// Storage view can be specified as [`&Snapshot`] or [`&mut Fork`]. In the first case, only
/// immutable methods are available. In the second case, both immutable and mutable methods are
/// available.
///
/// [`&Snapshot`]: ../trait.Snapshot.html
/// [`&mut Fork`]: ../struct.Fork.html
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let index_id = vec![01];
///
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new_in_family(name, &index_id, &snapshot);
/// ```
pub fn new_in_family<S: AsRef<str>, I: StorageKey>(
family_name: S,
index_id: &I,
view: T,
) -> Self {
Self {
base: BaseIndex::new_in_family(family_name, index_id, IndexType::Map, view),
_k: PhantomData,
_v: PhantomData,
}
}
/// Returns a value corresponding to the key.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = MapIndex::new(name, &mut fork);
/// assert!(index.get(&1).is_none());
///
/// index.put(&1, 2);
/// assert_eq!(Some(2), index.get(&1));
/// ```
pub fn get<Q>(&self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: StorageKey + ?Sized,
{
self.base.get(key)
}
/// Returns `true` if the map contains a value corresponding to the specified key.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = MapIndex::new(name, &mut fork);
/// assert!(!index.contains(&1));
///
/// index.put(&1, 2);
/// assert!(index.contains(&1));
pub fn contains<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: StorageKey + ?Sized,
{
self.base.contains(key)
}
/// Returns an iterator over the entries of the map in ascending order. The iterator element
/// type is (K, V).
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
///
/// for v in index.iter() {
/// println!("{:?}", v);
/// }
/// ```
pub fn iter(&self) -> MapIndexIter<K, V> {
MapIndexIter {
base_iter: self.base.iter(&()),
}
}
/// Returns an iterator over the keys of a map in ascending order. The iterator element
/// type is K.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
///
/// for key in index.keys() {
/// println!("{}", key);
/// }
/// ```
pub fn keys(&self) -> MapIndexKeys<K> {
MapIndexKeys {
base_iter: self.base.iter(&()),
}
}
/// Returns an iterator over the values of a map in ascending order of keys. The iterator
/// element type is V.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
///
/// for val in index.values() {
/// println!("{}", val);
/// }
/// ```
pub fn values(&self) -> MapIndexValues<V> {
MapIndexValues {
base_iter: self.base.iter(&()),
}
}
/// Returns an iterator over the entries of a map in ascending order starting from the
/// specified key. The iterator element type is (K, V).
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
///
/// for v in index.iter_from(&2) {
/// println!("{:?}", v);
/// }
/// ```
pub fn iter_from<Q>(&self, from: &Q) -> MapIndexIter<K, V>
where
K: Borrow<Q>,
Q: StorageKey + ?Sized,
{
MapIndexIter {
base_iter: self.base.iter_from(&(), from),
}
}
/// Returns an iterator over the keys of a map in ascending order starting from the
/// specified key. The iterator element type is K.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
///
/// for key in index.keys_from(&2) {
/// println!("{}", key);
/// }
/// ```
pub fn keys_from<Q>(&self, from: &Q) -> MapIndexKeys<K>
where
K: Borrow<Q>,
Q: StorageKey + ?Sized,
{
MapIndexKeys {
base_iter: self.base.iter_from(&(), from),
}
}
/// Returns an iterator over the values of a map in ascending order of keys starting from the
/// specified key. The iterator element type is V.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let snapshot = db.snapshot();
/// let index: MapIndex<_, u8, u8> = MapIndex::new(name, &snapshot);
/// for val in index.values_from(&2) {
/// println!("{}", val);
/// }
/// ```
pub fn values_from<Q>(&self, from: &Q) -> MapIndexValues<V>
where
K: Borrow<Q>,
Q: StorageKey + ?Sized,
{
MapIndexValues {
base_iter: self.base.iter_from(&(), from),
}
}
}
impl<'a, K, V> MapIndex<&'a mut Fork, K, V>
where
K: StorageKey,
V: StorageValue,
{
/// Inserts a key-value pair into a map.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = MapIndex::new(name, &mut fork);
///
/// index.put(&1, 2);
/// assert!(index.contains(&1));
pub fn put(&mut self, key: &K, value: V) {
self.base.put(key, value)
}
/// Removes a key from a map.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = MapIndex::new(name, &mut fork);
///
/// index.put(&1, 2);
/// assert!(index.contains(&1));
///
/// index.remove(&1);
/// assert!(!index.contains(&1));
pub fn remove<Q>(&mut self, key: &Q)
where
K: Borrow<Q>,
Q: StorageKey + ?Sized,
{
self.base.remove(key)
}
/// Clears a map, removing all entries.
///
/// # Notes
/// Currently, this method is not optimized to delete a large set of data. During the execution of
/// this method, the amount of allocated memory is linearly dependent on the number of elements
/// in the index.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, MapIndex};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = MapIndex::new(name, &mut fork);
///
/// index.put(&1, 2);
/// assert!(index.contains(&1));
///
/// index.clear();
/// assert!(!index.contains(&1));
pub fn clear(&mut self) {
self.base.clear()
}
}
impl<'a, T, K, V> ::std::iter::IntoIterator for &'a MapIndex<T, K, V>
where
T: AsRef<dyn Snapshot>,
K: StorageKey,
V: StorageValue,
{
type Item = (K::Owned, V);
type IntoIter = MapIndexIter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, K, V> Iterator for MapIndexIter<'a, K, V>
where
K: StorageKey,
V: StorageValue,
{
type Item = (K::Owned, V);
fn next(&mut self) -> Option<Self::Item> {
self.base_iter.next()
}
}
impl<'a, K> Iterator for MapIndexKeys<'a, K>
where
K: StorageKey,
{
type Item = K::Owned;
fn next(&mut self) -> Option<Self::Item> {
self.base_iter.next().map(|(k, ..)| k)
}
}
impl<'a, V> Iterator for MapIndexValues<'a, V>
where
V: StorageValue,
{
type Item = V;
fn next(&mut self) -> Option<Self::Item> {
self.base_iter.next().map(|(.., v)| v)
}
}
#[cfg(test)]
mod tests {
use super::super::{Database, MemoryDB};
use super::*;
use rand::{thread_rng, Rng};
const IDX_NAME: &'static str = "idx_name";
#[test]
fn str_key() {
let db = MemoryDB::new();
let mut fork = db.fork();
const KEY: &str = "key_1";
let mut index: MapIndex<_, String, _> = MapIndex::new(IDX_NAME, &mut fork);
assert_eq!(false, index.contains(KEY));
index.put(&KEY.to_owned(), 0);
assert_eq!(true, index.contains(KEY));
index.remove(KEY);
assert_eq!(false, index.contains(KEY));
}
#[test]
fn u8_slice_key() {
let db = MemoryDB::new();
let mut fork = db.fork();
const KEY: &[u8] = &[1, 2, 3];
let mut index: MapIndex<_, Vec<u8>, _> = MapIndex::new(IDX_NAME, &mut fork);
assert_eq!(false, index.contains(KEY));
index.put(&KEY.to_owned(), 0);
assert_eq!(true, index.contains(KEY));
index.remove(KEY);
assert_eq!(false, index.contains(KEY));
}
fn iter(db: Box<dyn Database>) {
let mut fork = db.fork();
let mut map_index = MapIndex::new(IDX_NAME, &mut fork);
map_index.put(&1u8, 1u8);
map_index.put(&2u8, 2u8);
map_index.put(&3u8, 3u8);
assert_eq!(
map_index.iter().collect::<Vec<(u8, u8)>>(),
vec![(1, 1), (2, 2), (3, 3)]
);
assert_eq!(
map_index.iter_from(&0).collect::<Vec<(u8, u8)>>(),
vec![(1, 1), (2, 2), (3, 3)]
);
assert_eq!(
map_index.iter_from(&1).collect::<Vec<(u8, u8)>>(),
vec![(1, 1), (2, 2), (3, 3)]
);
assert_eq!(
map_index.iter_from(&2).collect::<Vec<(u8, u8)>>(),
vec![(2, 2), (3, 3)]
);
assert_eq!(
map_index.iter_from(&4).collect::<Vec<(u8, u8)>>(),
Vec::<(u8, u8)>::new()
);
assert_eq!(map_index.keys().collect::<Vec<u8>>(), vec![1, 2, 3]);
assert_eq!(map_index.keys_from(&0).collect::<Vec<u8>>(), vec![1, 2, 3]);
assert_eq!(map_index.keys_from(&1).collect::<Vec<u8>>(), vec![1, 2, 3]);
assert_eq!(map_index.keys_from(&2).collect::<Vec<u8>>(), vec![2, 3]);
assert_eq!(
map_index.keys_from(&4).collect::<Vec<u8>>(),
Vec::<u8>::new()
);
assert_eq!(map_index.values().collect::<Vec<u8>>(), vec![1, 2, 3]);
assert_eq!(
map_index.values_from(&0).collect::<Vec<u8>>(),
vec![1, 2, 3]
);
assert_eq!(
map_index.values_from(&1).collect::<Vec<u8>>(),
vec![1, 2, 3]
);
assert_eq!(map_index.values_from(&2).collect::<Vec<u8>>(), vec![2, 3]);
assert_eq!(
map_index.values_from(&4).collect::<Vec<u8>>(),
Vec::<u8>::new()
);
map_index.remove(&1u8);
assert_eq!(
map_index.iter_from(&0_u8).collect::<Vec<(u8, u8)>>(),
vec![(2, 2), (3, 3)]
);
assert_eq!(
map_index.iter_from(&1u8).collect::<Vec<(u8, u8)>>(),
vec![(2, 2), (3, 3)]
);
}
fn gen_tempdir_name() -> String {
thread_rng().gen_ascii_chars().take(10).collect()
}
mod memorydb_tests {
use std::path::Path;
use storage::{Database, MemoryDB};
use tempdir::TempDir;
fn create_database(_: &Path) -> Box<dyn Database> {
Box::new(MemoryDB::new())
}
#[test]
fn test_iter() {
let dir = TempDir::new(super::gen_tempdir_name().as_str()).unwrap();
let path = dir.path();
let db = create_database(path);
super::iter(db);
}
}
mod rocksdb_tests {
use std::path::Path;
use storage::Database;
use tempdir::TempDir;
fn create_database(path: &Path) -> Box<dyn Database> {
use storage::{DbOptions, RocksDB};
let opts = DbOptions::default();
Box::new(RocksDB::open(path, &opts).unwrap())
}
#[test]
fn test_iter() {
let dir = TempDir::new(super::gen_tempdir_name().as_str()).unwrap();
let path = dir.path();
let db = create_database(path);
super::iter(db);
}
}
}
| 28.389338 | 102 | 0.535481 |
76c6f78e633b2471f7ff19cf5100f7d0dd79f8b1 | 10,236 | #![allow(non_snake_case, non_upper_case_globals)]
#![allow(non_camel_case_types)]
//! BSEC2
//!
//! Used by: stm32mp153, stm32mp157
#[cfg(not(feature = "nosync"))]
pub use crate::stm32mp::peripherals::bsec::Instance;
pub use crate::stm32mp::peripherals::bsec::{RegisterBlock, ResetValues};
pub use crate::stm32mp::peripherals::bsec::{
BSEC_DENABLE, BSEC_HWCFGR, BSEC_IPIDR, BSEC_JTAGIN, BSEC_JTAGOUT, BSEC_OTP_CONFIG,
BSEC_OTP_CONTROL, BSEC_OTP_DATA0, BSEC_OTP_DATA1, BSEC_OTP_DATA10, BSEC_OTP_DATA11,
BSEC_OTP_DATA12, BSEC_OTP_DATA13, BSEC_OTP_DATA14, BSEC_OTP_DATA15, BSEC_OTP_DATA16,
BSEC_OTP_DATA17, BSEC_OTP_DATA18, BSEC_OTP_DATA19, BSEC_OTP_DATA2, BSEC_OTP_DATA20,
BSEC_OTP_DATA21, BSEC_OTP_DATA22, BSEC_OTP_DATA23, BSEC_OTP_DATA24, BSEC_OTP_DATA25,
BSEC_OTP_DATA26, BSEC_OTP_DATA27, BSEC_OTP_DATA28, BSEC_OTP_DATA29, BSEC_OTP_DATA3,
BSEC_OTP_DATA30, BSEC_OTP_DATA31, BSEC_OTP_DATA32, BSEC_OTP_DATA33, BSEC_OTP_DATA34,
BSEC_OTP_DATA35, BSEC_OTP_DATA36, BSEC_OTP_DATA37, BSEC_OTP_DATA38, BSEC_OTP_DATA39,
BSEC_OTP_DATA4, BSEC_OTP_DATA40, BSEC_OTP_DATA41, BSEC_OTP_DATA42, BSEC_OTP_DATA43,
BSEC_OTP_DATA44, BSEC_OTP_DATA45, BSEC_OTP_DATA46, BSEC_OTP_DATA47, BSEC_OTP_DATA48,
BSEC_OTP_DATA49, BSEC_OTP_DATA5, BSEC_OTP_DATA50, BSEC_OTP_DATA51, BSEC_OTP_DATA52,
BSEC_OTP_DATA53, BSEC_OTP_DATA54, BSEC_OTP_DATA55, BSEC_OTP_DATA56, BSEC_OTP_DATA57,
BSEC_OTP_DATA58, BSEC_OTP_DATA59, BSEC_OTP_DATA6, BSEC_OTP_DATA60, BSEC_OTP_DATA61,
BSEC_OTP_DATA62, BSEC_OTP_DATA63, BSEC_OTP_DATA64, BSEC_OTP_DATA65, BSEC_OTP_DATA66,
BSEC_OTP_DATA67, BSEC_OTP_DATA68, BSEC_OTP_DATA69, BSEC_OTP_DATA7, BSEC_OTP_DATA70,
BSEC_OTP_DATA71, BSEC_OTP_DATA72, BSEC_OTP_DATA73, BSEC_OTP_DATA74, BSEC_OTP_DATA75,
BSEC_OTP_DATA76, BSEC_OTP_DATA77, BSEC_OTP_DATA78, BSEC_OTP_DATA79, BSEC_OTP_DATA8,
BSEC_OTP_DATA80, BSEC_OTP_DATA81, BSEC_OTP_DATA82, BSEC_OTP_DATA83, BSEC_OTP_DATA84,
BSEC_OTP_DATA85, BSEC_OTP_DATA86, BSEC_OTP_DATA87, BSEC_OTP_DATA88, BSEC_OTP_DATA89,
BSEC_OTP_DATA9, BSEC_OTP_DATA90, BSEC_OTP_DATA91, BSEC_OTP_DATA92, BSEC_OTP_DATA93,
BSEC_OTP_DATA94, BSEC_OTP_DATA95, BSEC_OTP_DISTURBED0, BSEC_OTP_DISTURBED1,
BSEC_OTP_DISTURBED2, BSEC_OTP_ERROR0, BSEC_OTP_ERROR1, BSEC_OTP_ERROR2, BSEC_OTP_LOCK,
BSEC_OTP_SPLOCK0, BSEC_OTP_SPLOCK1, BSEC_OTP_SPLOCK2, BSEC_OTP_SRLOCK0, BSEC_OTP_SRLOCK1,
BSEC_OTP_SRLOCK2, BSEC_OTP_STATUS, BSEC_OTP_SWLOCK0, BSEC_OTP_SWLOCK1, BSEC_OTP_SWLOCK2,
BSEC_OTP_WRDATA, BSEC_OTP_WRLOCK0, BSEC_OTP_WRLOCK1, BSEC_OTP_WRLOCK2, BSEC_SCRATCH, BSEC_SIDR,
BSEC_VERR,
};
/// Access functions for the BSEC peripheral instance
pub mod BSEC {
use super::ResetValues;
#[cfg(not(feature = "nosync"))]
use super::Instance;
#[cfg(not(feature = "nosync"))]
const INSTANCE: Instance = Instance {
addr: 0x5c005000,
_marker: ::core::marker::PhantomData,
};
/// Reset values for each field in BSEC
pub const reset: ResetValues = ResetValues {
BSEC_OTP_CONFIG: 0x0000000E,
BSEC_OTP_CONTROL: 0x00000000,
BSEC_OTP_WRDATA: 0x00000000,
BSEC_OTP_STATUS: 0x00000000,
BSEC_OTP_LOCK: 0x00000000,
BSEC_DENABLE: 0x00000000,
BSEC_OTP_DISTURBED0: 0x00000000,
BSEC_OTP_DISTURBED1: 0x00000000,
BSEC_OTP_DISTURBED2: 0x00000000,
BSEC_OTP_ERROR0: 0x00000000,
BSEC_OTP_ERROR1: 0x00000000,
BSEC_OTP_ERROR2: 0x00000000,
BSEC_OTP_WRLOCK0: 0x00000000,
BSEC_OTP_WRLOCK1: 0x00000000,
BSEC_OTP_WRLOCK2: 0x00000000,
BSEC_OTP_SPLOCK0: 0x00000000,
BSEC_OTP_SPLOCK1: 0x00000000,
BSEC_OTP_SPLOCK2: 0x00000000,
BSEC_OTP_SWLOCK0: 0x00000001,
BSEC_OTP_SWLOCK1: 0x00000001,
BSEC_OTP_SWLOCK2: 0x00000001,
BSEC_OTP_SRLOCK0: 0x00000000,
BSEC_OTP_SRLOCK1: 0x00000000,
BSEC_OTP_SRLOCK2: 0x00000000,
BSEC_JTAGIN: 0x00000000,
BSEC_JTAGOUT: 0x00000000,
BSEC_SCRATCH: 0x00000000,
BSEC_OTP_DATA0: 0x00000000,
BSEC_OTP_DATA1: 0x00000000,
BSEC_OTP_DATA2: 0x00000000,
BSEC_OTP_DATA3: 0x00000000,
BSEC_OTP_DATA4: 0x00000000,
BSEC_OTP_DATA5: 0x00000000,
BSEC_OTP_DATA6: 0x00000000,
BSEC_OTP_DATA7: 0x00000000,
BSEC_OTP_DATA8: 0x00000000,
BSEC_OTP_DATA9: 0x00000000,
BSEC_OTP_DATA10: 0x00000000,
BSEC_OTP_DATA11: 0x00000000,
BSEC_OTP_DATA12: 0x00000000,
BSEC_OTP_DATA13: 0x00000000,
BSEC_OTP_DATA14: 0x00000000,
BSEC_OTP_DATA15: 0x00000000,
BSEC_OTP_DATA16: 0x00000000,
BSEC_OTP_DATA17: 0x00000000,
BSEC_OTP_DATA18: 0x00000000,
BSEC_OTP_DATA19: 0x00000000,
BSEC_OTP_DATA20: 0x00000000,
BSEC_OTP_DATA21: 0x00000000,
BSEC_OTP_DATA22: 0x00000000,
BSEC_OTP_DATA23: 0x00000000,
BSEC_OTP_DATA24: 0x00000000,
BSEC_OTP_DATA25: 0x00000000,
BSEC_OTP_DATA26: 0x00000000,
BSEC_OTP_DATA27: 0x00000000,
BSEC_OTP_DATA28: 0x00000000,
BSEC_OTP_DATA29: 0x00000000,
BSEC_OTP_DATA30: 0x00000000,
BSEC_OTP_DATA31: 0x00000000,
BSEC_OTP_DATA32: 0x00000000,
BSEC_OTP_DATA33: 0x00000000,
BSEC_OTP_DATA34: 0x00000000,
BSEC_OTP_DATA35: 0x00000000,
BSEC_OTP_DATA36: 0x00000000,
BSEC_OTP_DATA37: 0x00000000,
BSEC_OTP_DATA38: 0x00000000,
BSEC_OTP_DATA39: 0x00000000,
BSEC_OTP_DATA40: 0x00000000,
BSEC_OTP_DATA41: 0x00000000,
BSEC_OTP_DATA42: 0x00000000,
BSEC_OTP_DATA43: 0x00000000,
BSEC_OTP_DATA44: 0x00000000,
BSEC_OTP_DATA45: 0x00000000,
BSEC_OTP_DATA46: 0x00000000,
BSEC_OTP_DATA47: 0x00000000,
BSEC_OTP_DATA48: 0x00000000,
BSEC_OTP_DATA49: 0x00000000,
BSEC_OTP_DATA50: 0x00000000,
BSEC_OTP_DATA51: 0x00000000,
BSEC_OTP_DATA52: 0x00000000,
BSEC_OTP_DATA53: 0x00000000,
BSEC_OTP_DATA54: 0x00000000,
BSEC_OTP_DATA55: 0x00000000,
BSEC_OTP_DATA56: 0x00000000,
BSEC_OTP_DATA57: 0x00000000,
BSEC_OTP_DATA58: 0x00000000,
BSEC_OTP_DATA59: 0x00000000,
BSEC_OTP_DATA60: 0x00000000,
BSEC_OTP_DATA61: 0x00000000,
BSEC_OTP_DATA62: 0x00000000,
BSEC_OTP_DATA63: 0x00000000,
BSEC_OTP_DATA64: 0x00000000,
BSEC_OTP_DATA65: 0x00000000,
BSEC_OTP_DATA66: 0x00000000,
BSEC_OTP_DATA67: 0x00000000,
BSEC_OTP_DATA68: 0x00000000,
BSEC_OTP_DATA69: 0x00000000,
BSEC_OTP_DATA70: 0x00000000,
BSEC_OTP_DATA71: 0x00000000,
BSEC_OTP_DATA72: 0x00000000,
BSEC_OTP_DATA73: 0x00000000,
BSEC_OTP_DATA74: 0x00000000,
BSEC_OTP_DATA75: 0x00000000,
BSEC_OTP_DATA76: 0x00000000,
BSEC_OTP_DATA77: 0x00000000,
BSEC_OTP_DATA78: 0x00000000,
BSEC_OTP_DATA79: 0x00000000,
BSEC_OTP_DATA80: 0x00000000,
BSEC_OTP_DATA81: 0x00000000,
BSEC_OTP_DATA82: 0x00000000,
BSEC_OTP_DATA83: 0x00000000,
BSEC_OTP_DATA84: 0x00000000,
BSEC_OTP_DATA85: 0x00000000,
BSEC_OTP_DATA86: 0x00000000,
BSEC_OTP_DATA87: 0x00000000,
BSEC_OTP_DATA88: 0x00000000,
BSEC_OTP_DATA89: 0x00000000,
BSEC_OTP_DATA90: 0x00000000,
BSEC_OTP_DATA91: 0x00000000,
BSEC_OTP_DATA92: 0x00000000,
BSEC_OTP_DATA93: 0x00000000,
BSEC_OTP_DATA94: 0x00000000,
BSEC_OTP_DATA95: 0x00000000,
BSEC_HWCFGR: 0x00000014,
BSEC_VERR: 0x00000011,
BSEC_IPIDR: 0x00100032,
BSEC_SIDR: 0xA3C5DD04,
};
#[cfg(not(feature = "nosync"))]
#[allow(renamed_and_removed_lints)]
#[allow(private_no_mangle_statics)]
#[no_mangle]
static mut BSEC_TAKEN: bool = false;
/// Safe access to BSEC
///
/// This function returns `Some(Instance)` if this instance is not
/// currently taken, and `None` if it is. This ensures that if you
/// do get `Some(Instance)`, you are ensured unique access to
/// the peripheral and there cannot be data races (unless other
/// code uses `unsafe`, of course). You can then pass the
/// `Instance` around to other functions as required. When you're
/// done with it, you can call `release(instance)` to return it.
///
/// `Instance` itself dereferences to a `RegisterBlock`, which
/// provides access to the peripheral's registers.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn take() -> Option<Instance> {
external_cortex_m::interrupt::free(|_| unsafe {
if BSEC_TAKEN {
None
} else {
BSEC_TAKEN = true;
Some(INSTANCE)
}
})
}
/// Release exclusive access to BSEC
///
/// This function allows you to return an `Instance` so that it
/// is available to `take()` again. This function will panic if
/// you return a different `Instance` or if this instance is not
/// already taken.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn release(inst: Instance) {
external_cortex_m::interrupt::free(|_| unsafe {
if BSEC_TAKEN && inst.addr == INSTANCE.addr {
BSEC_TAKEN = false;
} else {
panic!("Released a peripheral which was not taken");
}
});
}
/// Unsafely steal BSEC
///
/// This function is similar to take() but forcibly takes the
/// Instance, marking it as taken irregardless of its previous
/// state.
#[cfg(not(feature = "nosync"))]
#[inline]
pub unsafe fn steal() -> Instance {
BSEC_TAKEN = true;
INSTANCE
}
}
/// Raw pointer to BSEC
///
/// Dereferencing this is unsafe because you are not ensured unique
/// access to the peripheral, so you may encounter data races with
/// other users of this peripheral. It is up to you to ensure you
/// will not cause data races.
///
/// This constant is provided for ease of use in unsafe code: you can
/// simply call for example `write_reg!(gpio, GPIOA, ODR, 1);`.
pub const BSEC: *const RegisterBlock = 0x5c005000 as *const _;
| 40.141176 | 99 | 0.693142 |
0ef56c7c42e7a8d01ade8b8949361078dea7d516 | 591 | use reqwest::Url;
use structopt::StructOpt;
#[derive(StructOpt)]
pub struct HostAddr {
/// node API address. Must always have `http://` or `https://` prefix.
/// E.g. `-h http://127.0.0.1`, `--host https://node.com:8443/cardano/api`
#[structopt(short, long)]
host: Url,
}
impl HostAddr {
pub fn with_segments(mut self, segments: &[&str]) -> Self {
self.host
.path_segments_mut()
.expect("Host address can't be used as base")
.extend(segments);
self
}
pub fn into_url(self) -> Url {
self.host
}
}
| 23.64 | 78 | 0.566836 |
ddf8a58ace243be5b9f01f9aa8891242d3f361c3 | 1,864 | use std::path::Path;
use anyhow::{anyhow, bail, Result};
use log::info;
use super::{cve, SOURCE_NAME};
use crate::db::{self, Pool};
pub fn run(pool: &Pool, year: &str, data_path: &Path, fresh: bool) -> Result<u32> {
let (_, mut cve_list) = cve::setup(year, data_path, fresh).map_err(|err| anyhow!(err))?;
let database = db::Database(pool.get()?);
info!("connected to database, importing records ...");
let mut num_imported = 0;
for item in &mut cve_list.items {
let json = serde_json::to_string(item)?;
let object_id = match database
.create_object_if_not_exist(db::models::NewObject::with(item.id().into(), json))
{
Err(e) => bail!(e),
Ok(id) => id,
};
let mut refs = db::models::References::default();
for data in &item.cve.references.reference_data {
refs.push(db::models::Reference {
url: data.url.clone(),
tags: data.tags.clone(),
})
}
for product in item.collect_unique_products() {
let new_cve = db::models::NewCVE::with(
SOURCE_NAME.into(),
product.vendor,
product.product,
item.id().into(),
item.summary().into(),
item.score(),
item.severity().into(),
Some(item.vector().into()),
refs.clone(),
Some(object_id),
);
match database.create_cve_if_not_exist(new_cve) {
Err(e) => bail!(e),
Ok(true) => num_imported += 1,
Ok(false) => {}
}
if num_imported > 0 && num_imported % 100 == 0 {
info!("imported {} records ...", num_imported);
}
}
}
Ok(num_imported)
}
| 29.587302 | 92 | 0.498927 |
f7be4f58dfb577e2bcd55f473f66695e160dd580 | 182,176 | // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Rustdoc's HTML Rendering module
//!
//! This modules contains the bulk of the logic necessary for rendering a
//! rustdoc `clean::Crate` instance to a set of static HTML pages. This
//! rendering process is largely driven by the `format!` syntax extension to
//! perform all I/O into files and streams.
//!
//! The rendering process is largely driven by the `Context` and `Cache`
//! structures. The cache is pre-populated by crawling the crate in question,
//! and then it is shared among the various rendering threads. The cache is meant
//! to be a fairly large structure not implementing `Clone` (because it's shared
//! among threads). The context, however, should be a lightweight structure. This
//! is cloned per-thread and contains information about what is currently being
//! rendered.
//!
//! In order to speed up rendering (mostly because of markdown rendering), the
//! rendering process has been parallelized. This parallelization is only
//! exposed through the `crate` method on the context, and then also from the
//! fact that the shared cache is stored in TLS (and must be accessed as such).
//!
//! In addition to rendering the crate itself, this module is also responsible
//! for creating the corresponding search index and source file renderings.
//! These threads are not parallelized (they haven't been a bottleneck yet), and
//! both occur before the crate is rendered.
pub use self::ExternalLocation::*;
use std::borrow::Cow;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashSet, VecDeque};
use std::default::Default;
use std::error;
use std::fmt::{self, Display, Formatter, Write as FmtWrite};
use std::fs::{self, File, OpenOptions};
use std::io::prelude::*;
use std::io::{self, BufWriter, BufReader};
use std::iter::repeat;
use std::mem;
use std::path::{PathBuf, Path, Component};
use std::str;
use std::sync::Arc;
use externalfiles::ExternalHtml;
use serialize::json::{ToJson, Json, as_json};
use syntax::ast;
use syntax::codemap::FileName;
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
use rustc::middle::privacy::AccessLevels;
use rustc::middle::stability;
use rustc::hir;
use rustc::util::nodemap::{FxHashMap, FxHashSet};
use rustc_data_structures::flock;
use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
use doctree;
use fold::DocFolder;
use html::escape::Escape;
use html::format::{AsyncSpace, ConstnessSpace};
use html::format::{GenericBounds, WhereClause, href, AbiSpace};
use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
use html::format::fmt_impl_for_trait_page;
use html::item_type::ItemType;
use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
use html::{highlight, layout};
use minifier;
/// A pair of name and its optional document.
pub type NameDoc = (String, Option<String>);
/// Major driving force in all rustdoc rendering. This contains information
/// about where in the tree-like hierarchy rendering is occurring and controls
/// how the current page is being rendered.
///
/// It is intended that this context is a lightweight object which can be fairly
/// easily cloned because it is cloned per work-job (about once per item in the
/// rustdoc tree).
#[derive(Clone)]
pub struct Context {
/// Current hierarchy of components leading down to what's currently being
/// rendered
pub current: Vec<String>,
/// The current destination folder of where HTML artifacts should be placed.
/// This changes as the context descends into the module hierarchy.
pub dst: PathBuf,
/// A flag, which when `true`, will render pages which redirect to the
/// real location of an item. This is used to allow external links to
/// publicly reused items to redirect to the right location.
pub render_redirect_pages: bool,
pub shared: Arc<SharedContext>,
}
pub struct SharedContext {
/// The path to the crate root source minus the file name.
/// Used for simplifying paths to the highlighted source code files.
pub src_root: PathBuf,
/// This describes the layout of each page, and is not modified after
/// creation of the context (contains info like the favicon and added html).
pub layout: layout::Layout,
/// This flag indicates whether `[src]` links should be generated or not. If
/// the source files are present in the html rendering, then this will be
/// `true`.
pub include_sources: bool,
/// The local file sources we've emitted and their respective url-paths.
pub local_sources: FxHashMap<PathBuf, String>,
/// All the passes that were run on this crate.
pub passes: FxHashSet<String>,
/// The base-URL of the issue tracker for when an item has been tagged with
/// an issue number.
pub issue_tracker_base_url: Option<String>,
/// The given user css file which allow to customize the generated
/// documentation theme.
pub css_file_extension: Option<PathBuf>,
/// The directories that have already been created in this doc run. Used to reduce the number
/// of spurious `create_dir_all` calls.
pub created_dirs: RefCell<FxHashSet<PathBuf>>,
/// This flag indicates whether listings of modules (in the side bar and documentation itself)
/// should be ordered alphabetically or in order of appearance (in the source code).
pub sort_modules_alphabetically: bool,
/// Additional themes to be added to the generated docs.
pub themes: Vec<PathBuf>,
/// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
/// "light-v2.css").
pub resource_suffix: String,
}
impl SharedContext {
fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
let mut dirs = self.created_dirs.borrow_mut();
if !dirs.contains(dst) {
fs::create_dir_all(dst)?;
dirs.insert(dst.to_path_buf());
}
Ok(())
}
}
impl SharedContext {
/// Returns whether the `collapse-docs` pass was run on this crate.
pub fn was_collapsed(&self) -> bool {
self.passes.contains("collapse-docs")
}
/// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
/// `collapsed_doc_value` of the given item.
pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
if self.was_collapsed() {
item.collapsed_doc_value().map(|s| s.into())
} else {
item.doc_value().map(|s| s.into())
}
}
}
/// Indicates where an external crate can be found.
pub enum ExternalLocation {
/// Remote URL root of the external crate
Remote(String),
/// This external crate can be found in the local doc/ folder
Local,
/// The external crate could not be found.
Unknown,
}
/// Metadata about implementations for a type or trait.
#[derive(Clone)]
pub struct Impl {
pub impl_item: clean::Item,
}
impl Impl {
fn inner_impl(&self) -> &clean::Impl {
match self.impl_item.inner {
clean::ImplItem(ref impl_) => impl_,
_ => panic!("non-impl item found in impl")
}
}
fn trait_did(&self) -> Option<DefId> {
self.inner_impl().trait_.def_id()
}
}
#[derive(Debug)]
pub struct Error {
file: PathBuf,
error: io::Error,
}
impl error::Error for Error {
fn description(&self) -> &str {
self.error.description()
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "\"{}\": {}", self.file.display(), self.error)
}
}
impl Error {
pub fn new(e: io::Error, file: &Path) -> Error {
Error {
file: file.to_path_buf(),
error: e,
}
}
}
macro_rules! try_none {
($e:expr, $file:expr) => ({
use std::io;
match $e {
Some(e) => e,
None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
$file))
}
})
}
macro_rules! try_err {
($e:expr, $file:expr) => ({
match $e {
Ok(e) => e,
Err(e) => return Err(Error::new(e, $file)),
}
})
}
/// This cache is used to store information about the `clean::Crate` being
/// rendered in order to provide more useful documentation. This contains
/// information like all implementors of a trait, all traits a type implements,
/// documentation for all known traits, etc.
///
/// This structure purposefully does not implement `Clone` because it's intended
/// to be a fairly large and expensive structure to clone. Instead this adheres
/// to `Send` so it may be stored in a `Arc` instance and shared among the various
/// rendering threads.
#[derive(Default)]
pub struct Cache {
/// Mapping of typaram ids to the name of the type parameter. This is used
/// when pretty-printing a type (so pretty printing doesn't have to
/// painfully maintain a context like this)
pub typarams: FxHashMap<DefId, String>,
/// Maps a type id to all known implementations for that type. This is only
/// recognized for intra-crate `ResolvedPath` types, and is used to print
/// out extra documentation on the page of an enum/struct.
///
/// The values of the map are a list of implementations and documentation
/// found on that implementation.
pub impls: FxHashMap<DefId, Vec<Impl>>,
/// Maintains a mapping of local crate node ids to the fully qualified name
/// and "short type description" of that node. This is used when generating
/// URLs when a type is being linked to. External paths are not located in
/// this map because the `External` type itself has all the information
/// necessary.
pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
/// Similar to `paths`, but only holds external paths. This is only used for
/// generating explicit hyperlinks to other crates.
pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
/// Maps local def ids of exported types to fully qualified paths.
/// Unlike 'paths', this mapping ignores any renames that occur
/// due to 'use' statements.
///
/// This map is used when writing out the special 'implementors'
/// javascript file. By using the exact path that the type
/// is declared with, we ensure that each path will be identical
/// to the path used if the corresponding type is inlined. By
/// doing this, we can detect duplicate impls on a trait page, and only display
/// the impl for the inlined type.
pub exact_paths: FxHashMap<DefId, Vec<String>>,
/// This map contains information about all known traits of this crate.
/// Implementations of a crate should inherit the documentation of the
/// parent trait if no extra documentation is specified, and default methods
/// should show up in documentation about trait implementations.
pub traits: FxHashMap<DefId, clean::Trait>,
/// When rendering traits, it's often useful to be able to list all
/// implementors of the trait, and this mapping is exactly, that: a mapping
/// of trait ids to the list of known implementors of the trait
pub implementors: FxHashMap<DefId, Vec<Impl>>,
/// Cache of where external crate documentation can be found.
pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
/// Cache of where documentation for primitives can be found.
pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
// Note that external items for which `doc(hidden)` applies to are shown as
// non-reachable while local items aren't. This is because we're reusing
// the access levels from crateanalysis.
pub access_levels: Arc<AccessLevels<DefId>>,
/// The version of the crate being documented, if given fron the `--crate-version` flag.
pub crate_version: Option<String>,
// Private fields only used when initially crawling a crate to build a cache
stack: Vec<String>,
parent_stack: Vec<DefId>,
parent_is_trait_impl: bool,
search_index: Vec<IndexItem>,
stripped_mod: bool,
deref_trait_did: Option<DefId>,
deref_mut_trait_did: Option<DefId>,
owned_box_did: Option<DefId>,
masked_crates: FxHashSet<CrateNum>,
// In rare case where a structure is defined in one module but implemented
// in another, if the implementing module is parsed before defining module,
// then the fully qualified name of the structure isn't presented in `paths`
// yet when its implementation methods are being indexed. Caches such methods
// and their parent id here and indexes them at the end of crate parsing.
orphan_impl_items: Vec<(DefId, clean::Item)>,
/// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
/// we need the alias element to have an array of items.
aliases: FxHashMap<String, Vec<IndexItem>>,
}
/// Temporary storage for data obtained during `RustdocVisitor::clean()`.
/// Later on moved into `CACHE_KEY`.
#[derive(Default)]
pub struct RenderInfo {
pub inlined: FxHashSet<DefId>,
pub external_paths: ::core::ExternalPaths,
pub external_typarams: FxHashMap<DefId, String>,
pub exact_paths: FxHashMap<DefId, Vec<String>>,
pub deref_trait_did: Option<DefId>,
pub deref_mut_trait_did: Option<DefId>,
pub owned_box_did: Option<DefId>,
}
/// Helper struct to render all source code to HTML pages
struct SourceCollector<'a> {
scx: &'a mut SharedContext,
/// Root destination to place all HTML output into
dst: PathBuf,
}
/// Wrapper struct to render the source code of a file. This will do things like
/// adding line numbers to the left-hand side.
struct Source<'a>(&'a str);
// Helper structs for rendering items/sidebars and carrying along contextual
// information
#[derive(Copy, Clone)]
struct Item<'a> {
cx: &'a Context,
item: &'a clean::Item,
}
struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
/// Struct representing one entry in the JS search index. These are all emitted
/// by hand to a large JS file at the end of cache-creation.
#[derive(Debug)]
struct IndexItem {
ty: ItemType,
name: String,
path: String,
desc: String,
parent: Option<DefId>,
parent_idx: Option<usize>,
search_type: Option<IndexItemFunctionType>,
}
impl ToJson for IndexItem {
fn to_json(&self) -> Json {
assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
let mut data = Vec::with_capacity(6);
data.push((self.ty as usize).to_json());
data.push(self.name.to_json());
data.push(self.path.to_json());
data.push(self.desc.to_json());
data.push(self.parent_idx.to_json());
data.push(self.search_type.to_json());
Json::Array(data)
}
}
/// A type used for the search index.
#[derive(Debug)]
struct Type {
name: Option<String>,
generics: Option<Vec<String>>,
}
impl ToJson for Type {
fn to_json(&self) -> Json {
match self.name {
Some(ref name) => {
let mut data = BTreeMap::new();
data.insert("n".to_owned(), name.to_json());
if let Some(ref generics) = self.generics {
data.insert("g".to_owned(), generics.to_json());
}
Json::Object(data)
},
None => Json::Null
}
}
}
/// Full type of functions/methods in the search index.
#[derive(Debug)]
struct IndexItemFunctionType {
inputs: Vec<Type>,
output: Option<Type>,
}
impl ToJson for IndexItemFunctionType {
fn to_json(&self) -> Json {
// If we couldn't figure out a type, just write `null`.
if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
Json::Null
} else {
let mut data = BTreeMap::new();
if !self.inputs.is_empty() {
data.insert("i".to_owned(), self.inputs.to_json());
}
if let Some(ref output) = self.output {
data.insert("o".to_owned(), output.to_json());
}
Json::Object(data)
}
}
}
thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
fn init_ids() -> FxHashMap<String, usize> {
[
"main",
"search",
"help",
"TOC",
"render-detail",
"associated-types",
"associated-const",
"required-methods",
"provided-methods",
"implementors",
"synthetic-implementors",
"implementors-list",
"synthetic-implementors-list",
"methods",
"deref-methods",
"implementations",
].into_iter().map(|id| (String::from(*id), 1)).collect()
}
/// This method resets the local table of used ID attributes. This is typically
/// used at the beginning of rendering an entire HTML page to reset from the
/// previous state (if any).
pub fn reset_ids(embedded: bool) {
USED_ID_MAP.with(|s| {
*s.borrow_mut() = if embedded {
init_ids()
} else {
FxHashMap()
};
});
}
pub fn derive_id(candidate: String) -> String {
USED_ID_MAP.with(|map| {
let id = match map.borrow_mut().get_mut(&candidate) {
None => candidate,
Some(a) => {
let id = format!("{}-{}", candidate, *a);
*a += 1;
id
}
};
map.borrow_mut().insert(id.clone(), 1);
id
})
}
/// Generates the documentation for `crate` into the directory `dst`
pub fn run(mut krate: clean::Crate,
external_html: &ExternalHtml,
playground_url: Option<String>,
dst: PathBuf,
resource_suffix: String,
passes: FxHashSet<String>,
css_file_extension: Option<PathBuf>,
renderinfo: RenderInfo,
sort_modules_alphabetically: bool,
themes: Vec<PathBuf>,
enable_minification: bool) -> Result<(), Error> {
let src_root = match krate.src {
FileName::Real(ref p) => match p.parent() {
Some(p) => p.to_path_buf(),
None => PathBuf::new(),
},
_ => PathBuf::new(),
};
let mut scx = SharedContext {
src_root,
passes,
include_sources: true,
local_sources: FxHashMap(),
issue_tracker_base_url: None,
layout: layout::Layout {
logo: "".to_string(),
favicon: "".to_string(),
external_html: external_html.clone(),
krate: krate.name.clone(),
},
css_file_extension: css_file_extension.clone(),
created_dirs: RefCell::new(FxHashSet()),
sort_modules_alphabetically,
themes,
resource_suffix,
};
// If user passed in `--playground-url` arg, we fill in crate name here
if let Some(url) = playground_url {
markdown::PLAYGROUND.with(|slot| {
*slot.borrow_mut() = Some((Some(krate.name.clone()), url));
});
}
// Crawl the crate attributes looking for attributes which control how we're
// going to emit HTML
if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
for attr in attrs.lists("doc") {
let name = attr.name().map(|s| s.as_str());
match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
(Some("html_favicon_url"), Some(s)) => {
scx.layout.favicon = s.to_string();
}
(Some("html_logo_url"), Some(s)) => {
scx.layout.logo = s.to_string();
}
(Some("html_playground_url"), Some(s)) => {
markdown::PLAYGROUND.with(|slot| {
let name = krate.name.clone();
*slot.borrow_mut() = Some((Some(name), s.to_string()));
});
}
(Some("issue_tracker_base_url"), Some(s)) => {
scx.issue_tracker_base_url = Some(s.to_string());
}
(Some("html_no_source"), None) if attr.is_word() => {
scx.include_sources = false;
}
_ => {}
}
}
}
try_err!(fs::create_dir_all(&dst), &dst);
krate = render_sources(&dst, &mut scx, krate)?;
let cx = Context {
current: Vec::new(),
dst,
render_redirect_pages: false,
shared: Arc::new(scx),
};
// Crawl the crate to build various caches used for the output
let RenderInfo {
inlined: _,
external_paths,
external_typarams,
exact_paths,
deref_trait_did,
deref_mut_trait_did,
owned_box_did,
} = renderinfo;
let external_paths = external_paths.into_iter()
.map(|(k, (v, t))| (k, (v, ItemType::from(t))))
.collect();
let mut cache = Cache {
impls: FxHashMap(),
external_paths,
exact_paths,
paths: FxHashMap(),
implementors: FxHashMap(),
stack: Vec::new(),
parent_stack: Vec::new(),
search_index: Vec::new(),
parent_is_trait_impl: false,
extern_locations: FxHashMap(),
primitive_locations: FxHashMap(),
stripped_mod: false,
access_levels: krate.access_levels.clone(),
crate_version: krate.version.take(),
orphan_impl_items: Vec::new(),
traits: mem::replace(&mut krate.external_traits, FxHashMap()),
deref_trait_did,
deref_mut_trait_did,
owned_box_did,
masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
typarams: external_typarams,
aliases: FxHashMap(),
};
// Cache where all our extern crates are located
for &(n, ref e) in &krate.externs {
let src_root = match e.src {
FileName::Real(ref p) => match p.parent() {
Some(p) => p.to_path_buf(),
None => PathBuf::new(),
},
_ => PathBuf::new(),
};
cache.extern_locations.insert(n, (e.name.clone(), src_root,
extern_location(e, &cx.dst)));
let did = DefId { krate: n, index: CRATE_DEF_INDEX };
cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
}
// Cache where all known primitives have their documentation located.
//
// Favor linking to as local extern as possible, so iterate all crates in
// reverse topological order.
for &(_, ref e) in krate.externs.iter().rev() {
for &(def_id, prim, _) in &e.primitives {
cache.primitive_locations.insert(prim, def_id);
}
}
for &(def_id, prim, _) in &krate.primitives {
cache.primitive_locations.insert(prim, def_id);
}
cache.stack.push(krate.name.clone());
krate = cache.fold_crate(krate);
// Build our search index
let index = build_index(&krate, &mut cache);
// Freeze the cache now that the index has been built. Put an Arc into TLS
// for future parallelization opportunities
let cache = Arc::new(cache);
CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
write_shared(&cx, &krate, &*cache, index, enable_minification)?;
// And finally render the whole crate's documentation
cx.krate(krate)
}
/// Build the search index from the collected metadata
fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
let mut nodeid_to_pathid = FxHashMap();
let mut crate_items = Vec::with_capacity(cache.search_index.len());
let mut crate_paths = Vec::<Json>::new();
let Cache { ref mut search_index,
ref orphan_impl_items,
ref mut paths, .. } = *cache;
// Attach all orphan items to the type's definition if the type
// has since been learned.
for &(did, ref item) in orphan_impl_items {
if let Some(&(ref fqp, _)) = paths.get(&did) {
search_index.push(IndexItem {
ty: item.type_(),
name: item.name.clone().unwrap(),
path: fqp[..fqp.len() - 1].join("::"),
desc: plain_summary_line(item.doc_value()),
parent: Some(did),
parent_idx: None,
search_type: get_index_search_type(&item),
});
}
}
// Reduce `NodeId` in paths into smaller sequential numbers,
// and prune the paths that do not appear in the index.
let mut lastpath = String::new();
let mut lastpathid = 0usize;
for item in search_index {
item.parent_idx = item.parent.map(|nodeid| {
if nodeid_to_pathid.contains_key(&nodeid) {
*nodeid_to_pathid.get(&nodeid).unwrap()
} else {
let pathid = lastpathid;
nodeid_to_pathid.insert(nodeid, pathid);
lastpathid += 1;
let &(ref fqp, short) = paths.get(&nodeid).unwrap();
crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
pathid
}
});
// Omit the parent path if it is same to that of the prior item.
if lastpath == item.path {
item.path.clear();
} else {
lastpath = item.path.clone();
}
crate_items.push(item.to_json());
}
let crate_doc = krate.module.as_ref().map(|module| {
plain_summary_line(module.doc_value())
}).unwrap_or(String::new());
let mut crate_data = BTreeMap::new();
crate_data.insert("doc".to_owned(), Json::String(crate_doc));
crate_data.insert("items".to_owned(), Json::Array(crate_items));
crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
// Collect the index into a string
format!("searchIndex[{}] = {};",
as_json(&krate.name),
Json::Object(crate_data))
}
fn write_shared(cx: &Context,
krate: &clean::Crate,
cache: &Cache,
search_index: String,
enable_minification: bool) -> Result<(), Error> {
// Write out the shared files. Note that these are shared among all rustdoc
// docs placed in the output directory, so this needs to be a synchronized
// operation with respect to all other rustdocs running around.
let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
// Add all the static files. These may already exist, but we just
// overwrite them anyway to make sure that they're fresh and up-to-date.
write(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
include_bytes!("static/rustdoc.css"))?;
write(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
include_bytes!("static/settings.css"))?;
// To avoid "light.css" to be overwritten, we'll first run over the received themes and only
// then we'll run over the "official" styles.
let mut themes: HashSet<String> = HashSet::new();
for entry in &cx.shared.themes {
let mut content = Vec::with_capacity(100000);
let mut f = try_err!(File::open(&entry), &entry);
try_err!(f.read_to_end(&mut content), &entry);
let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
content.as_slice())?;
themes.insert(theme.to_owned());
}
write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
include_bytes!("static/brush.svg"))?;
write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
include_bytes!("static/wheel.svg"))?;
write(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
include_bytes!("static/themes/light.css"))?;
themes.insert("light".to_owned());
write(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
include_bytes!("static/themes/dark.css"))?;
themes.insert("dark".to_owned());
let mut themes: Vec<&String> = themes.iter().collect();
themes.sort();
// To avoid theme switch latencies as much as possible, we put everything theme related
// at the beginning of the html files into another js file.
write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
format!(
r#"var themes = document.getElementById("theme-choices");
var themePicker = document.getElementById("theme-picker");
function switchThemeButtonState() {{
if (themes.style.display === "block") {{
themes.style.display = "none";
themePicker.style.borderBottomRightRadius = "3px";
themePicker.style.borderBottomLeftRadius = "3px";
}} else {{
themes.style.display = "block";
themePicker.style.borderBottomRightRadius = "0";
themePicker.style.borderBottomLeftRadius = "0";
}}
}};
function handleThemeButtonsBlur(e) {{
var active = document.activeElement;
var related = e.relatedTarget;
if (active.id !== "themePicker" &&
(!active.parentNode || active.parentNode.id !== "theme-choices") &&
(!related ||
(related.id !== "themePicker" &&
(!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
switchThemeButtonState();
}}
}}
themePicker.onclick = switchThemeButtonState;
themePicker.onblur = handleThemeButtonsBlur;
[{}].forEach(function(item) {{
var but = document.createElement('button');
but.innerHTML = item;
but.onclick = function(el) {{
switchTheme(currentTheme, mainTheme, item);
}};
but.onblur = handleThemeButtonsBlur;
themes.appendChild(but);
}});"#,
themes.iter()
.map(|s| format!("\"{}\"", s))
.collect::<Vec<String>>()
.join(",")).as_bytes(),
)?;
write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
include_str!("static/main.js"),
enable_minification)?;
write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
include_str!("static/settings.js"),
enable_minification)?;
{
let mut data = format!("var resourcesSuffix = \"{}\";\n",
cx.shared.resource_suffix);
data.push_str(include_str!("static/storage.js"));
write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
&data,
enable_minification)?;
}
if let Some(ref css) = cx.shared.css_file_extension {
let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
try_err!(fs::copy(css, out), css);
}
write(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
include_bytes!("static/normalize.css"))?;
write(cx.dst.join("FiraSans-Regular.woff"),
include_bytes!("static/FiraSans-Regular.woff"))?;
write(cx.dst.join("FiraSans-Medium.woff"),
include_bytes!("static/FiraSans-Medium.woff"))?;
write(cx.dst.join("FiraSans-LICENSE.txt"),
include_bytes!("static/FiraSans-LICENSE.txt"))?;
write(cx.dst.join("Heuristica-Italic.woff"),
include_bytes!("static/Heuristica-Italic.woff"))?;
write(cx.dst.join("Heuristica-LICENSE.txt"),
include_bytes!("static/Heuristica-LICENSE.txt"))?;
write(cx.dst.join("SourceSerifPro-Regular.woff"),
include_bytes!("static/SourceSerifPro-Regular.woff"))?;
write(cx.dst.join("SourceSerifPro-Bold.woff"),
include_bytes!("static/SourceSerifPro-Bold.woff"))?;
write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
write(cx.dst.join("SourceCodePro-Regular.woff"),
include_bytes!("static/SourceCodePro-Regular.woff"))?;
write(cx.dst.join("SourceCodePro-Semibold.woff"),
include_bytes!("static/SourceCodePro-Semibold.woff"))?;
write(cx.dst.join("SourceCodePro-LICENSE.txt"),
include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
write(cx.dst.join("LICENSE-MIT.txt"),
include_bytes!("static/LICENSE-MIT.txt"))?;
write(cx.dst.join("LICENSE-APACHE.txt"),
include_bytes!("static/LICENSE-APACHE.txt"))?;
write(cx.dst.join("COPYRIGHT.txt"),
include_bytes!("static/COPYRIGHT.txt"))?;
fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
let mut ret = Vec::new();
if path.exists() {
for line in BufReader::new(File::open(path)?).lines() {
let line = line?;
if !line.starts_with(key) {
continue;
}
if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
continue;
}
ret.push(line.to_string());
}
}
Ok(ret)
}
fn show_item(item: &IndexItem, krate: &str) -> String {
format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
if let Some(p) = item.parent_idx {
format!(",'parent':{}", p)
} else {
String::new()
})
}
let dst = cx.dst.join("aliases.js");
{
let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
let mut w = try_err!(File::create(&dst), &dst);
let mut output = String::with_capacity(100);
for (alias, items) in &cache.aliases {
if items.is_empty() {
continue
}
output.push_str(&format!("\"{}\":[{}],",
alias,
items.iter()
.map(|v| show_item(v, &krate.name))
.collect::<Vec<_>>()
.join(",")));
}
all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
all_aliases.sort();
try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
for aliases in &all_aliases {
try_err!(writeln!(&mut w, "{}", aliases), &dst);
}
}
// Update the search index
let dst = cx.dst.join("search-index.js");
let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
all_indexes.push(search_index);
// Sort the indexes by crate so the file will be generated identically even
// with rustdoc running in parallel.
all_indexes.sort();
let mut w = try_err!(File::create(&dst), &dst);
try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
for index in &all_indexes {
try_err!(writeln!(&mut w, "{}", *index), &dst);
}
try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
// Update the list of all implementors for traits
let dst = cx.dst.join("implementors");
for (&did, imps) in &cache.implementors {
// Private modules can leak through to this phase of rustdoc, which
// could contain implementations for otherwise private types. In some
// rare cases we could find an implementation for an item which wasn't
// indexed, so we just skip this step in that case.
//
// FIXME: this is a vague explanation for why this can't be a `get`, in
// theory it should be...
let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
Some(p) => p,
None => match cache.external_paths.get(&did) {
Some(p) => p,
None => continue,
}
};
let mut have_impls = false;
let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
for imp in imps {
// If the trait and implementation are in the same crate, then
// there's no need to emit information about it (there's inlining
// going on). If they're in different crates then the crate defining
// the trait will be interested in our implementation.
if imp.impl_item.def_id.krate == did.krate { continue }
// If the implementation is from another crate then that crate
// should add it.
if !imp.impl_item.def_id.is_local() { continue }
have_impls = true;
write!(implementors, "{{text:{},synthetic:{},types:{}}},",
as_json(&imp.inner_impl().to_string()),
imp.inner_impl().synthetic,
as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
}
implementors.push_str("];");
// Only create a js file if we have impls to add to it. If the trait is
// documented locally though we always create the file to avoid dead
// links.
if !have_impls && !cache.paths.contains_key(&did) {
continue;
}
let mut mydst = dst.clone();
for part in &remote_path[..remote_path.len() - 1] {
mydst.push(part);
}
try_err!(fs::create_dir_all(&mydst), &mydst);
mydst.push(&format!("{}.{}.js",
remote_item_type.css_class(),
remote_path[remote_path.len() - 1]));
let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
all_implementors.push(implementors);
// Sort the implementors by crate so the file will be generated
// identically even with rustdoc running in parallel.
all_implementors.sort();
let mut f = try_err!(File::create(&mydst), &mydst);
try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
for implementor in &all_implementors {
try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
}
try_err!(writeln!(&mut f, "{}", r"
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
"), &mydst);
try_err!(writeln!(&mut f, r"}})()"), &mydst);
}
Ok(())
}
fn render_sources(dst: &Path, scx: &mut SharedContext,
krate: clean::Crate) -> Result<clean::Crate, Error> {
info!("emitting source files");
let dst = dst.join("src").join(&krate.name);
try_err!(fs::create_dir_all(&dst), &dst);
let mut folder = SourceCollector {
dst,
scx,
};
Ok(folder.fold_crate(krate))
}
/// Writes the entire contents of a string to a destination, not attempting to
/// catch any errors.
fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
Ok(try_err!(fs::write(&dst, contents), &dst))
}
fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
if enable_minification {
write(dst, minifier::js::minify(contents).as_bytes())
} else {
write(dst, contents.as_bytes())
}
}
/// Takes a path to a source file and cleans the path to it. This canonicalizes
/// things like ".." to components which preserve the "top down" hierarchy of a
/// static HTML tree. Each component in the cleaned path will be passed as an
/// argument to `f`. The very last component of the path (ie the file name) will
/// be passed to `f` if `keep_filename` is true, and ignored otherwise.
// FIXME (#9639): The closure should deal with &[u8] instead of &str
// FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
F: FnMut(&str),
{
// make it relative, if possible
let p = p.strip_prefix(src_root).unwrap_or(p);
let mut iter = p.components().peekable();
while let Some(c) = iter.next() {
if !keep_filename && iter.peek().is_none() {
break;
}
match c {
Component::ParentDir => f("up"),
Component::Normal(c) => f(c.to_str().unwrap()),
_ => continue,
}
}
}
/// Attempts to find where an external crate is located, given that we're
/// rendering in to the specified source destination.
fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
// See if there's documentation generated into the local directory
let local_location = dst.join(&e.name);
if local_location.is_dir() {
return Local;
}
// Failing that, see if there's an attribute specifying where to find this
// external crate
e.attrs.lists("doc")
.filter(|a| a.check_name("html_root_url"))
.filter_map(|a| a.value_str())
.map(|url| {
let mut url = url.to_string();
if !url.ends_with("/") {
url.push('/')
}
Remote(url)
}).next().unwrap_or(Unknown) // Well, at least we tried.
}
impl<'a> DocFolder for SourceCollector<'a> {
fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
// If we're including source files, and we haven't seen this file yet,
// then we need to render it out to the filesystem.
if self.scx.include_sources
// skip all invalid or macro spans
&& item.source.filename.is_real()
// skip non-local items
&& item.def_id.is_local() {
// If it turns out that we couldn't read this file, then we probably
// can't read any of the files (generating html output from json or
// something like that), so just don't include sources for the
// entire crate. The other option is maintaining this mapping on a
// per-file basis, but that's probably not worth it...
self.scx
.include_sources = match self.emit_source(&item.source.filename) {
Ok(()) => true,
Err(e) => {
println!("warning: source code was requested to be rendered, \
but processing `{}` had an error: {}",
item.source.filename, e);
println!(" skipping rendering of source code");
false
}
};
}
self.fold_item_recur(item)
}
}
impl<'a> SourceCollector<'a> {
/// Renders the given filename into its corresponding HTML source file.
fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
let p = match *filename {
FileName::Real(ref file) => file,
_ => return Ok(()),
};
if self.scx.local_sources.contains_key(&**p) {
// We've already emitted this source
return Ok(());
}
let contents = fs::read_to_string(&p)?;
// Remove the utf-8 BOM if any
let contents = if contents.starts_with("\u{feff}") {
&contents[3..]
} else {
&contents[..]
};
// Create the intermediate directories
let mut cur = self.dst.clone();
let mut root_path = String::from("../../");
let mut href = String::new();
clean_srcpath(&self.scx.src_root, &p, false, |component| {
cur.push(component);
fs::create_dir_all(&cur).unwrap();
root_path.push_str("../");
href.push_str(component);
href.push('/');
});
let mut fname = p.file_name()
.expect("source has no filename")
.to_os_string();
fname.push(".html");
cur.push(&fname);
href.push_str(&fname.to_string_lossy());
let mut w = BufWriter::new(File::create(&cur)?);
let title = format!("{} -- source", cur.file_name().unwrap()
.to_string_lossy());
let desc = format!("Source to the Rust file `{}`.", filename);
let page = layout::Page {
title: &title,
css_class: "source",
root_path: &root_path,
description: &desc,
keywords: BASIC_KEYWORDS,
resource_suffix: &self.scx.resource_suffix,
};
layout::render(&mut w, &self.scx.layout,
&page, &(""), &Source(contents),
self.scx.css_file_extension.is_some(),
&self.scx.themes)?;
w.flush()?;
self.scx.local_sources.insert(p.clone(), href);
Ok(())
}
}
impl DocFolder for Cache {
fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
// If this is a stripped module,
// we don't want it or its children in the search index.
let orig_stripped_mod = match item.inner {
clean::StrippedItem(box clean::ModuleItem(..)) => {
mem::replace(&mut self.stripped_mod, true)
}
_ => self.stripped_mod,
};
// If the impl is from a masked crate or references something from a
// masked crate then remove it completely.
if let clean::ImplItem(ref i) = item.inner {
if self.masked_crates.contains(&item.def_id.krate) ||
i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
return None;
}
}
// Register any generics to their corresponding string. This is used
// when pretty-printing types.
if let Some(generics) = item.inner.generics() {
self.generics(generics);
}
// Propagate a trait method's documentation to all implementors of the
// trait.
if let clean::TraitItem(ref t) = item.inner {
self.traits.entry(item.def_id).or_insert_with(|| t.clone());
}
// Collect all the implementors of traits.
if let clean::ImplItem(ref i) = item.inner {
if let Some(did) = i.trait_.def_id() {
self.implementors.entry(did).or_insert(vec![]).push(Impl {
impl_item: item.clone(),
});
}
}
// Index this method for searching later on.
if let Some(ref s) = item.name {
let (parent, is_inherent_impl_item) = match item.inner {
clean::StrippedItem(..) => ((None, None), false),
clean::AssociatedConstItem(..) |
clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
// skip associated items in trait impls
((None, None), false)
}
clean::AssociatedTypeItem(..) |
clean::TyMethodItem(..) |
clean::StructFieldItem(..) |
clean::VariantItem(..) => {
((Some(*self.parent_stack.last().unwrap()),
Some(&self.stack[..self.stack.len() - 1])),
false)
}
clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
if self.parent_stack.is_empty() {
((None, None), false)
} else {
let last = self.parent_stack.last().unwrap();
let did = *last;
let path = match self.paths.get(&did) {
// The current stack not necessarily has correlation
// for where the type was defined. On the other
// hand, `paths` always has the right
// information if present.
Some(&(ref fqp, ItemType::Trait)) |
Some(&(ref fqp, ItemType::Struct)) |
Some(&(ref fqp, ItemType::Union)) |
Some(&(ref fqp, ItemType::Enum)) =>
Some(&fqp[..fqp.len() - 1]),
Some(..) => Some(&*self.stack),
None => None
};
((Some(*last), path), true)
}
}
_ => ((None, Some(&*self.stack)), false)
};
match parent {
(parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
debug_assert!(!item.is_stripped());
// A crate has a module at its root, containing all items,
// which should not be indexed. The crate-item itself is
// inserted later on when serializing the search-index.
if item.def_id.index != CRATE_DEF_INDEX {
self.search_index.push(IndexItem {
ty: item.type_(),
name: s.to_string(),
path: path.join("::").to_string(),
desc: plain_summary_line(item.doc_value()),
parent,
parent_idx: None,
search_type: get_index_search_type(&item),
});
}
}
(Some(parent), None) if is_inherent_impl_item => {
// We have a parent, but we don't know where they're
// defined yet. Wait for later to index this item.
self.orphan_impl_items.push((parent, item.clone()));
}
_ => {}
}
}
// Keep track of the fully qualified path for this item.
let pushed = match item.name {
Some(ref n) if !n.is_empty() => {
self.stack.push(n.to_string());
true
}
_ => false,
};
match item.inner {
clean::StructItem(..) | clean::EnumItem(..) |
clean::TypedefItem(..) | clean::TraitItem(..) |
clean::FunctionItem(..) | clean::ModuleItem(..) |
clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
clean::ConstantItem(..) | clean::StaticItem(..) |
clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
if !self.stripped_mod => {
// Re-exported items mean that the same id can show up twice
// in the rustdoc ast that we're looking at. We know,
// however, that a re-exported item doesn't show up in the
// `public_items` map, so we can skip inserting into the
// paths map if there was already an entry present and we're
// not a public item.
if !self.paths.contains_key(&item.def_id) ||
self.access_levels.is_public(item.def_id)
{
self.paths.insert(item.def_id,
(self.stack.clone(), item.type_()));
}
self.add_aliases(&item);
}
// Link variants to their parent enum because pages aren't emitted
// for each variant.
clean::VariantItem(..) if !self.stripped_mod => {
let mut stack = self.stack.clone();
stack.pop();
self.paths.insert(item.def_id, (stack, ItemType::Enum));
}
clean::PrimitiveItem(..) if item.visibility.is_some() => {
self.add_aliases(&item);
self.paths.insert(item.def_id, (self.stack.clone(),
item.type_()));
}
_ => {}
}
// Maintain the parent stack
let orig_parent_is_trait_impl = self.parent_is_trait_impl;
let parent_pushed = match item.inner {
clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
clean::StructItem(..) | clean::UnionItem(..) => {
self.parent_stack.push(item.def_id);
self.parent_is_trait_impl = false;
true
}
clean::ImplItem(ref i) => {
self.parent_is_trait_impl = i.trait_.is_some();
match i.for_ {
clean::ResolvedPath{ did, .. } => {
self.parent_stack.push(did);
true
}
ref t => {
let prim_did = t.primitive_type().and_then(|t| {
self.primitive_locations.get(&t).cloned()
});
match prim_did {
Some(did) => {
self.parent_stack.push(did);
true
}
None => false,
}
}
}
}
_ => false
};
// Once we've recursively found all the generics, hoard off all the
// implementations elsewhere.
let ret = self.fold_item_recur(item).and_then(|item| {
if let clean::Item { inner: clean::ImplItem(_), .. } = item {
// Figure out the id of this impl. This may map to a
// primitive rather than always to a struct/enum.
// Note: matching twice to restrict the lifetime of the `i` borrow.
let mut dids = FxHashSet();
if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
match i.for_ {
clean::ResolvedPath { did, .. } |
clean::BorrowedRef {
type_: box clean::ResolvedPath { did, .. }, ..
} => {
dids.insert(did);
}
ref t => {
let did = t.primitive_type().and_then(|t| {
self.primitive_locations.get(&t).cloned()
});
if let Some(did) = did {
dids.insert(did);
}
}
}
if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
for bound in generics {
if let Some(did) = bound.def_id() {
dids.insert(did);
}
}
}
} else {
unreachable!()
};
for did in dids {
self.impls.entry(did).or_insert(vec![]).push(Impl {
impl_item: item.clone(),
});
}
None
} else {
Some(item)
}
});
if pushed { self.stack.pop().unwrap(); }
if parent_pushed { self.parent_stack.pop().unwrap(); }
self.stripped_mod = orig_stripped_mod;
self.parent_is_trait_impl = orig_parent_is_trait_impl;
ret
}
}
impl<'a> Cache {
fn generics(&mut self, generics: &clean::Generics) {
for param in &generics.params {
match param.kind {
clean::GenericParamDefKind::Lifetime => {}
clean::GenericParamDefKind::Type { did, .. } => {
self.typarams.insert(did, param.name.clone());
}
}
}
}
fn add_aliases(&mut self, item: &clean::Item) {
if item.def_id.index == CRATE_DEF_INDEX {
return
}
if let Some(ref item_name) = item.name {
let path = self.paths.get(&item.def_id)
.map(|p| p.0[..p.0.len() - 1].join("::"))
.unwrap_or("std".to_owned());
for alias in item.attrs.lists("doc")
.filter(|a| a.check_name("alias"))
.filter_map(|a| a.value_str()
.map(|s| s.to_string().replace("\"", "")))
.filter(|v| !v.is_empty())
.collect::<FxHashSet<_>>()
.into_iter() {
self.aliases.entry(alias)
.or_insert(Vec::with_capacity(1))
.push(IndexItem {
ty: item.type_(),
name: item_name.to_string(),
path: path.clone(),
desc: plain_summary_line(item.doc_value()),
parent: None,
parent_idx: None,
search_type: get_index_search_type(&item),
});
}
}
}
}
#[derive(Debug, Eq, PartialEq, Hash)]
struct ItemEntry {
url: String,
name: String,
}
impl ItemEntry {
fn new(mut url: String, name: String) -> ItemEntry {
while url.starts_with('/') {
url.remove(0);
}
ItemEntry {
url,
name,
}
}
}
impl fmt::Display for ItemEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
}
}
impl PartialOrd for ItemEntry {
fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ItemEntry {
fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
self.name.cmp(&other.name)
}
}
#[derive(Debug)]
struct AllTypes {
structs: HashSet<ItemEntry>,
enums: HashSet<ItemEntry>,
unions: HashSet<ItemEntry>,
primitives: HashSet<ItemEntry>,
traits: HashSet<ItemEntry>,
macros: HashSet<ItemEntry>,
functions: HashSet<ItemEntry>,
typedefs: HashSet<ItemEntry>,
statics: HashSet<ItemEntry>,
constants: HashSet<ItemEntry>,
keywords: HashSet<ItemEntry>,
}
impl AllTypes {
fn new() -> AllTypes {
AllTypes {
structs: HashSet::with_capacity(100),
enums: HashSet::with_capacity(100),
unions: HashSet::with_capacity(100),
primitives: HashSet::with_capacity(26),
traits: HashSet::with_capacity(100),
macros: HashSet::with_capacity(100),
functions: HashSet::with_capacity(100),
typedefs: HashSet::with_capacity(100),
statics: HashSet::with_capacity(100),
constants: HashSet::with_capacity(100),
keywords: HashSet::with_capacity(100),
}
}
fn append(&mut self, item_name: String, item_type: &ItemType) {
let mut url: Vec<_> = item_name.split("::").skip(1).collect();
if let Some(name) = url.pop() {
let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
url.push(name);
let name = url.join("::");
match *item_type {
ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
_ => true,
};
}
}
}
fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
class: &str) -> fmt::Result {
if !e.is_empty() {
let mut e: Vec<&ItemEntry> = e.iter().collect();
e.sort();
write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
title,
Escape(title),
class,
e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
}
Ok(())
}
impl fmt::Display for AllTypes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"<h1 class='fqn'>\
<span class='in-band'>List of all items</span>\
<span class='out-of-band'>\
<span id='render-detail'>\
<a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
[<span class='inner'>−</span>]\
</a>\
</span>
</span>
</h1>")?;
print_entries(f, &self.structs, "Structs", "structs")?;
print_entries(f, &self.enums, "Enums", "enums")?;
print_entries(f, &self.unions, "Unions", "unions")?;
print_entries(f, &self.primitives, "Primitives", "primitives")?;
print_entries(f, &self.traits, "Traits", "traits")?;
print_entries(f, &self.macros, "Macros", "macros")?;
print_entries(f, &self.functions, "Functions", "functions")?;
print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
print_entries(f, &self.statics, "Statics", "statics")?;
print_entries(f, &self.constants, "Constants", "constants")
}
}
#[derive(Debug)]
struct Settings<'a> {
// (id, explanation, default value)
settings: Vec<(&'static str, &'static str, bool)>,
root_path: &'a str,
suffix: &'a str,
}
impl<'a> Settings<'a> {
pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
Settings {
settings: vec![
("item-declarations", "Auto-hide item declarations.", true),
("item-attributes", "Auto-hide item attributes.", true),
("go-to-only-result", "Directly go to item in search if there is only one result",
false),
],
root_path,
suffix,
}
}
}
impl<'a> fmt::Display for Settings<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"<h1 class='fqn'>\
<span class='in-band'>Rustdoc settings</span>\
</h1>\
<div class='settings'>{}</div>\
<script src='{}settings{}.js'></script>",
self.settings.iter()
.map(|(id, text, enabled)| {
format!("<div class='setting-line'>\
<label class='toggle'>\
<input type='checkbox' id='{}' {}>\
<span class='slider'></span>\
</label>\
<div>{}</div>\
</div>", id, if *enabled { " checked" } else { "" }, text)
})
.collect::<String>(),
self.root_path,
self.suffix)
}
}
impl Context {
/// String representation of how to get back to the root path of the 'doc/'
/// folder in terms of a relative URL.
fn root_path(&self) -> String {
repeat("../").take(self.current.len()).collect::<String>()
}
/// Recurse in the directory structure and change the "root path" to make
/// sure it always points to the top (relatively).
fn recurse<T, F>(&mut self, s: String, f: F) -> T where
F: FnOnce(&mut Context) -> T,
{
if s.is_empty() {
panic!("Unexpected empty destination: {:?}", self.current);
}
let prev = self.dst.clone();
self.dst.push(&s);
self.current.push(s);
info!("Recursing into {}", self.dst.display());
let ret = f(self);
info!("Recursed; leaving {}", self.dst.display());
// Go back to where we were at
self.dst = prev;
self.current.pop().unwrap();
ret
}
/// Main method for rendering a crate.
///
/// This currently isn't parallelized, but it'd be pretty easy to add
/// parallelization to this function.
fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
let mut item = match krate.module.take() {
Some(i) => i,
None => return Ok(()),
};
let final_file = self.dst.join(&krate.name)
.join("all.html");
let settings_file = self.dst.join("settings.html");
let crate_name = krate.name.clone();
item.name = Some(krate.name);
let mut all = AllTypes::new();
{
// Render the crate documentation
let mut work = vec![(self.clone(), item)];
while let Some((mut cx, item)) = work.pop() {
cx.item(item, &mut all, |cx, item| {
work.push((cx.clone(), item))
})?
}
}
let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
if !root_path.ends_with('/') {
root_path.push('/');
}
let mut page = layout::Page {
title: "List of all items in this crate",
css_class: "mod",
root_path: "../",
description: "List of all items in this crate",
keywords: BASIC_KEYWORDS,
resource_suffix: &self.shared.resource_suffix,
};
let sidebar = if let Some(ref version) = cache().crate_version {
format!("<p class='location'>Crate {}</p>\
<div class='block version'>\
<p>Version {}</p>\
</div>\
<a id='all-types' href='index.html'><p>Back to index</p></a>",
crate_name, version)
} else {
String::new()
};
try_err!(layout::render(&mut w, &self.shared.layout,
&page, &sidebar, &all,
self.shared.css_file_extension.is_some(),
&self.shared.themes),
&final_file);
// Generating settings page.
let settings = Settings::new("./", &self.shared.resource_suffix);
page.title = "Rustdoc settings";
page.description = "Settings of Rustdoc";
page.root_path = "./";
let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
let mut themes = self.shared.themes.clone();
let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
themes.push(PathBuf::from("settings.css"));
let mut layout = self.shared.layout.clone();
layout.krate = String::new();
layout.logo = String::new();
layout.favicon = String::new();
try_err!(layout::render(&mut w, &layout,
&page, &sidebar, &settings,
self.shared.css_file_extension.is_some(),
&themes),
&settings_file);
Ok(())
}
fn render_item(&self,
writer: &mut io::Write,
it: &clean::Item,
pushname: bool)
-> io::Result<()> {
// A little unfortunate that this is done like this, but it sure
// does make formatting *a lot* nicer.
CURRENT_LOCATION_KEY.with(|slot| {
*slot.borrow_mut() = self.current.clone();
});
let mut title = if it.is_primitive() {
// No need to include the namespace for primitive types
String::new()
} else {
self.current.join("::")
};
if pushname {
if !title.is_empty() {
title.push_str("::");
}
title.push_str(it.name.as_ref().unwrap());
}
title.push_str(" - Rust");
let tyname = it.type_().css_class();
let desc = if it.is_crate() {
format!("API documentation for the Rust `{}` crate.",
self.shared.layout.krate)
} else {
format!("API documentation for the Rust `{}` {} in crate `{}`.",
it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
};
let keywords = make_item_keywords(it);
let page = layout::Page {
css_class: tyname,
root_path: &self.root_path(),
title: &title,
description: &desc,
keywords: &keywords,
resource_suffix: &self.shared.resource_suffix,
};
reset_ids(true);
if !self.render_redirect_pages {
layout::render(writer, &self.shared.layout, &page,
&Sidebar{ cx: self, item: it },
&Item{ cx: self, item: it },
self.shared.css_file_extension.is_some(),
&self.shared.themes)?;
} else {
let mut url = self.root_path();
if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
for name in &names[..names.len() - 1] {
url.push_str(name);
url.push_str("/");
}
url.push_str(&item_path(ty, names.last().unwrap()));
layout::redirect(writer, &url)?;
}
}
Ok(())
}
/// Non-parallelized version of rendering an item. This will take the input
/// item, render its contents, and then invoke the specified closure with
/// all sub-items which need to be rendered.
///
/// The rendering driver uses this closure to queue up more work.
fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
where F: FnMut(&mut Context, clean::Item),
{
// Stripped modules survive the rustdoc passes (i.e. `strip-private`)
// if they contain impls for public types. These modules can also
// contain items such as publicly re-exported structures.
//
// External crates will provide links to these structures, so
// these modules are recursed into, but not rendered normally
// (a flag on the context).
if !self.render_redirect_pages {
self.render_redirect_pages = item.is_stripped();
}
if item.is_mod() {
// modules are special because they add a namespace. We also need to
// recurse into the items of the module as well.
let name = item.name.as_ref().unwrap().to_string();
let mut item = Some(item);
self.recurse(name, |this| {
let item = item.take().unwrap();
let mut buf = Vec::new();
this.render_item(&mut buf, &item, false).unwrap();
// buf will be empty if the module is stripped and there is no redirect for it
if !buf.is_empty() {
try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
let joint_dst = this.dst.join("index.html");
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
try_err!(dst.write_all(&buf), &joint_dst);
}
let m = match item.inner {
clean::StrippedItem(box clean::ModuleItem(m)) |
clean::ModuleItem(m) => m,
_ => unreachable!()
};
// Render sidebar-items.js used throughout this module.
if !this.render_redirect_pages {
let items = this.build_sidebar_items(&m);
let js_dst = this.dst.join("sidebar-items.js");
let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
try_err!(write!(&mut js_out, "initSidebarItems({});",
as_json(&items)), &js_dst);
}
for item in m.items {
f(this, item);
}
Ok(())
})?;
} else if item.name.is_some() {
let mut buf = Vec::new();
self.render_item(&mut buf, &item, true).unwrap();
// buf will be empty if the item is stripped and there is no redirect for it
if !buf.is_empty() {
let name = item.name.as_ref().unwrap();
let item_type = item.type_();
let file_name = &item_path(item_type, name);
try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
let joint_dst = self.dst.join(file_name);
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
try_err!(dst.write_all(&buf), &joint_dst);
if !self.render_redirect_pages {
all.append(full_path(self, &item), &item_type);
}
// Redirect from a sane URL using the namespace to Rustdoc's
// URL for the page.
let redir_name = format!("{}.{}.html", name, item_type.name_space());
let redir_dst = self.dst.join(redir_name);
if let Ok(redirect_out) = OpenOptions::new().create_new(true)
.write(true)
.open(&redir_dst) {
let mut redirect_out = BufWriter::new(redirect_out);
try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
}
// If the item is a macro, redirect from the old macro URL (with !)
// to the new one (without).
// FIXME(#35705) remove this redirect.
if item_type == ItemType::Macro {
let redir_name = format!("{}.{}!.html", item_type, name);
let redir_dst = self.dst.join(redir_name);
let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
let mut redirect_out = BufWriter::new(redirect_out);
try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
}
}
}
Ok(())
}
fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
// BTreeMap instead of HashMap to get a sorted output
let mut map = BTreeMap::new();
for item in &m.items {
if item.is_stripped() { continue }
let short = item.type_().css_class();
let myname = match item.name {
None => continue,
Some(ref s) => s.to_string(),
};
let short = short.to_string();
map.entry(short).or_insert(vec![])
.push((myname, Some(plain_summary_line(item.doc_value()))));
}
if self.shared.sort_modules_alphabetically {
for (_, items) in &mut map {
items.sort();
}
}
map
}
}
impl<'a> Item<'a> {
/// Generate a url appropriate for an `href` attribute back to the source of
/// this item.
///
/// The url generated, when clicked, will redirect the browser back to the
/// original source code.
///
/// If `None` is returned, then a source link couldn't be generated. This
/// may happen, for example, with externally inlined items where the source
/// of their crate documentation isn't known.
fn src_href(&self) -> Option<String> {
let mut root = self.cx.root_path();
let cache = cache();
let mut path = String::new();
// We can safely ignore macros from other libraries
let file = match self.item.source.filename {
FileName::Real(ref path) => path,
_ => return None,
};
let (krate, path) = if self.item.def_id.is_local() {
if let Some(path) = self.cx.shared.local_sources.get(file) {
(&self.cx.shared.layout.krate, path)
} else {
return None;
}
} else {
let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
Some(&(ref name, ref src, Local)) => (name, src),
Some(&(ref name, ref src, Remote(ref s))) => {
root = s.to_string();
(name, src)
}
Some(&(_, _, Unknown)) | None => return None,
};
clean_srcpath(&src_root, file, false, |component| {
path.push_str(component);
path.push('/');
});
let mut fname = file.file_name().expect("source has no filename")
.to_os_string();
fname.push(".html");
path.push_str(&fname.to_string_lossy());
(krate, &path)
};
let lines = if self.item.source.loline == self.item.source.hiline {
format!("{}", self.item.source.loline)
} else {
format!("{}-{}", self.item.source.loline, self.item.source.hiline)
};
Some(format!("{root}src/{krate}/{path}#{lines}",
root = Escape(&root),
krate = krate,
path = path,
lines = lines))
}
}
fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
f: F) -> fmt::Result
where F: Fn(&mut fmt::Formatter) -> fmt::Result {
write!(w, "<div class=\"docblock type-decl\">")?;
f(w)?;
write!(w, "</div>")
}
impl<'a> fmt::Display for Item<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(!self.item.is_stripped());
// Write the breadcrumb trail header for the top
write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
match self.item.inner {
clean::ModuleItem(ref m) => if m.is_crate {
write!(fmt, "Crate ")?;
} else {
write!(fmt, "Module ")?;
},
clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
clean::TraitItem(..) => write!(fmt, "Trait ")?,
clean::StructItem(..) => write!(fmt, "Struct ")?,
clean::UnionItem(..) => write!(fmt, "Union ")?,
clean::EnumItem(..) => write!(fmt, "Enum ")?,
clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
clean::MacroItem(..) => write!(fmt, "Macro ")?,
clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
clean::ConstantItem(..) => write!(fmt, "Constant ")?,
clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
_ => {
// We don't generate pages for any other type.
unreachable!();
}
}
if !self.item.is_primitive() && !self.item.is_keyword() {
let cur = &self.cx.current;
let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) {
write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
repeat("../").take(cur.len() - i - 1)
.collect::<String>(),
component)?;
}
}
write!(fmt, "<a class=\"{}\" href=''>{}</a>",
self.item.type_(), self.item.name.as_ref().unwrap())?;
write!(fmt, "</span>")?; // in-band
write!(fmt, "<span class='out-of-band'>")?;
if let Some(version) = self.item.stable_since() {
write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
version)?;
}
write!(fmt,
"<span id='render-detail'>\
<a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
title=\"collapse all docs\">\
[<span class='inner'>−</span>]\
</a>\
</span>")?;
// Write `src` tag
//
// When this item is part of a `pub use` in a downstream crate, the
// [src] link in the downstream documentation will actually come back to
// this page, and this link will be auto-clicked. The `id` attribute is
// used to find the link to auto-click.
if self.cx.shared.include_sources && !self.item.is_primitive() {
if let Some(l) = self.src_href() {
write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
l, "goto source code")?;
}
}
write!(fmt, "</span></h1>")?; // out-of-band
match self.item.inner {
clean::ModuleItem(ref m) =>
item_module(fmt, self.cx, self.item, &m.items),
clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
item_function(fmt, self.cx, self.item, f),
clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
item_static(fmt, self.cx, self.item, i),
clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
_ => {
// We don't generate pages for any other type.
unreachable!();
}
}
}
}
fn item_path(ty: ItemType, name: &str) -> String {
match ty {
ItemType::Module => format!("{}/index.html", name),
_ => format!("{}.{}.html", ty.css_class(), name),
}
}
fn full_path(cx: &Context, item: &clean::Item) -> String {
let mut s = cx.current.join("::");
s.push_str("::");
s.push_str(item.name.as_ref().unwrap());
s
}
fn shorter<'a>(s: Option<&'a str>) -> String {
match s {
Some(s) => s.lines()
.skip_while(|s| s.chars().all(|c| c.is_whitespace()))
.take_while(|line|{
(*line).chars().any(|chr|{
!chr.is_whitespace()
})
}).collect::<Vec<_>>().join("\n"),
None => "".to_string()
}
}
#[inline]
fn plain_summary_line(s: Option<&str>) -> String {
let line = shorter(s).replace("\n", " ");
markdown::plain_summary_line(&line[..])
}
fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
if let Some(ref name) = item.name {
info!("Documenting {}", name);
}
document_stability(w, cx, item)?;
let prefix = render_assoc_const_value(item);
document_full(w, item, cx, &prefix)?;
Ok(())
}
/// Render md_text as markdown.
fn render_markdown(w: &mut fmt::Formatter,
md_text: &str,
links: Vec<(String, String)>,
prefix: &str,)
-> fmt::Result {
write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
}
fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
prefix: &str) -> fmt::Result {
if let Some(s) = item.doc_value() {
let markdown = if s.contains('\n') {
format!("{} [Read more]({})",
&plain_summary_line(Some(s)), naive_assoc_href(item, link))
} else {
format!("{}", &plain_summary_line(Some(s)))
};
render_markdown(w, &markdown, item.links(), prefix)?;
} else if !prefix.is_empty() {
write!(w, "<div class='docblock'>{}</div>", prefix)?;
}
Ok(())
}
fn render_assoc_const_value(item: &clean::Item) -> String {
match item.inner {
clean::AssociatedConstItem(ref ty, Some(ref default)) => {
highlight::render_with_highlighting(
&format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
None,
None,
None,
None,
)
}
_ => String::new(),
}
}
fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
cx: &Context, prefix: &str) -> fmt::Result {
if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
debug!("Doc block: =====\n{}\n=====", s);
render_markdown(w, &*s, item.links(), prefix)?;
} else if !prefix.is_empty() {
write!(w, "<div class='docblock'>{}</div>", prefix)?;
}
Ok(())
}
fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
let stabilities = short_stability(item, cx, true);
if !stabilities.is_empty() {
write!(w, "<div class='stability'>")?;
for stability in stabilities {
write!(w, "{}", stability)?;
}
write!(w, "</div>")?;
}
Ok(())
}
fn name_key(name: &str) -> (&str, u64, usize) {
// find number at end
let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
// count leading zeroes
let after_zeroes =
name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
// sort leading zeroes last
let num_zeroes = after_zeroes - split;
match name[split..].parse() {
Ok(n) => (&name[..split], n, num_zeroes),
Err(_) => (name, 0, num_zeroes),
}
}
fn item_module(w: &mut fmt::Formatter, cx: &Context,
item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
document(w, cx, item)?;
let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
// the order of item types in the listing
fn reorder(ty: ItemType) -> u8 {
match ty {
ItemType::ExternCrate => 0,
ItemType::Import => 1,
ItemType::Primitive => 2,
ItemType::Module => 3,
ItemType::Macro => 4,
ItemType::Struct => 5,
ItemType::Enum => 6,
ItemType::Constant => 7,
ItemType::Static => 8,
ItemType::Trait => 9,
ItemType::Function => 10,
ItemType::Typedef => 12,
ItemType::Union => 13,
_ => 14 + ty as u8,
}
}
fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
let ty1 = i1.type_();
let ty2 = i2.type_();
if ty1 != ty2 {
return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
}
let s1 = i1.stability.as_ref().map(|s| s.level);
let s2 = i2.stability.as_ref().map(|s| s.level);
match (s1, s2) {
(Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
(Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
_ => {}
}
let lhs = i1.name.as_ref().map_or("", |s| &**s);
let rhs = i2.name.as_ref().map_or("", |s| &**s);
name_key(lhs).cmp(&name_key(rhs))
}
if cx.shared.sort_modules_alphabetically {
indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
}
// This call is to remove re-export duplicates in cases such as:
//
// ```
// pub mod foo {
// pub mod bar {
// pub trait Double { fn foo(); }
// }
// }
//
// pub use foo::bar::*;
// pub use foo::*;
// ```
//
// `Double` will appear twice in the generated docs.
//
// FIXME: This code is quite ugly and could be improved. Small issue: DefId
// can be identical even if the elements are different (mostly in imports).
// So in case this is an import, we keep everything by adding a "unique id"
// (which is the position in the vector).
indices.dedup_by_key(|i| (items[*i].def_id,
if items[*i].name.as_ref().is_some() {
Some(full_path(cx, &items[*i]).clone())
} else {
None
},
items[*i].type_(),
if items[*i].is_import() {
*i
} else {
0
}));
debug!("{:?}", indices);
let mut curty = None;
for &idx in &indices {
let myitem = &items[idx];
if myitem.is_stripped() {
continue;
}
let myty = Some(myitem.type_());
if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
// Put `extern crate` and `use` re-exports in the same section.
curty = myty;
} else if myty != curty {
if curty.is_some() {
write!(w, "</table>")?;
}
curty = myty;
let (short, name) = item_ty_to_strs(&myty.unwrap());
write!(w, "<h2 id='{id}' class='section-header'>\
<a href=\"#{id}\">{name}</a></h2>\n<table>",
id = derive_id(short.to_owned()), name = name)?;
}
match myitem.inner {
clean::ExternCrateItem(ref name, ref src) => {
use html::format::HRef;
match *src {
Some(ref src) => {
write!(w, "<tr><td><code>{}extern crate {} as {};",
VisSpace(&myitem.visibility),
HRef::new(myitem.def_id, src),
name)?
}
None => {
write!(w, "<tr><td><code>{}extern crate {};",
VisSpace(&myitem.visibility),
HRef::new(myitem.def_id, name))?
}
}
write!(w, "</code></td></tr>")?;
}
clean::ImportItem(ref import) => {
write!(w, "<tr><td><code>{}{}</code></td></tr>",
VisSpace(&myitem.visibility), *import)?;
}
_ => {
if myitem.name.is_none() { continue }
let stabilities = short_stability(myitem, cx, false);
let stab_docs = if !stabilities.is_empty() {
stabilities.iter()
.map(|s| format!("[{}]", s))
.collect::<Vec<_>>()
.as_slice()
.join(" ")
} else {
String::new()
};
let unsafety_flag = match myitem.inner {
clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
if func.header.unsafety == hir::Unsafety::Unsafe => {
"<a title='unsafe function' href='#'><sup>⚠</sup></a>"
}
_ => "",
};
let doc_value = myitem.doc_value().unwrap_or("");
write!(w, "
<tr class='{stab} module-item'>
<td><a class=\"{class}\" href=\"{href}\"
title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
<td class='docblock-short'>
{stab_docs} {docs}
</td>
</tr>",
name = *myitem.name.as_ref().unwrap(),
stab_docs = stab_docs,
docs = MarkdownSummaryLine(doc_value, &myitem.links()),
class = myitem.type_(),
stab = myitem.stability_class().unwrap_or("".to_string()),
unsafety_flag = unsafety_flag,
href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
title_type = myitem.type_(),
title = full_path(cx, myitem))?;
}
}
}
if curty.is_some() {
write!(w, "</table>")?;
}
Ok(())
}
fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
let mut stability = vec![];
if let Some(stab) = item.stability.as_ref() {
let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
format!(": {}", stab.deprecated_reason)
} else {
String::new()
};
if !stab.deprecated_since.is_empty() {
let since = if show_reason {
format!(" since {}", Escape(&stab.deprecated_since))
} else {
String::new()
};
let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
format!("Deprecated{}{}",
since,
MarkdownHtml(&deprecated_reason))
} else {
format!("Deprecating in {}{}",
Escape(&stab.deprecated_since),
MarkdownHtml(&deprecated_reason))
};
stability.push(format!("<div class='stab deprecated'>{}</div>", text))
};
if stab.level == stability::Unstable {
if show_reason {
let unstable_extra = match (!stab.feature.is_empty(),
&cx.shared.issue_tracker_base_url,
stab.issue) {
(true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
Escape(&stab.feature), tracker_url, issue_no, issue_no),
(false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
issue_no),
(true, ..) =>
format!(" (<code>{}</code>)", Escape(&stab.feature)),
_ => String::new(),
};
if stab.unstable_reason.is_empty() {
stability.push(format!("<div class='stab unstable'>\
<span class=microscope>🔬</span> \
This is a nightly-only experimental API. {}\
</div>",
unstable_extra));
} else {
let text = format!("<summary><span class=microscope>🔬</span> \
This is a nightly-only experimental API. {}\
</summary>{}",
unstable_extra,
MarkdownHtml(&stab.unstable_reason));
stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
text));
}
} else {
stability.push(format!("<div class='stab unstable'>Experimental</div>"))
}
};
} else if let Some(depr) = item.deprecation.as_ref() {
let note = if show_reason && !depr.note.is_empty() {
format!(": {}", depr.note)
} else {
String::new()
};
let since = if show_reason && !depr.since.is_empty() {
format!(" since {}", Escape(&depr.since))
} else {
String::new()
};
let text = if stability::deprecation_in_effect(&depr.since) {
format!("Deprecated{}{}",
since,
MarkdownHtml(¬e))
} else {
format!("Deprecating in {}{}",
Escape(&depr.since),
MarkdownHtml(¬e))
};
stability.push(format!("<div class='stab deprecated'>{}</div>", text))
}
if let Some(ref cfg) = item.attrs.cfg {
stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
cfg.render_long_html()
} else {
cfg.render_short_html()
}));
}
stability
}
struct Initializer<'a>(&'a str);
impl<'a> fmt::Display for Initializer<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Initializer(s) = *self;
if s.is_empty() { return Ok(()); }
write!(f, "<code> = </code>")?;
write!(f, "<code>{}</code>", Escape(s))
}
}
fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
c: &clean::Constant) -> fmt::Result {
write!(w, "<pre class='rust const'>")?;
render_attributes(w, it)?;
write!(w, "{vis}const \
{name}: {typ}{init}</pre>",
vis = VisSpace(&it.visibility),
name = it.name.as_ref().unwrap(),
typ = c.type_,
init = Initializer(&c.expr))?;
document(w, cx, it)
}
fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
s: &clean::Static) -> fmt::Result {
write!(w, "<pre class='rust static'>")?;
render_attributes(w, it)?;
write!(w, "{vis}static {mutability}\
{name}: {typ}{init}</pre>",
vis = VisSpace(&it.visibility),
mutability = MutableSpace(s.mutability),
name = it.name.as_ref().unwrap(),
typ = s.type_,
init = Initializer(&s.expr))?;
document(w, cx, it)
}
fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
f: &clean::Function) -> fmt::Result {
let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
VisSpace(&it.visibility),
ConstnessSpace(f.header.constness),
UnsafetySpace(f.header.unsafety),
AsyncSpace(f.header.asyncness),
AbiSpace(f.header.abi),
it.name.as_ref().unwrap(),
f.generics).len();
write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
render_attributes(w, it)?;
write!(w,
"{vis}{constness}{unsafety}{asyncness}{abi}fn \
{name}{generics}{decl}{where_clause}</pre>",
vis = VisSpace(&it.visibility),
constness = ConstnessSpace(f.header.constness),
unsafety = UnsafetySpace(f.header.unsafety),
asyncness = AsyncSpace(f.header.asyncness),
abi = AbiSpace(f.header.abi),
name = it.name.as_ref().unwrap(),
generics = f.generics,
where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
decl = Method {
decl: &f.decl,
name_len,
indent: 0,
})?;
document(w, cx, it)
}
fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
// If there's already another implementor that has the same abbridged name, use the
// full path, for example in `std::iter::ExactSizeIterator`
let use_absolute = match implementor.inner_impl().for_ {
clean::ResolvedPath { ref path, is_generic: false, .. } |
clean::BorrowedRef {
type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
..
} => implementor_dups[path.last_name()].1,
_ => false,
};
fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
for it in &implementor.inner_impl().items {
if let clean::TypedefItem(ref tydef, _) = it.inner {
write!(w, "<span class=\"where fmt-newline\"> ")?;
assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
write!(w, ";</span>")?;
}
}
write!(w, "</code><td>")?;
if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
write!(w, "<div class='out-of-band'>")?;
write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
l, "goto source code")?;
write!(w, "</div>")?;
}
writeln!(w, "</td></tr></tbody></table></li>")?;
Ok(())
}
fn render_impls(cx: &Context, w: &mut fmt::Formatter,
traits: &[&&Impl],
containing_item: &clean::Item) -> fmt::Result {
for i in traits {
let did = i.trait_did().unwrap();
let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
render_impl(w, cx, i, assoc_link,
RenderMode::Normal, containing_item.stable_since(), true)?;
}
Ok(())
}
fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
t: &clean::Trait) -> fmt::Result {
let mut bounds = String::new();
let mut bounds_plain = String::new();
if !t.bounds.is_empty() {
if !bounds.is_empty() {
bounds.push(' ');
bounds_plain.push(' ');
}
bounds.push_str(": ");
bounds_plain.push_str(": ");
for (i, p) in t.bounds.iter().enumerate() {
if i > 0 {
bounds.push_str(" + ");
bounds_plain.push_str(" + ");
}
bounds.push_str(&format!("{}", *p));
bounds_plain.push_str(&format!("{:#}", *p));
}
}
let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
// Output the trait definition
wrap_into_docblock(w, |w| {
write!(w, "<pre class='rust trait'>")?;
render_attributes(w, it)?;
write!(w, "{}{}{}trait {}{}{}",
VisSpace(&it.visibility),
UnsafetySpace(t.unsafety),
if t.is_auto { "auto " } else { "" },
it.name.as_ref().unwrap(),
t.generics,
bounds)?;
if !t.generics.where_predicates.is_empty() {
write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
} else {
write!(w, " ")?;
}
if t.items.is_empty() {
write!(w, "{{ }}")?;
} else {
// FIXME: we should be using a derived_id for the Anchors here
write!(w, "{{\n")?;
for t in &types {
write!(w, " ")?;
render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
write!(w, ";\n")?;
}
if !types.is_empty() && !consts.is_empty() {
w.write_str("\n")?;
}
for t in &consts {
write!(w, " ")?;
render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
write!(w, ";\n")?;
}
if !consts.is_empty() && !required.is_empty() {
w.write_str("\n")?;
}
for (pos, m) in required.iter().enumerate() {
write!(w, " ")?;
render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
write!(w, ";\n")?;
if pos < required.len() - 1 {
write!(w, "<div class='item-spacer'></div>")?;
}
}
if !required.is_empty() && !provided.is_empty() {
w.write_str("\n")?;
}
for (pos, m) in provided.iter().enumerate() {
write!(w, " ")?;
render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
match m.inner {
clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
write!(w, ",\n {{ ... }}\n")?;
},
_ => {
write!(w, " {{ ... }}\n")?;
},
}
if pos < provided.len() - 1 {
write!(w, "<div class='item-spacer'></div>")?;
}
}
write!(w, "}}")?;
}
write!(w, "</pre>")
})?;
// Trait documentation
document(w, cx, it)?;
fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
-> fmt::Result {
let name = m.name.as_ref().unwrap();
let item_type = m.type_();
let id = derive_id(format!("{}.{}", item_type, name));
let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "{extra}<h3 id='{id}' class='method'>\
<span id='{ns_id}' class='invisible'><code>",
extra = render_spotlight_traits(m)?,
id = id,
ns_id = ns_id)?;
render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
write!(w, "</code>")?;
render_stability_since(w, m, t)?;
write!(w, "</span></h3>")?;
document(w, cx, m)?;
Ok(())
}
if !types.is_empty() {
write!(w, "
<h2 id='associated-types' class='small-section-header'>
Associated Types<a href='#associated-types' class='anchor'></a>
</h2>
<div class='methods'>
")?;
for t in &types {
trait_item(w, cx, *t, it)?;
}
write!(w, "</div>")?;
}
if !consts.is_empty() {
write!(w, "
<h2 id='associated-const' class='small-section-header'>
Associated Constants<a href='#associated-const' class='anchor'></a>
</h2>
<div class='methods'>
")?;
for t in &consts {
trait_item(w, cx, *t, it)?;
}
write!(w, "</div>")?;
}
// Output the documentation for each function individually
if !required.is_empty() {
write!(w, "
<h2 id='required-methods' class='small-section-header'>
Required Methods<a href='#required-methods' class='anchor'></a>
</h2>
<div class='methods'>
")?;
for m in &required {
trait_item(w, cx, *m, it)?;
}
write!(w, "</div>")?;
}
if !provided.is_empty() {
write!(w, "
<h2 id='provided-methods' class='small-section-header'>
Provided Methods<a href='#provided-methods' class='anchor'></a>
</h2>
<div class='methods'>
")?;
for m in &provided {
trait_item(w, cx, *m, it)?;
}
write!(w, "</div>")?;
}
// If there are methods directly on this trait object, render them here.
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
let cache = cache();
let impl_header = "
<h2 id='implementors' class='small-section-header'>
Implementors<a href='#implementors' class='anchor'></a>
</h2>
<ul class='item-list' id='implementors-list'>
";
let synthetic_impl_header = "
<h2 id='synthetic-implementors' class='small-section-header'>
Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
</h2>
<ul class='item-list' id='synthetic-implementors-list'>
";
let mut synthetic_types = Vec::new();
if let Some(implementors) = cache.implementors.get(&it.def_id) {
// The DefId is for the first Type found with that name. The bool is
// if any Types with the same name but different DefId have been found.
let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
for implementor in implementors {
match implementor.inner_impl().for_ {
clean::ResolvedPath { ref path, did, is_generic: false, .. } |
clean::BorrowedRef {
type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
..
} => {
let &mut (prev_did, ref mut has_duplicates) =
implementor_dups.entry(path.last_name()).or_insert((did, false));
if prev_did != did {
*has_duplicates = true;
}
}
_ => {}
}
}
let (local, foreign) = implementors.iter()
.partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
.map_or(true, |d| cache.paths.contains_key(&d)));
let (synthetic, concrete) = local.iter()
.partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
if !foreign.is_empty() {
write!(w, "
<h2 id='foreign-impls' class='small-section-header'>
Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
</h2>
")?;
for implementor in foreign {
let assoc_link = AssocItemLink::GotoSource(
implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
);
render_impl(w, cx, &implementor, assoc_link,
RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
}
}
write!(w, "{}", impl_header)?;
for implementor in concrete {
render_implementor(cx, implementor, w, &implementor_dups)?;
}
write!(w, "</ul>")?;
if t.auto {
write!(w, "{}", synthetic_impl_header)?;
for implementor in synthetic {
synthetic_types.extend(
collect_paths_for_type(implementor.inner_impl().for_.clone())
);
render_implementor(cx, implementor, w, &implementor_dups)?;
}
write!(w, "</ul>")?;
}
} else {
// even without any implementations to write in, we still want the heading and list, so the
// implementors javascript file pulled in below has somewhere to write the impls into
write!(w, "{}", impl_header)?;
write!(w, "</ul>")?;
if t.auto {
write!(w, "{}", synthetic_impl_header)?;
write!(w, "</ul>")?;
}
}
write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
as_json(&synthetic_types))?;
write!(w, r#"<script type="text/javascript" async
src="{root_path}/implementors/{path}/{ty}.{name}.js">
</script>"#,
root_path = vec![".."; cx.current.len()].join("/"),
path = if it.def_id.is_local() {
cx.current.join("/")
} else {
let (ref path, _) = cache.external_paths[&it.def_id];
path[..path.len() - 1].join("/")
},
ty = it.type_().css_class(),
name = *it.name.as_ref().unwrap())?;
Ok(())
}
fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
use html::item_type::ItemType::*;
let name = it.name.as_ref().unwrap();
let ty = match it.type_() {
Typedef | AssociatedType => AssociatedType,
s@_ => s,
};
let anchor = format!("#{}.{}", ty, name);
match link {
AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
AssocItemLink::Anchor(None) => anchor,
AssocItemLink::GotoSource(did, _) => {
href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
}
}
}
fn assoc_const(w: &mut fmt::Formatter,
it: &clean::Item,
ty: &clean::Type,
_default: Option<&String>,
link: AssocItemLink) -> fmt::Result {
write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
VisSpace(&it.visibility),
naive_assoc_href(it, link),
it.name.as_ref().unwrap(),
ty)?;
Ok(())
}
fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
bounds: &Vec<clean::GenericBound>,
default: Option<&clean::Type>,
link: AssocItemLink) -> fmt::Result {
write!(w, "type <a href='{}' class=\"type\">{}</a>",
naive_assoc_href(it, link),
it.name.as_ref().unwrap())?;
if !bounds.is_empty() {
write!(w, ": {}", GenericBounds(bounds))?
}
if let Some(default) = default {
write!(w, " = {}", default)?;
}
Ok(())
}
fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
ver: Option<&'a str>,
containing_ver: Option<&'a str>) -> fmt::Result {
if let Some(v) = ver {
if containing_ver != ver && v.len() > 0 {
write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
v)?
}
}
Ok(())
}
fn render_stability_since(w: &mut fmt::Formatter,
item: &clean::Item,
containing_item: &clean::Item) -> fmt::Result {
render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
}
fn render_assoc_item(w: &mut fmt::Formatter,
item: &clean::Item,
link: AssocItemLink,
parent: ItemType) -> fmt::Result {
fn method(w: &mut fmt::Formatter,
meth: &clean::Item,
header: hir::FnHeader,
g: &clean::Generics,
d: &clean::FnDecl,
link: AssocItemLink,
parent: ItemType)
-> fmt::Result {
let name = meth.name.as_ref().unwrap();
let anchor = format!("#{}.{}", meth.type_(), name);
let href = match link {
AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
AssocItemLink::Anchor(None) => anchor,
AssocItemLink::GotoSource(did, provided_methods) => {
// We're creating a link from an impl-item to the corresponding
// trait-item and need to map the anchored type accordingly.
let ty = if provided_methods.contains(name) {
ItemType::Method
} else {
ItemType::TyMethod
};
href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
}
};
let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
VisSpace(&meth.visibility),
ConstnessSpace(header.constness),
UnsafetySpace(header.unsafety),
AsyncSpace(header.asyncness),
AbiSpace(header.abi),
name,
*g).len();
let (indent, end_newline) = if parent == ItemType::Trait {
head_len += 4;
(4, false)
} else {
(0, true)
};
render_attributes(w, meth)?;
write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
{generics}{decl}{where_clause}",
VisSpace(&meth.visibility),
ConstnessSpace(header.constness),
UnsafetySpace(header.unsafety),
AsyncSpace(header.asyncness),
AbiSpace(header.abi),
href = href,
name = name,
generics = *g,
decl = Method {
decl: d,
name_len: head_len,
indent,
},
where_clause = WhereClause {
gens: g,
indent,
end_newline,
})
}
match item.inner {
clean::StrippedItem(..) => Ok(()),
clean::TyMethodItem(ref m) => {
method(w, item, m.header, &m.generics, &m.decl, link, parent)
}
clean::MethodItem(ref m) => {
method(w, item, m.header, &m.generics, &m.decl, link, parent)
}
clean::AssociatedConstItem(ref ty, ref default) => {
assoc_const(w, item, ty, default.as_ref(), link)
}
clean::AssociatedTypeItem(ref bounds, ref default) => {
assoc_type(w, item, bounds, default.as_ref(), link)
}
_ => panic!("render_assoc_item called on non-associated-item")
}
}
fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
s: &clean::Struct) -> fmt::Result {
wrap_into_docblock(w, |w| {
write!(w, "<pre class='rust struct'>")?;
render_attributes(w, it)?;
render_struct(w,
it,
Some(&s.generics),
s.struct_type,
&s.fields,
"",
true)?;
write!(w, "</pre>")
})?;
document(w, cx, it)?;
let mut fields = s.fields.iter().filter_map(|f| {
match f.inner {
clean::StructFieldItem(ref ty) => Some((f, ty)),
_ => None,
}
}).peekable();
if let doctree::Plain = s.struct_type {
if fields.peek().is_some() {
write!(w, "<h2 id='fields' class='fields small-section-header'>
Fields<a href='#fields' class='anchor'></a></h2>")?;
for (field, ty) in fields {
let id = derive_id(format!("{}.{}",
ItemType::StructField,
field.name.as_ref().unwrap()));
let ns_id = derive_id(format!("{}.{}",
field.name.as_ref().unwrap(),
ItemType::StructField.name_space()));
write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
<a href=\"#{id}\" class=\"anchor field\"></a>
<span id=\"{ns_id}\" class='invisible'>
<code>{name}: {ty}</code>
</span></span>",
item_type = ItemType::StructField,
id = id,
ns_id = ns_id,
name = field.name.as_ref().unwrap(),
ty = ty)?;
if let Some(stability_class) = field.stability_class() {
write!(w, "<span class='stab {stab}'></span>",
stab = stability_class)?;
}
document(w, cx, field)?;
}
}
}
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
s: &clean::Union) -> fmt::Result {
wrap_into_docblock(w, |w| {
write!(w, "<pre class='rust union'>")?;
render_attributes(w, it)?;
render_union(w,
it,
Some(&s.generics),
&s.fields,
"",
true)?;
write!(w, "</pre>")
})?;
document(w, cx, it)?;
let mut fields = s.fields.iter().filter_map(|f| {
match f.inner {
clean::StructFieldItem(ref ty) => Some((f, ty)),
_ => None,
}
}).peekable();
if fields.peek().is_some() {
write!(w, "<h2 id='fields' class='fields small-section-header'>
Fields<a href='#fields' class='anchor'></a></h2>")?;
for (field, ty) in fields {
let name = field.name.as_ref().expect("union field name");
let id = format!("{}.{}", ItemType::StructField, name);
write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
<a href=\"#{id}\" class=\"anchor field\"></a>\
<span class='invisible'><code>{name}: {ty}</code></span>\
</span>",
id = id,
name = name,
shortty = ItemType::StructField,
ty = ty)?;
if let Some(stability_class) = field.stability_class() {
write!(w, "<span class='stab {stab}'></span>",
stab = stability_class)?;
}
document(w, cx, field)?;
}
}
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
e: &clean::Enum) -> fmt::Result {
wrap_into_docblock(w, |w| {
write!(w, "<pre class='rust enum'>")?;
render_attributes(w, it)?;
write!(w, "{}enum {}{}{}",
VisSpace(&it.visibility),
it.name.as_ref().unwrap(),
e.generics,
WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
if e.variants.is_empty() && !e.variants_stripped {
write!(w, " {{}}")?;
} else {
write!(w, " {{\n")?;
for v in &e.variants {
write!(w, " ")?;
let name = v.name.as_ref().unwrap();
match v.inner {
clean::VariantItem(ref var) => {
match var.kind {
clean::VariantKind::CLike => write!(w, "{}", name)?,
clean::VariantKind::Tuple(ref tys) => {
write!(w, "{}(", name)?;
for (i, ty) in tys.iter().enumerate() {
if i > 0 {
write!(w, ", ")?
}
write!(w, "{}", *ty)?;
}
write!(w, ")")?;
}
clean::VariantKind::Struct(ref s) => {
render_struct(w,
v,
None,
s.struct_type,
&s.fields,
" ",
false)?;
}
}
}
_ => unreachable!()
}
write!(w, ",\n")?;
}
if e.variants_stripped {
write!(w, " // some variants omitted\n")?;
}
write!(w, "}}")?;
}
write!(w, "</pre>")
})?;
document(w, cx, it)?;
if !e.variants.is_empty() {
write!(w, "<h2 id='variants' class='variants small-section-header'>
Variants<a href='#variants' class='anchor'></a></h2>\n")?;
for variant in &e.variants {
let id = derive_id(format!("{}.{}",
ItemType::Variant,
variant.name.as_ref().unwrap()));
let ns_id = derive_id(format!("{}.{}",
variant.name.as_ref().unwrap(),
ItemType::Variant.name_space()));
write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
<a href=\"#{id}\" class=\"anchor field\"></a>\
<span id='{ns_id}' class='invisible'><code>{name}",
id = id,
ns_id = ns_id,
name = variant.name.as_ref().unwrap())?;
if let clean::VariantItem(ref var) = variant.inner {
if let clean::VariantKind::Tuple(ref tys) = var.kind {
write!(w, "(")?;
for (i, ty) in tys.iter().enumerate() {
if i > 0 {
write!(w, ", ")?;
}
write!(w, "{}", *ty)?;
}
write!(w, ")")?;
}
}
write!(w, "</code></span></span>")?;
document(w, cx, variant)?;
use clean::{Variant, VariantKind};
if let clean::VariantItem(Variant {
kind: VariantKind::Struct(ref s)
}) = variant.inner {
let variant_id = derive_id(format!("{}.{}.fields",
ItemType::Variant,
variant.name.as_ref().unwrap()));
write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
id = variant_id)?;
write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
<table>", name = variant.name.as_ref().unwrap())?;
for field in &s.fields {
use clean::StructFieldItem;
if let StructFieldItem(ref ty) = field.inner {
let id = derive_id(format!("variant.{}.field.{}",
variant.name.as_ref().unwrap(),
field.name.as_ref().unwrap()));
let ns_id = derive_id(format!("{}.{}.{}.{}",
variant.name.as_ref().unwrap(),
ItemType::Variant.name_space(),
field.name.as_ref().unwrap(),
ItemType::StructField.name_space()));
write!(w, "<tr><td \
id='{id}'>\
<span id='{ns_id}' class='invisible'>\
<code>{f}: {t}</code></span></td><td>",
id = id,
ns_id = ns_id,
f = field.name.as_ref().unwrap(),
t = *ty)?;
document(w, cx, field)?;
write!(w, "</td></tr>")?;
}
}
write!(w, "</table></span>")?;
}
render_stability_since(w, variant, it)?;
}
}
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
Ok(())
}
fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
let name = attr.name();
if attr.is_word() {
Some(format!("{}", name))
} else if let Some(v) = attr.value_str() {
Some(format!("{} = {:?}", name, v.as_str()))
} else if let Some(values) = attr.meta_item_list() {
let display: Vec<_> = values.iter().filter_map(|attr| {
attr.meta_item().and_then(|mi| render_attribute(mi))
}).collect();
if display.len() > 0 {
Some(format!("{}({})", name, display.join(", ")))
} else {
None
}
} else {
None
}
}
const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
"export_name",
"lang",
"link_section",
"must_use",
"no_mangle",
"repr",
"unsafe_destructor_blind_to_params"
];
fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
let mut attrs = String::new();
for attr in &it.attrs.other_attrs {
let name = attr.name();
if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
continue;
}
if let Some(s) = render_attribute(&attr.meta().unwrap()) {
attrs.push_str(&format!("#[{}]\n", s));
}
}
if attrs.len() > 0 {
write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
}
Ok(())
}
fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
g: Option<&clean::Generics>,
ty: doctree::StructType,
fields: &[clean::Item],
tab: &str,
structhead: bool) -> fmt::Result {
write!(w, "{}{}{}",
VisSpace(&it.visibility),
if structhead {"struct "} else {""},
it.name.as_ref().unwrap())?;
if let Some(g) = g {
write!(w, "{}", g)?
}
match ty {
doctree::Plain => {
if let Some(g) = g {
write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
}
let mut has_visible_fields = false;
write!(w, " {{")?;
for field in fields {
if let clean::StructFieldItem(ref ty) = field.inner {
write!(w, "\n{} {}{}: {},",
tab,
VisSpace(&field.visibility),
field.name.as_ref().unwrap(),
*ty)?;
has_visible_fields = true;
}
}
if has_visible_fields {
if it.has_stripped_fields().unwrap() {
write!(w, "\n{} // some fields omitted", tab)?;
}
write!(w, "\n{}", tab)?;
} else if it.has_stripped_fields().unwrap() {
// If there are no visible fields we can just display
// `{ /* fields omitted */ }` to save space.
write!(w, " /* fields omitted */ ")?;
}
write!(w, "}}")?;
}
doctree::Tuple => {
write!(w, "(")?;
for (i, field) in fields.iter().enumerate() {
if i > 0 {
write!(w, ", ")?;
}
match field.inner {
clean::StrippedItem(box clean::StructFieldItem(..)) => {
write!(w, "_")?
}
clean::StructFieldItem(ref ty) => {
write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
}
_ => unreachable!()
}
}
write!(w, ")")?;
if let Some(g) = g {
write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
}
write!(w, ";")?;
}
doctree::Unit => {
// Needed for PhantomData.
if let Some(g) = g {
write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
}
write!(w, ";")?;
}
}
Ok(())
}
fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
g: Option<&clean::Generics>,
fields: &[clean::Item],
tab: &str,
structhead: bool) -> fmt::Result {
write!(w, "{}{}{}",
VisSpace(&it.visibility),
if structhead {"union "} else {""},
it.name.as_ref().unwrap())?;
if let Some(g) = g {
write!(w, "{}", g)?;
write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
}
write!(w, " {{\n{}", tab)?;
for field in fields {
if let clean::StructFieldItem(ref ty) = field.inner {
write!(w, " {}{}: {},\n{}",
VisSpace(&field.visibility),
field.name.as_ref().unwrap(),
*ty,
tab)?;
}
}
if it.has_stripped_fields().unwrap() {
write!(w, " // some fields omitted\n{}", tab)?;
}
write!(w, "}}")?;
Ok(())
}
#[derive(Copy, Clone)]
enum AssocItemLink<'a> {
Anchor(Option<&'a str>),
GotoSource(DefId, &'a FxHashSet<String>),
}
impl<'a> AssocItemLink<'a> {
fn anchor(&self, id: &'a String) -> Self {
match *self {
AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
ref other => *other,
}
}
}
enum AssocItemRender<'a> {
All,
DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
}
#[derive(Copy, Clone, PartialEq)]
enum RenderMode {
Normal,
ForDeref { mut_: bool },
}
fn render_assoc_items(w: &mut fmt::Formatter,
cx: &Context,
containing_item: &clean::Item,
it: DefId,
what: AssocItemRender) -> fmt::Result {
let c = cache();
let v = match c.impls.get(&it) {
Some(v) => v,
None => return Ok(()),
};
let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
i.inner_impl().trait_.is_none()
});
if !non_trait.is_empty() {
let render_mode = match what {
AssocItemRender::All => {
write!(w, "
<h2 id='methods' class='small-section-header'>
Methods<a href='#methods' class='anchor'></a>
</h2>
")?;
RenderMode::Normal
}
AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
write!(w, "
<h2 id='deref-methods' class='small-section-header'>
Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
</h2>
", trait_, type_)?;
RenderMode::ForDeref { mut_: deref_mut_ }
}
};
for i in &non_trait {
render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
containing_item.stable_since(), true)?;
}
}
if let AssocItemRender::DerefFor { .. } = what {
return Ok(());
}
if !traits.is_empty() {
let deref_impl = traits.iter().find(|t| {
t.inner_impl().trait_.def_id() == c.deref_trait_did
});
if let Some(impl_) = deref_impl {
let has_deref_mut = traits.iter().find(|t| {
t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
}).is_some();
render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
}
let (synthetic, concrete) = traits
.iter()
.partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
render_impls(self.0, fmt, &self.1, self.2)
}
}
let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
if !impls.is_empty() {
write!(w, "
<h2 id='implementations' class='small-section-header'>
Trait Implementations<a href='#implementations' class='anchor'></a>
</h2>
<div id='implementations-list'>{}</div>", impls)?;
}
if !synthetic.is_empty() {
write!(w, "
<h2 id='synthetic-implementations' class='small-section-header'>
Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
</h2>
<div id='synthetic-implementations-list'>
")?;
render_impls(cx, w, &synthetic, containing_item)?;
write!(w, "</div>")?;
}
}
Ok(())
}
fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
let target = impl_.inner_impl().items.iter().filter_map(|item| {
match item.inner {
clean::TypedefItem(ref t, true) => Some(&t.type_),
_ => None,
}
}).next().expect("Expected associated type binding");
let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
deref_mut_: deref_mut };
if let Some(did) = target.def_id() {
render_assoc_items(w, cx, container_item, did, what)
} else {
if let Some(prim) = target.primitive_type() {
if let Some(&did) = cache().primitive_locations.get(&prim) {
render_assoc_items(w, cx, container_item, did, what)?;
}
}
Ok(())
}
}
fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
let self_type_opt = match item.inner {
clean::MethodItem(ref method) => method.decl.self_type(),
clean::TyMethodItem(ref method) => method.decl.self_type(),
_ => None
};
if let Some(self_ty) = self_type_opt {
let (by_mut_ref, by_box, by_value) = match self_ty {
SelfTy::SelfBorrowed(_, mutability) |
SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
(mutability == Mutability::Mutable, false, false)
},
SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
(false, Some(did) == cache().owned_box_did, false)
},
SelfTy::SelfValue => (false, false, true),
_ => (false, false, false),
};
(deref_mut_ || !by_mut_ref) && !by_box && !by_value
} else {
false
}
}
fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
let mut out = String::new();
match item.inner {
clean::FunctionItem(clean::Function { ref decl, .. }) |
clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
clean::MethodItem(clean::Method { ref decl, .. }) |
clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
out = spotlight_decl(decl)?;
}
_ => {}
}
Ok(out)
}
fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
let mut out = String::new();
let mut trait_ = String::new();
if let Some(did) = decl.output.def_id() {
let c = cache();
if let Some(impls) = c.impls.get(&did) {
for i in impls {
let impl_ = i.inner_impl();
if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
if out.is_empty() {
out.push_str(
&format!("<h3 class=\"important\">Important traits for {}</h3>\
<code class=\"content\">",
impl_.for_));
trait_.push_str(&format!("{}", impl_.for_));
}
//use the "where" class here to make it small
out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
let t_did = impl_.trait_.def_id().unwrap();
for it in &impl_.items {
if let clean::TypedefItem(ref tydef, _) = it.inner {
out.push_str("<span class=\"where fmt-newline\"> ");
assoc_type(&mut out, it, &vec![],
Some(&tydef.type_),
AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
out.push_str(";</span>");
}
}
}
}
}
}
if !out.is_empty() {
out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
<span class='tooltiptext'>Important traits for {}</span></div>\
<div class=\"content hidden\">",
trait_));
out.push_str("</code></div></div>");
}
Ok(out)
}
fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
render_mode: RenderMode, outer_version: Option<&str>,
show_def_docs: bool) -> fmt::Result {
if render_mode == RenderMode::Normal {
let id = derive_id(match i.inner_impl().trait_ {
Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
None => "impl".to_string(),
});
write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
<tbody><tr><td><code>{}</code>",
id, i.inner_impl())?;
write!(w, "<a href='#{}' class='anchor'></a>", id)?;
write!(w, "</span></td><td><span class='out-of-band'>")?;
let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
write!(w, "<div class='ghost'></div>")?;
render_stability_since_raw(w, since, outer_version)?;
write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
l, "goto source code")?;
} else {
render_stability_since_raw(w, since, outer_version)?;
}
write!(w, "</span></td></tr></tbody></table></h3>")?;
if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
write!(w, "<div class='docblock'>{}</div>",
Markdown(&*dox, &i.impl_item.links()))?;
}
}
fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
link: AssocItemLink, render_mode: RenderMode,
is_default_item: bool, outer_version: Option<&str>,
trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
let item_type = item.type_();
let name = item.name.as_ref().unwrap();
let render_method_item: bool = match render_mode {
RenderMode::Normal => true,
RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
};
match item.inner {
clean::MethodItem(clean::Method { ref decl, .. }) |
clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
// Only render when the method is not static or we allow static methods
if render_method_item {
let id = derive_id(format!("{}.{}", item_type, name));
let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
write!(w, "{}", spotlight_decl(decl)?)?;
write!(w, "<span id='{}' class='invisible'>", ns_id)?;
write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
write!(w, "</code>")?;
if let Some(l) = (Item { cx, item }).src_href() {
write!(w, "</span></td><td><span class='out-of-band'>")?;
write!(w, "<div class='ghost'></div>")?;
render_stability_since_raw(w, item.stable_since(), outer_version)?;
write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
l, "goto source code")?;
} else {
write!(w, "</td><td>")?;
render_stability_since_raw(w, item.stable_since(), outer_version)?;
}
write!(w, "</td></tr></tbody></table></span></h4>")?;
}
}
clean::TypedefItem(ref tydef, _) => {
let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
write!(w, "</code></span></h4>\n")?;
}
clean::AssociatedConstItem(ref ty, ref default) => {
let id = derive_id(format!("{}.{}", item_type, name));
let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
write!(w, "</code></span></h4>\n")?;
}
clean::AssociatedTypeItem(ref bounds, ref default) => {
let id = derive_id(format!("{}.{}", item_type, name));
let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
write!(w, "</code></span></h4>\n")?;
}
clean::StrippedItem(..) => return Ok(()),
_ => panic!("can't make docs for trait item with name {:?}", item.name)
}
if render_method_item || render_mode == RenderMode::Normal {
let prefix = render_assoc_const_value(item);
if !is_default_item {
if let Some(t) = trait_ {
// The trait item may have been stripped so we might not
// find any documentation or stability for it.
if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
// We need the stability of the item from the trait
// because impls can't have a stability.
document_stability(w, cx, it)?;
if item.doc_value().is_some() {
document_full(w, item, cx, &prefix)?;
} else if show_def_docs {
// In case the item isn't documented,
// provide short documentation from the trait.
document_short(w, it, link, &prefix)?;
}
}
} else {
document_stability(w, cx, item)?;
if show_def_docs {
document_full(w, item, cx, &prefix)?;
}
}
} else {
document_stability(w, cx, item)?;
if show_def_docs {
document_short(w, item, link, &prefix)?;
}
}
}
Ok(())
}
let traits = &cache().traits;
let trait_ = i.trait_did().map(|did| &traits[&did]);
if !show_def_docs {
write!(w, "<span class='docblock autohide'>")?;
}
write!(w, "<div class='impl-items'>")?;
for trait_item in &i.inner_impl().items {
doc_impl_item(w, cx, trait_item, link, render_mode,
false, outer_version, trait_, show_def_docs)?;
}
fn render_default_items(w: &mut fmt::Formatter,
cx: &Context,
t: &clean::Trait,
i: &clean::Impl,
render_mode: RenderMode,
outer_version: Option<&str>,
show_def_docs: bool) -> fmt::Result {
for trait_item in &t.items {
let n = trait_item.name.clone();
if i.items.iter().find(|m| m.name == n).is_some() {
continue;
}
let did = i.trait_.as_ref().unwrap().def_id().unwrap();
let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
outer_version, None, show_def_docs)?;
}
Ok(())
}
// If we've implemented a trait, then also emit documentation for all
// default items which weren't overridden in the implementation block.
if let Some(t) = trait_ {
render_default_items(w, cx, t, &i.inner_impl(),
render_mode, outer_version, show_def_docs)?;
}
write!(w, "</div>")?;
if !show_def_docs {
write!(w, "</span>")?;
}
Ok(())
}
fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
t: &clean::Typedef) -> fmt::Result {
write!(w, "<pre class='rust typedef'>")?;
render_attributes(w, it)?;
write!(w, "type {}{}{where_clause} = {type_};</pre>",
it.name.as_ref().unwrap(),
t.generics,
where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
type_ = t.type_)?;
document(w, cx, it)?;
// Render any items associated directly to this alias, as otherwise they
// won't be visible anywhere in the docs. It would be nice to also show
// associated items from the aliased type (see discussion in #32077), but
// we need #14072 to make sense of the generics.
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
render_attributes(w, it)?;
write!(
w,
" {}type {};\n}}</pre>",
VisSpace(&it.visibility),
it.name.as_ref().unwrap(),
)?;
document(w, cx, it)?;
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
impl<'a> fmt::Display for Sidebar<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let cx = self.cx;
let it = self.item;
let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
|| it.is_enum() || it.is_mod() || it.is_typedef() {
write!(fmt, "<p class='location'>{}{}</p>",
match it.inner {
clean::StructItem(..) => "Struct ",
clean::TraitItem(..) => "Trait ",
clean::PrimitiveItem(..) => "Primitive Type ",
clean::UnionItem(..) => "Union ",
clean::EnumItem(..) => "Enum ",
clean::TypedefItem(..) => "Type Definition ",
clean::ForeignTypeItem => "Foreign Type ",
clean::ModuleItem(..) => if it.is_crate() {
"Crate "
} else {
"Module "
},
_ => "",
},
it.name.as_ref().unwrap())?;
}
if it.is_crate() {
if let Some(ref version) = cache().crate_version {
write!(fmt,
"<div class='block version'>\
<p>Version {}</p>\
</div>
<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
version,
it.name.as_ref().unwrap())?;
}
}
write!(fmt, "<div class=\"sidebar-elems\">")?;
match it.inner {
clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
_ => (),
}
// The sidebar is designed to display sibling functions, modules and
// other miscellaneous information. since there are lots of sibling
// items (and that causes quadratic growth in large modules),
// we refactor common parts into a shared JavaScript file per module.
// still, we don't move everything into JS because we want to preserve
// as much HTML as possible in order to allow non-JS-enabled browsers
// to navigate the documentation (though slightly inefficiently).
write!(fmt, "<p class='location'>")?;
for (i, name) in cx.current.iter().take(parentlen).enumerate() {
if i > 0 {
write!(fmt, "::<wbr>")?;
}
write!(fmt, "<a href='{}index.html'>{}</a>",
&cx.root_path()[..(cx.current.len() - i - 1) * 3],
*name)?;
}
write!(fmt, "</p>")?;
// Sidebar refers to the enclosing module, not this module.
let relpath = if it.is_mod() { "../" } else { "" };
write!(fmt,
"<script>window.sidebarCurrent = {{\
name: '{name}', \
ty: '{ty}', \
relpath: '{path}'\
}};</script>",
name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
ty = it.type_().css_class(),
path = relpath)?;
if parentlen == 0 {
// There is no sidebar-items.js beyond the crate root path
// FIXME maybe dynamic crate loading can be merged here
} else {
write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
path = relpath)?;
}
// Closes sidebar-elems div.
write!(fmt, "</div>")?;
Ok(())
}
}
fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
i.items.iter().filter_map(|item| {
match item.name {
// Maybe check with clean::Visibility::Public as well?
Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
if !for_deref || should_render_item(item, false) {
Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
} else {
None
}
}
_ => None,
}
}).collect::<Vec<_>>()
}
// The point is to url encode any potential character from a type with genericity.
fn small_url_encode(s: &str) -> String {
s.replace("<", "%3C")
.replace(">", "%3E")
.replace(" ", "%20")
.replace("?", "%3F")
.replace("'", "%27")
.replace("&", "%26")
.replace(",", "%2C")
.replace(":", "%3A")
.replace(";", "%3B")
.replace("[", "%5B")
.replace("]", "%5D")
.replace("\"", "%22")
}
fn sidebar_assoc_items(it: &clean::Item) -> String {
let mut out = String::new();
let c = cache();
if let Some(v) = c.impls.get(&it.def_id) {
let ret = v.iter()
.filter(|i| i.inner_impl().trait_.is_none())
.flat_map(|i| get_methods(i.inner_impl(), false))
.collect::<String>();
if !ret.is_empty() {
out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
</a><div class=\"sidebar-links\">{}</div>", ret));
}
if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
if let Some(impl_) = v.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
match item.inner {
clean::TypedefItem(ref t, true) => Some(&t.type_),
_ => None,
}
}).next() {
let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
c.primitive_locations.get(&prim).cloned()
})).and_then(|did| c.impls.get(&did));
if let Some(impls) = inner_impl {
out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
out.push_str(&format!("Methods from {}<Target={}>",
Escape(&format!("{:#}",
impl_.inner_impl().trait_.as_ref().unwrap())),
Escape(&format!("{:#}", target))));
out.push_str("</a>");
let ret = impls.iter()
.filter(|i| i.inner_impl().trait_.is_none())
.flat_map(|i| get_methods(i.inner_impl(), true))
.collect::<String>();
out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
}
}
}
let format_impls = |impls: Vec<&Impl>| {
let mut links = HashSet::new();
impls.iter()
.filter_map(|i| {
let is_negative_impl = is_negative_impl(i.inner_impl());
if let Some(ref i) = i.inner_impl().trait_ {
let i_display = format!("{:#}", i);
let out = Escape(&i_display);
let encoded = small_url_encode(&format!("{:#}", i));
let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
encoded,
if is_negative_impl { "!" } else { "" },
out);
if links.insert(generated.clone()) {
Some(generated)
} else {
None
}
} else {
None
}
})
.collect::<String>()
};
let (synthetic, concrete) = v
.iter()
.partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
let concrete_format = format_impls(concrete);
let synthetic_format = format_impls(synthetic);
if !concrete_format.is_empty() {
out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
Trait Implementations</a>");
out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
}
if !synthetic_format.is_empty() {
out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
Auto Trait Implementations</a>");
out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
}
}
}
out
}
fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
s: &clean::Struct) -> fmt::Result {
let mut sidebar = String::new();
let fields = get_struct_fields_name(&s.fields);
if !fields.is_empty() {
if let doctree::Plain = s.struct_type {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
<div class=\"sidebar-links\">{}</div>", fields));
}
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
}
Ok(())
}
fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
match item.inner {
clean::ItemEnum::ImplItem(ref i) => {
if let Some(ref trait_) = i.trait_ {
Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
} else {
None
}
},
_ => None,
}
}
fn is_negative_impl(i: &clean::Impl) -> bool {
i.polarity == Some(clean::ImplPolarity::Negative)
}
fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
t: &clean::Trait) -> fmt::Result {
let mut sidebar = String::new();
let types = t.items
.iter()
.filter_map(|m| {
match m.name {
Some(ref name) if m.is_associated_type() => {
Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
name=name))
}
_ => None,
}
})
.collect::<String>();
let consts = t.items
.iter()
.filter_map(|m| {
match m.name {
Some(ref name) if m.is_associated_const() => {
Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
name=name))
}
_ => None,
}
})
.collect::<String>();
let required = t.items
.iter()
.filter_map(|m| {
match m.name {
Some(ref name) if m.is_ty_method() => {
Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
name=name))
}
_ => None,
}
})
.collect::<String>();
let provided = t.items
.iter()
.filter_map(|m| {
match m.name {
Some(ref name) if m.is_method() => {
Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
}
_ => None,
}
})
.collect::<String>();
if !types.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
Associated Types</a><div class=\"sidebar-links\">{}</div>",
types));
}
if !consts.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
Associated Constants</a><div class=\"sidebar-links\">{}</div>",
consts));
}
if !required.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
Required Methods</a><div class=\"sidebar-links\">{}</div>",
required));
}
if !provided.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
Provided Methods</a><div class=\"sidebar-links\">{}</div>",
provided));
}
let c = cache();
if let Some(implementors) = c.implementors.get(&it.def_id) {
let res = implementors.iter()
.filter(|i| i.inner_impl().for_.def_id()
.map_or(false, |d| !c.paths.contains_key(&d)))
.filter_map(|i| {
match extract_for_impl_name(&i.impl_item) {
Some((ref name, ref url)) => {
Some(format!("<a href=\"#impl-{}\">{}</a>",
small_url_encode(url),
Escape(name)))
}
_ => None,
}
})
.collect::<String>();
if !res.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
Implementations on Foreign Types</a><div \
class=\"sidebar-links\">{}</div>",
res));
}
}
sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
if t.auto {
sidebar.push_str("<a class=\"sidebar-title\" \
href=\"#synthetic-implementors\">Auto Implementors</a>");
}
sidebar.push_str(&sidebar_assoc_items(it));
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
}
fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
_p: &clean::PrimitiveType) -> fmt::Result {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
}
Ok(())
}
fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
_t: &clean::Typedef) -> fmt::Result {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
}
Ok(())
}
fn get_struct_fields_name(fields: &[clean::Item]) -> String {
fields.iter()
.filter(|f| if let clean::StructFieldItem(..) = f.inner {
true
} else {
false
})
.filter_map(|f| match f.name {
Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
{name}</a>", name=name)),
_ => None,
})
.collect()
}
fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
u: &clean::Union) -> fmt::Result {
let mut sidebar = String::new();
let fields = get_struct_fields_name(&u.fields);
if !fields.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
<div class=\"sidebar-links\">{}</div>", fields));
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
}
Ok(())
}
fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
e: &clean::Enum) -> fmt::Result {
let mut sidebar = String::new();
let variants = e.variants.iter()
.filter_map(|v| match v.name {
Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
</a>", name = name)),
_ => None,
})
.collect::<String>();
if !variants.is_empty() {
sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
<div class=\"sidebar-links\">{}</div>", variants));
}
sidebar.push_str(&sidebar_assoc_items(it));
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
}
Ok(())
}
fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
match *ty {
ItemType::ExternCrate |
ItemType::Import => ("reexports", "Re-exports"),
ItemType::Module => ("modules", "Modules"),
ItemType::Struct => ("structs", "Structs"),
ItemType::Union => ("unions", "Unions"),
ItemType::Enum => ("enums", "Enums"),
ItemType::Function => ("functions", "Functions"),
ItemType::Typedef => ("types", "Type Definitions"),
ItemType::Static => ("statics", "Statics"),
ItemType::Constant => ("constants", "Constants"),
ItemType::Trait => ("traits", "Traits"),
ItemType::Impl => ("impls", "Implementations"),
ItemType::TyMethod => ("tymethods", "Type Methods"),
ItemType::Method => ("methods", "Methods"),
ItemType::StructField => ("fields", "Struct Fields"),
ItemType::Variant => ("variants", "Variants"),
ItemType::Macro => ("macros", "Macros"),
ItemType::Primitive => ("primitives", "Primitive Types"),
ItemType::AssociatedType => ("associated-types", "Associated Types"),
ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
ItemType::ForeignType => ("foreign-types", "Foreign Types"),
ItemType::Keyword => ("keywords", "Keywords"),
}
}
fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
items: &[clean::Item]) -> fmt::Result {
let mut sidebar = String::new();
if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
it.type_() == ItemType::Import) {
sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
id = "reexports",
name = "Re-exports"));
}
// ordering taken from item_module, reorder, where it prioritized elements in a certain order
// to print its headings
for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
let (short, name) = item_ty_to_strs(&myty);
sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
id = short,
name = name));
}
}
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
}
Ok(())
}
fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
let sidebar = sidebar_assoc_items(it);
if !sidebar.is_empty() {
write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
}
Ok(())
}
impl<'a> fmt::Display for Source<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Source(s) = *self;
let lines = s.lines().count();
let mut cols = 0;
let mut tmp = lines;
while tmp > 0 {
cols += 1;
tmp /= 10;
}
write!(fmt, "<pre class=\"line-numbers\">")?;
for i in 1..lines + 1 {
write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
}
write!(fmt, "</pre>")?;
write!(fmt, "{}",
highlight::render_with_highlighting(s, None, None, None, None))?;
Ok(())
}
}
fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
t: &clean::Macro) -> fmt::Result {
wrap_into_docblock(w, |w| {
w.write_str(&highlight::render_with_highlighting(&t.source,
Some("macro"),
None,
None,
None))
})?;
document(w, cx, it)
}
fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
it: &clean::Item,
_p: &clean::PrimitiveType) -> fmt::Result {
document(w, cx, it)?;
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
}
fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
it: &clean::Item,
_p: &str) -> fmt::Result {
document(w, cx, it)
}
const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
fn make_item_keywords(it: &clean::Item) -> String {
format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
}
fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
let decl = match item.inner {
clean::FunctionItem(ref f) => &f.decl,
clean::MethodItem(ref m) => &m.decl,
clean::TyMethodItem(ref m) => &m.decl,
_ => return None
};
let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
let output = match decl.output {
clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
_ => None
};
Some(IndexItemFunctionType { inputs: inputs, output: output })
}
fn get_index_type(clean_type: &clean::Type) -> Type {
let t = Type {
name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
generics: get_generics(clean_type),
};
t
}
/// Returns a list of all paths used in the type.
/// This is used to help deduplicate imported impls
/// for reexported types. If any of the contained
/// types are re-exported, we don't use the corresponding
/// entry from the js file, as inlining will have already
/// picked up the impl
fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
let mut out = Vec::new();
let mut visited = FxHashSet();
let mut work = VecDeque::new();
let cache = cache();
work.push_back(first_ty);
while let Some(ty) = work.pop_front() {
if !visited.insert(ty.clone()) {
continue;
}
match ty {
clean::Type::ResolvedPath { did, .. } => {
let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
match fqp {
Some(path) => {
out.push(path.join("::"));
},
_ => {}
};
},
clean::Type::Tuple(tys) => {
work.extend(tys.into_iter());
},
clean::Type::Slice(ty) => {
work.push_back(*ty);
}
clean::Type::Array(ty, _) => {
work.push_back(*ty);
},
clean::Type::Unique(ty) => {
work.push_back(*ty);
},
clean::Type::RawPointer(_, ty) => {
work.push_back(*ty);
},
clean::Type::BorrowedRef { type_, .. } => {
work.push_back(*type_);
},
clean::Type::QPath { self_type, trait_, .. } => {
work.push_back(*self_type);
work.push_back(*trait_);
},
_ => {}
}
};
out
}
fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
match *clean_type {
clean::ResolvedPath { ref path, .. } => {
let segments = &path.segments;
let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
"get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
clean_type, accept_generic
));
Some(path_segment.name.clone())
}
clean::Generic(ref s) if accept_generic => Some(s.clone()),
clean::Primitive(ref p) => Some(format!("{:?}", p)),
clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
// FIXME: add all from clean::Type.
_ => None
}
}
fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
clean_type.generics()
.and_then(|types| {
let r = types.iter()
.filter_map(|t| get_index_type_name(t, false))
.map(|s| s.to_ascii_lowercase())
.collect::<Vec<_>>();
if r.is_empty() {
None
} else {
Some(r)
}
})
}
pub fn cache() -> Arc<Cache> {
CACHE_KEY.with(|c| c.borrow().clone())
}
#[cfg(test)]
#[test]
fn test_unique_id() {
let input = ["foo", "examples", "examples", "method.into_iter","examples",
"method.into_iter", "foo", "main", "search", "methods",
"examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
"method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
"examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
let test = || {
let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
assert_eq!(&actual[..], expected);
};
test();
reset_ids(true);
test();
}
#[cfg(test)]
#[test]
fn test_name_key() {
assert_eq!(name_key("0"), ("", 0, 1));
assert_eq!(name_key("123"), ("", 123, 0));
assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
}
#[cfg(test)]
#[test]
fn test_name_sorting() {
let names = ["Apple",
"Banana",
"Fruit", "Fruit0", "Fruit00",
"Fruit1", "Fruit01",
"Fruit2", "Fruit02",
"Fruit20",
"Fruit100",
"Pear"];
let mut sorted = names.to_owned();
sorted.sort_by_key(|&s| name_key(s));
assert_eq!(names, sorted);
}
| 39.32139 | 100 | 0.496509 |
de15571a32f47fa12f6583363bc2348647a9be47 | 959 | use raylib::prelude::*;
use std::ffi::CString;
mod options;
pub fn main() {
let opt = options::Opt::new();
let (mut rl, thread) = opt.open_window("Camera 2D");
let (_w, _h) = (opt.width, opt.height);
let mut wb = rgui::WindowBox {
bounds: Rectangle::new(64.0, 64.0, 128.0, 72.0),
text: CString::new("Hello World").unwrap()
};
rl.set_target_fps(200);
let btn = rgui::Button {
bounds: Rectangle::new(72.0, 172.0 + 24.0, 64.0, 16.0),
text: CString::new("Click Me").unwrap()
};
let mut exit_program = false;
while !exit_program && !rl.window_should_close() {
let mut d = rl.begin_drawing(&thread);
d.clear_background(Color::WHITE);
if let rgui::DrawResult::Bool(b) = d.draw_gui(&wb) {
if b { exit_program = true; }
}
if let rgui::DrawResult::Bool(b) = d.draw_gui(&btn) {
if b { wb.bounds.x += 8.0; }
}
}
}
| 25.236842 | 63 | 0.550574 |
16a339cdcb530b22e99d455cc76ab740f06ae4f8 | 7,992 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module provides a simplified abstraction for working with
//! code blocks identified by their integer node-id. In particular,
//! it captures a common set of attributes that all "function-like
//! things" (represented by `FnLike` instances) share. For example,
//! all `FnLike` instances have a type signature (be it explicit or
//! inferred). And all `FnLike` instances have a body, i.e. the code
//! that is run when the function-like thing it represents is invoked.
//!
//! With the above abstraction in place, one can treat the program
//! text as a collection of blocks of code (and most such blocks are
//! nested within a uniquely determined `FnLike`), and users can ask
//! for the `Code` associated with a particular NodeId.
pub use self::Code::*;
use abi;
use ast::{Block, FnDecl, NodeId};
use ast;
use ast_map::{Node};
use ast_map;
use codemap::Span;
use visit;
/// An FnLikeNode is a Node that is like a fn, in that it has a decl
/// and a body (as well as a NodeId, a span, etc).
///
/// More specifically, it is one of either:
/// - A function item,
/// - A closure expr (i.e. an ExprClosure), or
/// - The default implementation for a trait method.
///
/// To construct one, use the `Code::from_node` function.
#[derive(Copy)]
pub struct FnLikeNode<'a> { node: ast_map::Node<'a> }
/// MaybeFnLike wraps a method that indicates if an object
/// corresponds to some FnLikeNode.
pub trait MaybeFnLike { fn is_fn_like(&self) -> bool; }
/// Components shared by fn-like things (fn items, methods, closures).
pub struct FnParts<'a> {
pub decl: &'a FnDecl,
pub body: &'a Block,
pub kind: visit::FnKind<'a>,
pub span: Span,
pub id: NodeId,
}
impl MaybeFnLike for ast::Item {
fn is_fn_like(&self) -> bool {
match self.node { ast::ItemFn(..) => true, _ => false, }
}
}
impl MaybeFnLike for ast::TraitItem {
fn is_fn_like(&self) -> bool {
match self.node { ast::MethodTraitItem(_, Some(_)) => true, _ => false, }
}
}
impl MaybeFnLike for ast::Expr {
fn is_fn_like(&self) -> bool {
match self.node {
ast::ExprClosure(..) => true,
_ => false,
}
}
}
/// Carries either an FnLikeNode or a Block, as these are the two
/// constructs that correspond to "code" (as in, something from which
/// we can construct a control-flow graph).
#[derive(Copy)]
pub enum Code<'a> {
FnLikeCode(FnLikeNode<'a>),
BlockCode(&'a Block),
}
impl<'a> Code<'a> {
pub fn id(&self) -> ast::NodeId {
match *self {
FnLikeCode(node) => node.id(),
BlockCode(block) => block.id,
}
}
/// Attempts to construct a Code from presumed FnLike or Block node input.
pub fn from_node(node: Node) -> Option<Code> {
fn new(node: Node) -> FnLikeNode { FnLikeNode { node: node } }
match node {
ast_map::NodeItem(item) if item.is_fn_like() =>
Some(FnLikeCode(new(node))),
ast_map::NodeTraitItem(tm) if tm.is_fn_like() =>
Some(FnLikeCode(new(node))),
ast_map::NodeImplItem(_) =>
Some(FnLikeCode(new(node))),
ast_map::NodeExpr(e) if e.is_fn_like() =>
Some(FnLikeCode(new(node))),
ast_map::NodeBlock(block) =>
Some(BlockCode(block)),
_ =>
None,
}
}
}
/// These are all the components one can extract from a fn item for
/// use when implementing FnLikeNode operations.
struct ItemFnParts<'a> {
ident: ast::Ident,
decl: &'a ast::FnDecl,
unsafety: ast::Unsafety,
abi: abi::Abi,
generics: &'a ast::Generics,
body: &'a Block,
id: ast::NodeId,
span: Span
}
/// These are all the components one can extract from a closure expr
/// for use when implementing FnLikeNode operations.
struct ClosureParts<'a> {
decl: &'a FnDecl,
body: &'a Block,
id: NodeId,
span: Span
}
impl<'a> ClosureParts<'a> {
fn new(d: &'a FnDecl, b: &'a Block, id: NodeId, s: Span) -> ClosureParts<'a> {
ClosureParts { decl: d, body: b, id: id, span: s }
}
}
impl<'a> FnLikeNode<'a> {
pub fn to_fn_parts(self) -> FnParts<'a> {
FnParts {
decl: self.decl(),
body: self.body(),
kind: self.kind(),
span: self.span(),
id: self.id(),
}
}
pub fn body(self) -> &'a Block {
self.handle(|i: ItemFnParts<'a>| &*i.body,
|_, _, _: &'a ast::MethodSig, body: &'a ast::Block, _| body,
|c: ClosureParts<'a>| c.body)
}
pub fn decl(self) -> &'a FnDecl {
self.handle(|i: ItemFnParts<'a>| &*i.decl,
|_, _, sig: &'a ast::MethodSig, _, _| &sig.decl,
|c: ClosureParts<'a>| c.decl)
}
pub fn span(self) -> Span {
self.handle(|i: ItemFnParts| i.span,
|_, _, _: &'a ast::MethodSig, _, span| span,
|c: ClosureParts| c.span)
}
pub fn id(self) -> NodeId {
self.handle(|i: ItemFnParts| i.id,
|id, _, _: &'a ast::MethodSig, _, _| id,
|c: ClosureParts| c.id)
}
pub fn kind(self) -> visit::FnKind<'a> {
let item = |p: ItemFnParts<'a>| -> visit::FnKind<'a> {
visit::FkItemFn(p.ident, p.generics, p.unsafety, p.abi)
};
let closure = |_: ClosureParts| {
visit::FkFnBlock
};
let method = |_, ident, sig: &'a ast::MethodSig, _, _| {
visit::FkMethod(ident, sig)
};
self.handle(item, method, closure)
}
fn handle<A, I, M, C>(self, item_fn: I, method: M, closure: C) -> A where
I: FnOnce(ItemFnParts<'a>) -> A,
M: FnOnce(NodeId, ast::Ident, &'a ast::MethodSig, &'a ast::Block, Span) -> A,
C: FnOnce(ClosureParts<'a>) -> A,
{
match self.node {
ast_map::NodeItem(i) => match i.node {
ast::ItemFn(ref decl, unsafety, abi, ref generics, ref block) =>
item_fn(ItemFnParts{
ident: i.ident, decl: &**decl, unsafety: unsafety, body: &**block,
generics: generics, abi: abi, id: i.id, span: i.span
}),
_ => panic!("item FnLikeNode that is not fn-like"),
},
ast_map::NodeTraitItem(ti) => match ti.node {
ast::MethodTraitItem(ref sig, Some(ref body)) => {
method(ti.id, ti.ident, sig, body, ti.span)
}
_ => panic!("trait method FnLikeNode that is not fn-like"),
},
ast_map::NodeImplItem(ii) => {
match ii.node {
ast::MethodImplItem(ref sig, ref body) => {
method(ii.id, ii.ident, sig, body, ii.span)
}
ast::TypeImplItem(_) |
ast::MacImplItem(_) => {
panic!("impl method FnLikeNode that is not fn-like")
}
}
}
ast_map::NodeExpr(e) => match e.node {
ast::ExprClosure(_, ref decl, ref block) =>
closure(ClosureParts::new(&**decl, &**block, e.id, e.span)),
_ => panic!("expr FnLikeNode that is not fn-like"),
},
_ => panic!("other FnLikeNode that is not fn-like"),
}
}
}
| 34.300429 | 90 | 0.550175 |
236a6e35631367a27ee5c7b48aceea81b5bd75f5 | 11,566 | use crate::{
behavior::raft::message::NewBlockRequest,
http::{
client_rpc::TxHttpRequest,
common::*,
config::{NetworkRouteTable, PeerId},
node_rpc::*,
},
};
use async_raft::{
raft::{
AppendEntriesRequest, AppendEntriesResponse, InstallSnapshotRequest,
InstallSnapshotResponse, VoteRequest, VoteResponse,
},
NodeId, RaftNetwork,
};
use async_trait::async_trait;
use futures::{
channel::{mpsc, oneshot},
future,
prelude::*,
};
use serde::{Deserialize, Serialize};
use slimchain_chain::{block_proposal::BlockProposal, consensus::raft::Block, role::Role};
use slimchain_common::{
error::{anyhow, bail, Result},
tx::TxTrait,
};
use slimchain_tx_state::TxProposal;
use slimchain_utils::{bytes::Bytes, record_event, serde::binary_encode};
use std::{marker::PhantomData, sync::Arc};
use tokio::{sync::RwLock, task::JoinHandle};
pub async fn fetch_leader_id(route_table: &NetworkRouteTable) -> Result<PeerId> {
let rand_client = route_table
.random_peer(&Role::Client)
.ok_or_else(|| anyhow!("Failed to find the client node."))
.and_then(|peer_id| route_table.peer_address(peer_id))?;
get_leader(rand_client).await
}
pub struct ClientNodeNetwork<Tx>
where
Tx: TxTrait + Serialize + for<'de> Deserialize<'de> + 'static,
{
route_table: NetworkRouteTable,
leader_id: RwLock<Option<PeerId>>,
_marker: PhantomData<Tx>,
}
impl<Tx> ClientNodeNetwork<Tx>
where
Tx: TxTrait + Serialize + for<'de> Deserialize<'de> + 'static,
{
pub fn new(route_table: NetworkRouteTable) -> Self {
Self {
route_table,
leader_id: RwLock::new(None),
_marker: PhantomData,
}
}
#[tracing::instrument(level = "debug", skip(self, tx_req))]
pub async fn forward_tx_to_storage_node(&self, tx_req: TxHttpRequest) {
let TxHttpRequest { req, shard_id } = tx_req;
let tx_req_id = req.id();
let storage_node_peer_id = match self.route_table.random_peer(&Role::Storage(shard_id)) {
Some(peer) => peer,
None => {
error!(%tx_req_id , "Failed to find the storage node. ShardId: {:?}", shard_id);
return;
}
};
debug_assert_ne!(storage_node_peer_id, self.route_table.peer_id());
let storage_node_addr = match self.route_table.peer_address(storage_node_peer_id) {
Ok(addr) => addr,
Err(_) => {
error!(%tx_req_id , "Failed to get the storage address. PeerId: {}", storage_node_peer_id);
return;
}
};
record_event!("tx_begin", "tx_id": tx_req_id);
let resp: Result<()> = send_post_request_using_binary(
&format!(
"http://{}/{}/{}",
storage_node_addr, NODE_RPC_ROUTE_PATH, STORAGE_TX_REQ_ROUTE_PATH
),
&req,
)
.await;
if let Err(e) = resp {
error!(
%tx_req_id,
"Failed to forward TX to storage node. Error: {}", e
);
}
}
pub async fn set_leader(&self, leader_id: PeerId) {
*self.leader_id.write().await = Some(leader_id);
}
#[allow(clippy::ptr_arg)]
#[tracing::instrument(level = "debug", skip(self, tx_proposals), err)]
pub async fn forward_tx_proposal_to_leader(
&self,
tx_proposals: &Vec<TxProposal<Tx>>,
) -> Result<()> {
let leader_id = *self.leader_id.read().await;
let leader_id = match leader_id {
Some(id) => id,
None => {
let id = fetch_leader_id(&self.route_table).await?;
*self.leader_id.write().await = Some(id);
id
}
};
debug_assert_ne!(leader_id, self.route_table.peer_id());
let addr = self.route_table.peer_address(leader_id)?;
match send_reqs_to_leader(addr, tx_proposals).await {
Err(e) => {
*self.leader_id.write().await = None;
Err(e)
}
Ok(()) => Ok(()),
}
}
#[allow(clippy::ptr_arg)]
#[tracing::instrument(level = "debug", skip(self, block_proposals), err)]
pub async fn broadcast_block_proposal_to_storage_node(
&self,
block_proposals: &Vec<BlockProposal<Block, Tx>>,
) -> Result<()> {
if block_proposals.is_empty() {
return Ok(());
}
let bytes = Bytes::from(binary_encode(block_proposals)?);
let reqs = self
.route_table
.role_table()
.iter()
.filter(|(role, _)| matches!(role, Role::Storage(_)))
.flat_map(|(_, list)| list.iter())
.filter_map(|&peer_id| match self.route_table.peer_address(peer_id) {
Ok(addr) => Some((
peer_id,
format!(
"http://{}/{}/{}",
addr, NODE_RPC_ROUTE_PATH, STORAGE_BLOCK_IMPORT_ROUTE_PATH
),
)),
Err(_) => {
warn!("Failed to get the peer address. PeerId: {}", peer_id);
None
}
})
.map(|(peer_id, uri)| {
let bytes = bytes.clone();
async move {
(
peer_id,
send_post_request_using_binary_bytes::<()>(&uri, bytes).await,
)
}
});
for (peer_id, resp) in future::join_all(reqs).await {
if let Err(e) = resp {
let begin_block_height = block_proposals
.first()
.expect("empty block proposals")
.get_block_height();
let end_block_height = block_proposals
.last()
.expect("empty block proposals")
.get_block_height();
error!(%begin_block_height, %end_block_height, %peer_id, "Failed to broadcast block proposal to storage node. Err: {:?}", e);
}
}
Ok(())
}
}
#[async_trait]
impl<Tx> RaftNetwork<NewBlockRequest<Tx>> for ClientNodeNetwork<Tx>
where
Tx: TxTrait + Serialize + for<'de> Deserialize<'de> + 'static,
{
#[tracing::instrument(level = "debug", skip(self, rpc))]
async fn append_entries(
&self,
target: NodeId,
rpc: AppendEntriesRequest<NewBlockRequest<Tx>>,
) -> Result<AppendEntriesResponse> {
let peer_id = PeerId::from(target);
debug_assert_ne!(peer_id, self.route_table.peer_id());
let addr = self.route_table.peer_address(peer_id)?;
send_post_request_using_binary(
&format!(
"http://{}/{}/{}",
addr, NODE_RPC_ROUTE_PATH, RAFT_APPEND_ENTRIES_ROUTE_PATH
),
&rpc,
)
.await
}
#[tracing::instrument(level = "debug", skip(self, rpc))]
async fn install_snapshot(
&self,
target: NodeId,
rpc: InstallSnapshotRequest,
) -> Result<InstallSnapshotResponse> {
let peer_id = PeerId::from(target);
debug_assert_ne!(peer_id, self.route_table.peer_id());
let addr = self.route_table.peer_address(peer_id)?;
send_post_request_using_binary(
&format!(
"http://{}/{}/{}",
addr, NODE_RPC_ROUTE_PATH, RAFT_INSTALL_SNAPSHOT_ROUTE_PATH
),
&rpc,
)
.await
}
#[tracing::instrument(level = "debug", skip(self, rpc))]
async fn vote(&self, target: NodeId, rpc: VoteRequest) -> Result<VoteResponse> {
let peer_id = PeerId::from(target);
debug_assert_ne!(peer_id, self.route_table.peer_id());
let addr = self.route_table.peer_address(peer_id)?;
send_post_request_using_binary(
&format!(
"http://{}/{}/{}",
addr, NODE_RPC_ROUTE_PATH, RAFT_VOTE_ROUTE_PATH
),
&rpc,
)
.await
}
}
pub struct ClientNodeNetworkWorker<Tx>
where
Tx: TxTrait + Serialize + for<'de> Deserialize<'de> + 'static,
{
req_handle: Option<JoinHandle<()>>,
req_tx: mpsc::UnboundedSender<TxHttpRequest>,
req_shutdown_tx: Option<oneshot::Sender<()>>,
block_proposal_handle: Option<JoinHandle<()>>,
block_proposal_tx: mpsc::UnboundedSender<BlockProposal<Block, Tx>>,
block_proposal_shutdown_tx: Option<oneshot::Sender<()>>,
}
impl<Tx> ClientNodeNetworkWorker<Tx>
where
Tx: TxTrait + Serialize + for<'de> Deserialize<'de> + 'static,
{
pub fn new(network: Arc<ClientNodeNetwork<Tx>>, async_broadcast_storage: bool) -> Self {
let (req_tx, req_rx) = mpsc::unbounded();
let req_fut = {
let network = network.clone();
req_rx.for_each_concurrent(64, move |req| {
let network = network.clone();
async move { network.forward_tx_to_storage_node(req).await }
})
};
let (req_shutdown_tx, req_shutdown_rx) = oneshot::channel();
let req_handle = tokio::spawn(async move {
tokio::select! {
_ = req_shutdown_rx => {}
_ = req_fut => {}
}
});
let (block_proposal_tx, block_proposal_rx) = mpsc::unbounded();
let mut block_proposal_rx = block_proposal_rx.ready_chunks(8);
let (block_proposal_shutdown_tx, mut block_proposal_shutdown_rx) = oneshot::channel();
let block_proposal_handle = if async_broadcast_storage {
Some(tokio::spawn(async move {
loop {
tokio::select! {
_ = &mut block_proposal_shutdown_rx => break,
Some(block_proposals) = block_proposal_rx.next() => {
network.broadcast_block_proposal_to_storage_node(&block_proposals).await.ok();
}
}
}
}))
} else {
None
};
Self {
req_handle: Some(req_handle),
req_tx,
req_shutdown_tx: Some(req_shutdown_tx),
block_proposal_handle,
block_proposal_tx,
block_proposal_shutdown_tx: Some(block_proposal_shutdown_tx),
}
}
pub fn get_req_tx(&self) -> mpsc::UnboundedSender<TxHttpRequest> {
self.req_tx.clone()
}
pub fn get_block_proposal_tx(&self) -> mpsc::UnboundedSender<BlockProposal<Block, Tx>> {
self.block_proposal_tx.clone()
}
pub async fn shutdown(&mut self) -> Result<()> {
self.req_tx.close_channel();
if let Some(shutdown_tx) = self.req_shutdown_tx.take() {
shutdown_tx.send(()).ok();
} else {
bail!("Already shutdown.");
}
if let Some(handler) = self.req_handle.take() {
handler.await?;
} else {
bail!("Already shutdown.");
}
self.block_proposal_tx.close_channel();
if let Some(shutdown_tx) = self.block_proposal_shutdown_tx.take() {
shutdown_tx.send(()).ok();
} else {
bail!("Already shutdown.");
}
if let Some(handler) = self.block_proposal_handle.take() {
handler.await?;
} else {
bail!("Already shutdown.");
}
Ok(())
}
}
| 33.045714 | 141 | 0.550579 |
1a6dd39b927df8fe179f0545f8f9db2b5b1e0fdf | 229 | //! <https://www.codewars.com/kata/55225023e1be1ec8bc000390/train/rust>
pub fn greet(input: &str) -> String {
if input == "Johnny" {
"Hello, my love!".into()
} else {
format!("Hello, {}!", input)
}
}
| 22.9 | 71 | 0.558952 |
628647cf07c14421b3d4fc54083656db14bfeff9 | 4,358 | // Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of substrate-subxt.
//
// subxt is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// subxt is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with substrate-subxt. If not, see <http://www.gnu.org/licenses/>.
//! Implements support for the pallet_balances module.
use std::fmt::Debug;
use futures::future::{
self,
Future,
};
use frame_support::Parameter;
use sp_runtime::traits::{
MaybeSerialize,
Member,
SimpleArithmetic,
};
use crate::{
error::Error,
frame::{
system::System,
Call,
},
Client,
};
/// The subset of the `pallet_balances::Trait` that a client must implement.
pub trait Balances: System {
/// The balance of an account.
type Balance: Parameter
+ Member
+ SimpleArithmetic
+ codec::Codec
+ Default
+ Copy
+ MaybeSerialize
+ Debug
+ From<<Self as System>::BlockNumber>;
}
/// Blanket impl for using existing runtime types
impl<T: frame_system::Trait + pallet_balances::Trait + Debug> Balances for T
where
<T as frame_system::Trait>::Header: serde::de::DeserializeOwned,
{
type Balance = T::Balance;
}
/// The Balances extension trait for the Client.
pub trait BalancesStore {
/// Balances type.
type Balances: Balances;
/// The 'free' balance of a given account.
///
/// This is the only balance that matters in terms of most operations on
/// tokens. It alone is used to determine the balance when in the contract
/// execution environment. When this balance falls below the value of
/// `ExistentialDeposit`, then the 'current account' is deleted:
/// specifically `FreeBalance`. Further, the `OnFreeBalanceZero` callback
/// is invoked, giving a chance to external modules to clean up data
/// associated with the deleted account.
///
/// `system::AccountNonce` is also deleted if `ReservedBalance` is also
/// zero. It also gets collapsed to zero if it ever becomes less than
/// `ExistentialDeposit`.
fn free_balance(
&self,
account_id: <Self::Balances as System>::AccountId,
) -> Box<dyn Future<Item = <Self::Balances as Balances>::Balance, Error = Error> + Send>;
}
impl<T: Balances + 'static, S: 'static> BalancesStore for Client<T, S> {
type Balances = T;
fn free_balance(
&self,
account_id: <Self::Balances as System>::AccountId,
) -> Box<dyn Future<Item = <Self::Balances as Balances>::Balance, Error = Error> + Send>
{
let free_balance_map = || {
Ok(self
.metadata()
.module("Balances")?
.storage("FreeBalance")?
.get_map::<
<Self::Balances as System>::AccountId,
<Self::Balances as Balances>::Balance>()?)
};
let map = match free_balance_map() {
Ok(map) => map,
Err(err) => return Box::new(future::err(err)),
};
Box::new(self.fetch_or(map.key(account_id), map.default()))
}
}
const MODULE: &str = "Balances";
const TRANSFER: &str = "transfer";
/// Arguments for transferring a balance
#[derive(codec::Encode)]
pub struct TransferArgs<T: Balances> {
to: <T as System>::Address,
#[codec(compact)]
amount: <T as Balances>::Balance,
}
/// Transfer some liquid free balance to another account.
///
/// `transfer` will set the `FreeBalance` of the sender and receiver.
/// It will decrease the total issuance of the system by the `TransferFee`.
/// If the sender's account is below the existential deposit as a result
/// of the transfer, the account will be reaped.
pub fn transfer<T: Balances>(
to: <T as System>::Address,
amount: <T as Balances>::Balance,
) -> Call<TransferArgs<T>> {
Call::new(MODULE, TRANSFER, TransferArgs { to, amount })
}
| 32.044118 | 93 | 0.64525 |
917310ac40aa41cbc49dfabf78d23738cbd561ed | 461 | use crate::riddler;
fn my_real_name() -> String {
"Bruce Wayne".to_string()
}
pub fn batman_quote() -> String {
// nobody will know
let _my_secret_identity = my_real_name();
// ask riddler for a riddle
let _riddle = riddler::difficult_riddle();
"Robin, you haven't fastened your safety bat-belt.".to_string()
}
pub fn advice() -> String {
"You've made a hasty generalization, Robin. It's a bad habit to get into.".to_string()
}
| 23.05 | 90 | 0.665944 |
8f5cb5acba916e049e291fdb587bfe4fcd6f843e | 4,935 | use core::fmt::Debug;
use core::mem;
use crate::elf;
use crate::endian;
use crate::pod::{Bytes, Pod};
use crate::read::util;
use crate::read::{self, Error, ReadError};
use super::FileHeader;
/// An iterator over the notes in an ELF section or segment.
#[derive(Debug)]
pub struct NoteIterator<'data, Elf>
where
Elf: FileHeader,
{
endian: Elf::Endian,
align: usize,
data: Bytes<'data>,
}
impl<'data, Elf> NoteIterator<'data, Elf>
where
Elf: FileHeader,
{
/// Returns `Err` if `align` is invalid.
pub(super) fn new(
endian: Elf::Endian,
align: Elf::Word,
data: &'data [u8],
) -> read::Result<Self> {
let align = match align.into() {
0u64..=4 => 4,
8 => 8,
_ => return Err(Error("Invalid ELF note alignment")),
};
// TODO: check data alignment?
Ok(NoteIterator {
endian,
align,
data: Bytes(data),
})
}
/// Returns the next note.
pub fn next(&mut self) -> read::Result<Option<Note<'data, Elf>>> {
let mut data = self.data;
if data.is_empty() {
return Ok(None);
}
let header = data
.read_at::<Elf::NoteHeader>(0)
.read_error("ELF note is too short")?;
// The name has no alignment requirement.
let offset = mem::size_of::<Elf::NoteHeader>();
let namesz = header.n_namesz(self.endian) as usize;
let name = data
.read_bytes_at(offset, namesz)
.read_error("Invalid ELF note namesz")?
.0;
// The descriptor must be aligned.
let offset = util::align(offset + namesz, self.align);
let descsz = header.n_descsz(self.endian) as usize;
let desc = data
.read_bytes_at(offset, descsz)
.read_error("Invalid ELF note descsz")?
.0;
// The next note (if any) must be aligned.
let offset = util::align(offset + descsz, self.align);
if data.skip(offset).is_err() {
data = Bytes(&[]);
}
self.data = data;
Ok(Some(Note { header, name, desc }))
}
}
/// A parsed `NoteHeader`.
#[derive(Debug)]
pub struct Note<'data, Elf>
where
Elf: FileHeader,
{
header: &'data Elf::NoteHeader,
name: &'data [u8],
desc: &'data [u8],
}
impl<'data, Elf: FileHeader> Note<'data, Elf> {
/// Return the `n_type` field of the `NoteHeader`.
///
/// The meaning of this field is determined by `name`.
pub fn n_type(&self, endian: Elf::Endian) -> u32 {
self.header.n_type(endian)
}
/// Return the `n_namesz` field of the `NoteHeader`.
pub fn n_namesz(&self, endian: Elf::Endian) -> u32 {
self.header.n_namesz(endian)
}
/// Return the `n_descsz` field of the `NoteHeader`.
pub fn n_descsz(&self, endian: Elf::Endian) -> u32 {
self.header.n_descsz(endian)
}
/// Return the bytes for the name field following the `NoteHeader`,
/// excluding any null terminator.
///
/// This field is usually a string including a null terminator
/// (but it is not required to be).
///
/// The length of this field (including any null terminator) is given by
/// `n_namesz`.
pub fn name(&self) -> &'data [u8] {
if let Some((last, name)) = self.name.split_last() {
if *last == 0 {
return name;
}
}
self.name
}
/// Return the bytes for the desc field following the `NoteHeader`.
///
/// The length of this field is given by `n_descsz`. The meaning
/// of this field is determined by `name` and `n_type`.
pub fn desc(&self) -> &'data [u8] {
self.desc
}
}
/// A trait for generic access to `NoteHeader32` and `NoteHeader64`.
#[allow(missing_docs)]
pub trait NoteHeader: Debug + Pod {
type Endian: endian::Endian;
fn n_namesz(&self, endian: Self::Endian) -> u32;
fn n_descsz(&self, endian: Self::Endian) -> u32;
fn n_type(&self, endian: Self::Endian) -> u32;
}
impl<Endian: endian::Endian> NoteHeader for elf::NoteHeader32<Endian> {
type Endian = Endian;
#[inline]
fn n_namesz(&self, endian: Self::Endian) -> u32 {
self.n_namesz.get(endian)
}
#[inline]
fn n_descsz(&self, endian: Self::Endian) -> u32 {
self.n_descsz.get(endian)
}
#[inline]
fn n_type(&self, endian: Self::Endian) -> u32 {
self.n_type.get(endian)
}
}
impl<Endian: endian::Endian> NoteHeader for elf::NoteHeader64<Endian> {
type Endian = Endian;
#[inline]
fn n_namesz(&self, endian: Self::Endian) -> u32 {
self.n_namesz.get(endian)
}
#[inline]
fn n_descsz(&self, endian: Self::Endian) -> u32 {
self.n_descsz.get(endian)
}
#[inline]
fn n_type(&self, endian: Self::Endian) -> u32 {
self.n_type.get(endian)
}
}
| 26.532258 | 76 | 0.568794 |
119fcca34a158105315d905eb235acc626f3f017 | 4,394 | use crate::state::Data;
use crate::state::State;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use tokio::io::{self, AsyncWrite};
/// The write half of the pipe which implements [`AsyncWrite`](https://docs.rs/tokio/0.2.16/tokio/io/trait.AsyncWrite.html).
pub struct PipeWriter {
pub(crate) state: Arc<Mutex<State>>,
}
impl PipeWriter {
/// Closes the pipe, any further read will return EOF and any further write will raise an error.
pub fn close(&self) -> io::Result<()> {
match self.state.lock() {
Ok(mut state) => {
state.closed = true;
self.wake_reader_half(&*state);
Ok(())
}
Err(err) => Err(io::Error::new(
io::ErrorKind::Other,
format!(
"{}: PipeWriter: Failed to lock the channel state: {}",
env!("CARGO_PKG_NAME"),
err
),
)),
}
}
/// It returns true if the next data chunk is written and consumed by the reader; Otherwise it returns false.
pub fn is_flushed(&self) -> io::Result<bool> {
let state = match self.state.lock() {
Ok(s) => s,
Err(err) => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"{}: PipeWriter: Failed to lock the channel state: {}",
env!("CARGO_PKG_NAME"),
err
),
));
}
};
Ok(state.done_cycle)
}
fn wake_reader_half(&self, state: &State) {
if let Some(ref waker) = state.reader_waker {
waker.clone().wake();
}
}
}
impl Drop for PipeWriter {
fn drop(&mut self) {
if let Err(err) = self.close() {
log::warn!(
"{}: PipeWriter: Failed to close the channel on drop: {}",
env!("CARGO_PKG_NAME"),
err
);
}
}
}
impl AsyncWrite for PipeWriter {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
let mut state;
match self.state.lock() {
Ok(s) => state = s,
Err(err) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
format!(
"{}: PipeWriter: Failed to lock the channel state: {}",
env!("CARGO_PKG_NAME"),
err
),
)))
}
}
if state.closed {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!(
"{}: PipeWriter: The channel is closed",
env!("CARGO_PKG_NAME")
),
)));
}
return if state.done_cycle {
state.data = Some(Data {
ptr: buf.as_ptr(),
len: buf.len(),
});
state.done_cycle = false;
state.writer_waker = Some(cx.waker().clone());
self.wake_reader_half(&*state);
Poll::Pending
} else {
if state.done_reading {
let read_bytes_len = state.read;
state.done_cycle = true;
state.read = 0;
state.writer_waker = None;
state.data = None;
state.done_reading = false;
Poll::Ready(Ok(read_bytes_len))
} else {
state.writer_waker = Some(cx.waker().clone());
Poll::Pending
}
};
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<io::Result<()>> {
match self.close() {
Ok(_) => Poll::Ready(Ok(())),
Err(err) => Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
format!(
"{}: PipeWriter: Failed to shutdown the channel: {}",
env!("CARGO_PKG_NAME"),
err
),
))),
}
}
}
| 30.303448 | 124 | 0.443787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.