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
|
---|---|---|---|---|---|
bb6579a7f82419f68d2e9afa0e604955da786727
| 2,915 |
use std::rc::Rc;
use std::fmt;
use super::*;
#[derive(Debug, Clone, PartialEq)]
pub enum StatementNode {
Expression(Expression),
Variable(Type, String, Option<Expression>),
Assignment(Expression, Expression),
Return(Option<Rc<Expression>>),
Implement(Expression, Expression),
Skip,
Break,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Statement {
pub node: StatementNode,
pub pos: Pos,
}
impl Statement {
pub fn new(node: StatementNode, pos: Pos) -> Self {
Statement {
node,
pos,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExpressionNode {
Int(u64),
Float(f64),
Str(String),
Char(char),
Bool(bool),
Unwrap(Rc<Expression>),
Neg(Rc<Expression>),
Not(Rc<Expression>),
Identifier(String),
Binary(Rc<Expression>, Operator, Rc<Expression>),
Array(Vec<Expression>),
Call(Rc<Expression>, Vec<Expression>),
Index(Rc<Expression>, Rc<Expression>),
Cast(Rc<Expression>, Type),
Block(Vec<Statement>),
Function(Vec<(String, Type)>, Type, Rc<Expression>, bool), // is_method: bool
If(Rc<Expression>, Rc<Expression>, Option<Vec<(Option<Expression>, Expression, Pos)>>),
While(Rc<Expression>, Rc<Expression>),
Module(Rc<Expression>),
Extern(Type, Option<String>),
Struct(String, Vec<(String, Type)>, String),
Initialization(Rc<Expression>, Vec<(String, Expression)>),
Empty,
EOF,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Expression {
pub node: ExpressionNode,
pub pos: Pos
}
impl Expression {
pub fn new(node: ExpressionNode, pos: Pos) -> Self {
Expression {
node,
pos,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Operator {
Add, Sub, Mul, Div, Mod, Pow, Concat, Eq, Lt, Gt, NEq, LtEq, GtEq, Or, And,
}
impl Operator {
pub fn from_str(operator: &str) -> Option<(Operator, u8)> {
use self::Operator::*;
let op_prec = match operator {
"or" => (Or, 0),
"and" => (And, 0),
"==" => (Eq, 1),
"<" => (Lt, 1),
">" => (Gt, 1),
"!=" => (NEq, 1),
"<=" => (LtEq, 1),
">=" => (GtEq, 1),
"+" => (Add, 2),
"-" => (Sub, 2),
"++" => (Concat, 2),
"*" => (Mul, 3),
"/" => (Div, 3),
"%" => (Mod, 3),
"^" => (Pow, 4),
_ => return None,
};
Some(op_prec)
}
pub fn as_str(&self) -> &str {
use self::Operator::*;
match *self {
Add => "+",
Sub => "-",
Concat => "++",
Pow => "^",
Mul => "*",
Div => "/",
Mod => "%",
Eq => "==",
Lt => "<",
Gt => ">",
NEq => "!=",
LtEq => "<=",
GtEq => ">=",
Or => "or",
And => "and",
}
}
}
impl fmt::Display for Operator {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
| 20.243056 | 89 | 0.513894 |
8ac5a72341c609d722dcae5c71243e6466541819
| 1,314 |
// Copyright (c) 2021 Quark Container 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.
use super::mm::*;
// Dumpability describes if and how core dumps should be created.
pub type Dumpability = i32;
// NotDumpable indicates that core dumps should never be created.
pub const NOT_DUMPABLE : Dumpability = 0;
// UserDumpable indicates that core dumps should be created, owned by
// the current user.
pub const USER_DUMPABLE : Dumpability = 1;
// RootDumpable indicates that core dumps should be created, owned by
// root.
pub const ROOT_DUMPABLE : Dumpability = 2;
impl MemoryManager {
pub fn Dumpability(&self) -> Dumpability {
return self.metadata.lock().dumpability;
}
pub fn SetDumpability(&self, d: Dumpability) {
self.metadata.lock().dumpability = d;
}
}
| 33.692308 | 75 | 0.729833 |
2109222c0603ace8e73397d20b1ad1c8822e480b
| 146 |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
pub mod swarm_config;
pub mod util;
| 18.25 | 44 | 0.739726 |
75160d530b5fdacdf96ddba9bb3c4d1860fba084
| 1,932 |
use errors::{bail, Result};
use minify_html::{minify, Cfg};
pub fn html(html: String) -> Result<String> {
let mut cfg = Cfg::spec_compliant();
cfg.keep_html_and_head_opening_tags = true;
let minified = minify(html.as_bytes(), &cfg);
match std::str::from_utf8(&minified) {
Ok(result) => Ok(result.to_string()),
Err(err) => bail!("Failed to convert bytes to string : {}", err),
}
}
#[cfg(test)]
mod tests {
use super::*;
// https://github.com/getzola/zola/issues/1292
#[test]
fn can_minify_html() {
let input = r#"
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>Example blog post</p>
FOO BAR
</body>
</html>
"#;
let expected = r#"<!doctype html><html><head><meta charset=utf-8><body><p>Example blog post</p> FOO BAR"#;
let res = html(input.to_owned()).unwrap();
assert_eq!(res, expected);
}
// https://github.com/getzola/zola/issues/1304
#[test]
fn can_minify_multibyte_characters() {
let input = r#"
俺が好きなのはキツネの…ケツねw
ー丁寧なインタネット生活の人より
"#;
let expected = r#"俺が好きなのはキツネの…ケツねw ー丁寧なインタネット生活の人より"#;
let res = html(input.to_owned()).unwrap();
assert_eq!(res, expected);
}
// https://github.com/getzola/zola/issues/1300
#[test]
fn can_minify_and_preserve_whitespace_in_pre_elements() {
let input = r#"
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<pre><code>fn main() {
println!("Hello, world!");
<span>loop {
println!("Hello, world!");
}</span>
}
</code></pre>
</body>
</html>
"#;
let expected = r#"<!doctype html><html><head><meta charset=utf-8><body><pre><code>fn main() {
println!("Hello, world!");
<span>loop {
println!("Hello, world!");
}</span>
}
</code></pre>"#;
let res = html(input.to_owned()).unwrap();
assert_eq!(res, expected);
}
}
| 22.729412 | 114 | 0.585404 |
11756b77ceb3f7554d5ed866babfa569cf540101
| 4,105 |
use crate::math::grid::{Direction, Grid};
use wasm_bindgen::prelude::*;
/**
* In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
*
* 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
* 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
* 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
* 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
* 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
* 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
* 32 98 81 28 64 23 67 10 [26] 38 40 67 59 54 70 66 18 38 64 70
* 67 26 20 68 02 62 12 20 95 [63] 94 39 63 08 40 91 66 49 94 21
* 24 55 58 05 66 73 99 26 97 17 [78] 78 96 83 14 88 34 89 63 72
* 21 36 23 09 75 00 76 44 20 45 35 [14] 00 61 33 97 34 31 33 95
* 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
* 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
* 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
* 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
* 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
* 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
* 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
* 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
* 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
* 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
*
* The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
*
* What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
*/
const INPUT: &str = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48";
#[wasm_bindgen]
pub fn solve_11(input: &str) -> i64 {
let grid = Grid::from(input);
let mut max: i64 = 0;
let mut max_product: i64 = 0;
for start in 0..grid.size() {
let pos = grid.get_position(start);
let to_check: Vec<Vec<i64>> = Direction::iter()
.filter_map(|dir| grid.get_values_in_direction(pos, dir, 4))
.collect();
for line in to_check {
let val: i64 = line.iter().sum();
if val > max {
max = val;
max_product = line.iter().product();
}
}
}
max_product
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn four_by_four_grid() {
assert_eq!(
solve_11(
"1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16"
),
43680
);
}
#[test]
fn five_by_five_grid() {
assert_eq!(
solve_11(
"1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25"
),
303600
);
}
#[test]
fn twenty_by_twenty_grid() {
assert_eq!(solve_11(INPUT), 70600674);
}
}
| 35.08547 | 135 | 0.589525 |
7a89d0775f4504e61ad4f1c0b82ba307b1d4687d
| 644 |
// 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.
mod create_column;
mod serializations;
mod wrapper;
| 35.777778 | 75 | 0.751553 |
f9d4a30994418c75365700f1b05ed789dca1bf6d
| 1,032 |
// c:legendPos
use super::LegendPositionValues;
use super::super::super::EnumValue;
use writer::driver::*;
use reader::driver::*;
use quick_xml::Reader;
use quick_xml::events::{BytesStart};
use quick_xml::Writer;
use std::io::Cursor;
#[derive(Default, Debug)]
pub struct LegendPosition {
val: EnumValue<LegendPositionValues>,
}
impl LegendPosition {
pub fn get_val(&self)-> &LegendPositionValues {
&self.val.get_value()
}
pub fn set_val(&mut self, value:LegendPositionValues)-> &mut LegendPosition {
self.val.set_value(value);
self
}
pub(crate) fn set_attributes(
&mut self,
_reader:&mut Reader<std::io::BufReader<std::fs::File>>,
e:&BytesStart
) {
self.val.set_value_string(get_attribute(e, b"val").unwrap());
}
pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) {
// c:legendPos
write_start_tag(writer, "c:legendPos", vec![
("val", &self.val.get_value_string()),
], true);
}
}
| 25.8 | 81 | 0.631783 |
61cbf871f7a1cee79941503fc888ff602e8d0a50
| 15,088 |
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::i32;
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use futures::{Future, Stream};
use grpcio::{
ChannelBuilder, EnvBuilder, Environment, ResourceQuota, Server as GrpcServer, ServerBuilder,
};
use kvproto::tikvpb::*;
use tokio_threadpool::{Builder as ThreadPoolBuilder, ThreadPool};
use tokio_timer::timer::Handle;
use crate::coprocessor::Endpoint;
use crate::server::gc_worker::GcWorker;
use crate::storage::lock_manager::LockManager;
use crate::storage::{Engine, Storage};
use engine_rocks::RocksEngine;
use raftstore::router::RaftStoreRouter;
use raftstore::store::SnapManager;
use tikv_util::security::SecurityManager;
use tikv_util::timer::GLOBAL_TIMER_HANDLE;
use tikv_util::worker::Worker;
use tikv_util::Either;
use super::load_statistics::*;
use super::raft_client::RaftClient;
use super::resolve::StoreAddrResolver;
use super::service::*;
use super::snap::{Runner as SnapHandler, Task as SnapTask};
use super::transport::ServerTransport;
use super::{Config, Result};
use crate::read_pool::ReadPool;
const LOAD_STATISTICS_SLOTS: usize = 4;
const LOAD_STATISTICS_INTERVAL: Duration = Duration::from_millis(100);
pub const GRPC_THREAD_PREFIX: &str = "grpc-server";
pub const READPOOL_NORMAL_THREAD_PREFIX: &str = "store-read-norm";
pub const STATS_THREAD_PREFIX: &str = "transport-stats";
/// The TiKV server
///
/// It hosts various internal components, including gRPC, the raftstore router
/// and a snapshot worker.
pub struct Server<T: RaftStoreRouter<RocksEngine> + 'static, S: StoreAddrResolver + 'static> {
env: Arc<Environment>,
/// A GrpcServer builder or a GrpcServer.
///
/// If the listening port is configured, the server will be started lazily.
builder_or_server: Option<Either<ServerBuilder, GrpcServer>>,
local_addr: SocketAddr,
// Transport.
trans: ServerTransport<T, S>,
raft_router: T,
// For sending/receiving snapshots.
snap_mgr: SnapManager<RocksEngine>,
snap_worker: Worker<SnapTask>,
// Currently load statistics is done in the thread.
stats_pool: Option<ThreadPool>,
grpc_thread_load: Arc<ThreadLoad>,
yatp_read_pool: Option<ReadPool>,
readpool_normal_thread_load: Arc<ThreadLoad>,
timer: Handle,
}
impl<T: RaftStoreRouter<RocksEngine>, S: StoreAddrResolver + 'static> Server<T, S> {
#[allow(clippy::too_many_arguments)]
pub fn new<E: Engine, L: LockManager>(
cfg: &Arc<Config>,
security_mgr: &Arc<SecurityManager>,
storage: Storage<E, L>,
cop: Endpoint<E>,
raft_router: T,
resolver: S,
snap_mgr: SnapManager<RocksEngine>,
gc_worker: GcWorker<E>,
yatp_read_pool: Option<ReadPool>,
) -> Result<Self> {
// A helper thread (or pool) for transport layer.
let stats_pool = if cfg.stats_concurrency > 0 {
Some(
ThreadPoolBuilder::new()
.pool_size(cfg.stats_concurrency)
.name_prefix(STATS_THREAD_PREFIX)
.build(),
)
} else {
None
};
let grpc_thread_load = Arc::new(ThreadLoad::with_threshold(cfg.heavy_load_threshold));
let readpool_normal_thread_load =
Arc::new(ThreadLoad::with_threshold(cfg.heavy_load_threshold));
let env = Arc::new(
EnvBuilder::new()
.cq_count(cfg.grpc_concurrency)
.name_prefix(thd_name!(GRPC_THREAD_PREFIX))
.build(),
);
let snap_worker = Worker::new("snap-handler");
let kv_service = KvService::new(
storage,
gc_worker,
cop,
raft_router.clone(),
snap_worker.scheduler(),
Arc::clone(&grpc_thread_load),
Arc::clone(&readpool_normal_thread_load),
cfg.enable_request_batch,
if cfg.enable_request_batch && cfg.request_batch_enable_cross_command {
Some(Duration::from(cfg.request_batch_wait_duration))
} else {
None
},
security_mgr.clone(),
);
let addr = SocketAddr::from_str(&cfg.addr)?;
let ip = format!("{}", addr.ip());
let mem_quota = ResourceQuota::new(Some("ServerMemQuota"))
.resize_memory(cfg.grpc_memory_pool_quota.0 as usize);
let channel_args = ChannelBuilder::new(Arc::clone(&env))
.stream_initial_window_size(cfg.grpc_stream_initial_window_size.0 as i32)
.max_concurrent_stream(cfg.grpc_concurrent_stream)
.max_receive_message_len(-1)
.set_resource_quota(mem_quota)
.max_send_message_len(-1)
.http2_max_ping_strikes(i32::MAX) // For pings without data from clients.
.keepalive_time(cfg.grpc_keepalive_time.into())
.keepalive_timeout(cfg.grpc_keepalive_timeout.into())
.build_args();
let builder = {
let mut sb = ServerBuilder::new(Arc::clone(&env))
.channel_args(channel_args)
.register_service(create_tikv(kv_service));
sb = security_mgr.bind(sb, &ip, addr.port());
Either::Left(sb)
};
let raft_client = Arc::new(RwLock::new(RaftClient::new(
Arc::clone(&env),
Arc::clone(cfg),
Arc::clone(security_mgr),
raft_router.clone(),
Arc::clone(&grpc_thread_load),
stats_pool.as_ref().map(|p| p.sender().clone()),
)));
let trans = ServerTransport::new(
raft_client,
snap_worker.scheduler(),
raft_router.clone(),
resolver,
);
let svr = Server {
env: Arc::clone(&env),
builder_or_server: Some(builder),
local_addr: addr,
trans,
raft_router,
snap_mgr,
snap_worker,
stats_pool,
grpc_thread_load,
yatp_read_pool,
readpool_normal_thread_load,
timer: GLOBAL_TIMER_HANDLE.clone(),
};
Ok(svr)
}
pub fn transport(&self) -> ServerTransport<T, S> {
self.trans.clone()
}
/// Register a gRPC service.
/// Register after starting, it fails and returns the service.
pub fn register_service(&mut self, svc: grpcio::Service) -> Option<grpcio::Service> {
match self.builder_or_server.take() {
Some(Either::Left(mut builder)) => {
builder = builder.register_service(svc);
self.builder_or_server = Some(Either::Left(builder));
None
}
Some(server) => {
self.builder_or_server = Some(server);
Some(svc)
}
None => Some(svc),
}
}
/// Build gRPC server and bind to address.
pub fn build_and_bind(&mut self) -> Result<SocketAddr> {
let sb = self.builder_or_server.take().unwrap().left().unwrap();
let server = sb.build()?;
let (host, port) = server.bind_addrs().next().unwrap();
let addr = SocketAddr::new(IpAddr::from_str(host)?, port);
self.local_addr = addr;
self.builder_or_server = Some(Either::Right(server));
Ok(addr)
}
/// Starts the TiKV server.
/// Notice: Make sure call `build_and_bind` first.
pub fn start(&mut self, cfg: Arc<Config>, security_mgr: Arc<SecurityManager>) -> Result<()> {
let snap_runner = SnapHandler::new(
Arc::clone(&self.env),
self.snap_mgr.clone(),
self.raft_router.clone(),
security_mgr,
Arc::clone(&cfg),
);
box_try!(self.snap_worker.start(snap_runner));
let mut grpc_server = self.builder_or_server.take().unwrap().right().unwrap();
info!("listening on addr"; "addr" => &self.local_addr);
grpc_server.start();
self.builder_or_server = Some(Either::Right(grpc_server));
let mut grpc_load_stats = {
let tl = Arc::clone(&self.grpc_thread_load);
ThreadLoadStatistics::new(LOAD_STATISTICS_SLOTS, GRPC_THREAD_PREFIX, tl)
};
let mut readpool_normal_load_stats = {
let tl = Arc::clone(&self.readpool_normal_thread_load);
ThreadLoadStatistics::new(LOAD_STATISTICS_SLOTS, READPOOL_NORMAL_THREAD_PREFIX, tl)
};
if let Some(ref p) = self.stats_pool {
p.spawn(
self.timer
.interval(Instant::now(), LOAD_STATISTICS_INTERVAL)
.map_err(|_| ())
.for_each(move |i| {
grpc_load_stats.record(i);
readpool_normal_load_stats.record(i);
Ok(())
}),
)
};
info!("TiKV is ready to serve");
Ok(())
}
/// Stops the TiKV server.
pub fn stop(&mut self) -> Result<()> {
self.snap_worker.stop();
if let Some(Either::Right(mut server)) = self.builder_or_server.take() {
server.shutdown();
}
if let Some(pool) = self.stats_pool.take() {
let _ = pool.shutdown_now().wait();
}
let _ = self.yatp_read_pool.take();
Ok(())
}
// Return listening address, this may only be used for outer test
// to get the real address because we may use "127.0.0.1:0"
// in test to avoid port conflict.
pub fn listening_addr(&self) -> SocketAddr {
self.local_addr
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::*;
use std::sync::mpsc::*;
use std::sync::*;
use std::time::Duration;
use super::*;
use super::super::resolve::{Callback as ResolveCallback, StoreAddrResolver};
use super::super::{Config, Result};
use crate::config::CoprReadPoolConfig;
use crate::coprocessor::{self, readpool_impl};
use crate::storage::TestStorageBuilder;
use raftstore::store::transport::Transport;
use raftstore::store::*;
use raftstore::Result as RaftStoreResult;
use engine_rocks::{RocksEngine, RocksSnapshot};
use kvproto::raft_cmdpb::RaftCmdRequest;
use kvproto::raft_serverpb::RaftMessage;
use tikv_util::security::SecurityConfig;
#[derive(Clone)]
struct MockResolver {
quick_fail: Arc<AtomicBool>,
addr: Arc<Mutex<Option<String>>>,
}
impl StoreAddrResolver for MockResolver {
fn resolve(&self, _: u64, cb: ResolveCallback) -> Result<()> {
if self.quick_fail.load(Ordering::SeqCst) {
return Err(box_err!("quick fail"));
}
let addr = self.addr.lock().unwrap();
cb(addr
.as_ref()
.map(|s| s.to_owned())
.ok_or(box_err!("not set")));
Ok(())
}
}
#[derive(Clone)]
struct TestRaftStoreRouter {
tx: Sender<usize>,
significant_msg_sender: Sender<SignificantMsg>,
}
impl RaftStoreRouter<RocksEngine> for TestRaftStoreRouter {
fn send_raft_msg(&self, _: RaftMessage) -> RaftStoreResult<()> {
self.tx.send(1).unwrap();
Ok(())
}
fn send_command(
&self,
_: RaftCmdRequest,
_: Callback<RocksSnapshot>,
) -> RaftStoreResult<()> {
self.tx.send(1).unwrap();
Ok(())
}
fn significant_send(&self, _: u64, msg: SignificantMsg) -> RaftStoreResult<()> {
self.significant_msg_sender.send(msg).unwrap();
Ok(())
}
fn casual_send(&self, _: u64, _: CasualMessage<RocksEngine>) -> RaftStoreResult<()> {
self.tx.send(1).unwrap();
Ok(())
}
fn broadcast_unreachable(&self, _: u64) {
let _ = self.tx.send(1);
}
}
fn is_unreachable_to(msg: &SignificantMsg, region_id: u64, to_peer_id: u64) -> bool {
if let SignificantMsg::Unreachable {
region_id: r_id,
to_peer_id: p_id,
} = *msg
{
region_id == r_id && to_peer_id == p_id
} else {
false
}
}
#[test]
// if this failed, unset the environmental variables 'http_proxy' and 'https_proxy', and retry.
fn test_peer_resolve() {
let mut cfg = Config::default();
cfg.addr = "127.0.0.1:0".to_owned();
let storage = TestStorageBuilder::new().build().unwrap();
let mut gc_worker =
GcWorker::new(storage.get_engine(), None, None, None, Default::default());
gc_worker.start().unwrap();
let (tx, rx) = mpsc::channel();
let (significant_msg_sender, significant_msg_receiver) = mpsc::channel();
let router = TestRaftStoreRouter {
tx,
significant_msg_sender,
};
let quick_fail = Arc::new(AtomicBool::new(false));
let cfg = Arc::new(cfg);
let security_mgr = Arc::new(SecurityManager::new(&SecurityConfig::default()).unwrap());
let cop_read_pool = ReadPool::from(readpool_impl::build_read_pool_for_test(
&CoprReadPoolConfig::default_for_test(),
storage.get_engine(),
));
let cop = coprocessor::Endpoint::new(&cfg, cop_read_pool.handle());
let addr = Arc::new(Mutex::new(None));
let mut server = Server::new(
&cfg,
&security_mgr,
storage,
cop,
router,
MockResolver {
quick_fail: Arc::clone(&quick_fail),
addr: Arc::clone(&addr),
},
SnapManager::new("", None),
gc_worker,
None,
)
.unwrap();
server.build_and_bind().unwrap();
server.start(cfg, security_mgr).unwrap();
let mut trans = server.transport();
trans.report_unreachable(RaftMessage::default());
let mut resp = significant_msg_receiver.try_recv().unwrap();
assert!(is_unreachable_to(&resp, 0, 0), "{:?}", resp);
let mut msg = RaftMessage::default();
msg.set_region_id(1);
trans.send(msg.clone()).unwrap();
trans.flush();
resp = significant_msg_receiver.try_recv().unwrap();
assert!(is_unreachable_to(&resp, 1, 0), "{:?}", resp);
*addr.lock().unwrap() = Some(format!("{}", server.listening_addr()));
trans.send(msg.clone()).unwrap();
trans.flush();
assert!(rx.recv_timeout(Duration::from_secs(5)).is_ok());
msg.mut_to_peer().set_store_id(2);
msg.set_region_id(2);
quick_fail.store(true, Ordering::SeqCst);
trans.send(msg).unwrap();
trans.flush();
resp = significant_msg_receiver.try_recv().unwrap();
assert!(is_unreachable_to(&resp, 2, 0), "{:?}", resp);
server.stop().unwrap();
}
}
| 34.213152 | 99 | 0.584173 |
38f4e4687a99b6358b946eb7ced49fd7796bcb2e
| 13,929 |
// Copyright 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.
//! Bit fiddling on positive IEEE 754 floats. Negative numbers aren't and needn't be handled.
//! Normal floating point numbers have a canonical representation as (frac, exp) such that the
//! value is 2<sup>exp</sup> * (1 + sum(frac[N-i] / 2<sup>i</sup>)) where N is the number of bits.
//! Subnormals are slightly different and weird, but the same principle applies.
//!
//! Here, however, we represent them as (sig, k) with f positive, such that the value is f *
//! 2<sup>e</sup>. Besides making the "hidden bit" explicit, this changes the exponent by the
//! so-called mantissa shift.
//!
//! Put another way, normally floats are written as (1) but here they are written as (2):
//!
//! 1. `1.101100...11 * 2^m`
//! 2. `1101100...11 * 2^n`
//!
//! We call (1) the **fractional representation** and (2) the **integral representation**.
//!
//! Many functions in this module only handle normal numbers. The dec2flt routines conservatively
//! take the universally-correct slow path (Algorithm M) for very small and very large numbers.
//! That algorithm needs only next_float() which does handle subnormals and zeros.
use cmp::Ordering::{Less, Equal, Greater};
use convert::{TryFrom, TryInto};
use ops::{Add, Mul, Div, Neg};
use fmt::{Debug, LowerExp};
use num::diy_float::Fp;
use num::FpCategory::{Infinite, Zero, Subnormal, Normal, Nan};
use num::FpCategory;
use num::dec2flt::num::{self, Big};
use num::dec2flt::table;
#[derive(Copy, Clone, Debug)]
pub struct Unpacked {
pub sig: u64,
pub k: i16,
}
impl Unpacked {
pub fn new(sig: u64, k: i16) -> Self {
Unpacked { sig, k }
}
}
/// A helper trait to avoid duplicating basically all the conversion code for `f32` and `f64`.
///
/// See the parent module's doc comment for why this is necessary.
///
/// Should **never ever** be implemented for other types or be used outside the dec2flt module.
pub trait RawFloat
: Copy
+ Debug
+ LowerExp
+ Mul<Output=Self>
+ Div<Output=Self>
+ Neg<Output=Self>
{
const INFINITY: Self;
const NAN: Self;
const ZERO: Self;
/// Type used by `to_bits` and `from_bits`.
type Bits: Add<Output = Self::Bits> + From<u8> + TryFrom<u64>;
/// Raw transmutation to integer.
fn to_bits(self) -> Self::Bits;
/// Raw transmutation from integer.
fn from_bits(v: Self::Bits) -> Self;
/// Returns the category that this number falls into.
fn classify(self) -> FpCategory;
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8);
/// Decode the float.
fn unpack(self) -> Unpacked;
/// Cast from a small integer that can be represented exactly. Panic if the integer can't be
/// represented, the other code in this module makes sure to never let that happen.
fn from_int(x: u64) -> Self;
/// Get the value 10<sup>e</sup> from a pre-computed table.
/// Panics for `e >= CEIL_LOG5_OF_MAX_SIG`.
fn short_fast_pow10(e: usize) -> Self;
/// What the name says. It's easier to hard code than juggling intrinsics and
/// hoping LLVM constant folds it.
const CEIL_LOG5_OF_MAX_SIG: i16;
// A conservative bound on the decimal digits of inputs that can't produce overflow or zero or
/// subnormals. Probably the decimal exponent of the maximum normal value, hence the name.
const MAX_NORMAL_DIGITS: usize;
/// When the most significant decimal digit has a place value greater than this, the number
/// is certainly rounded to infinity.
const INF_CUTOFF: i64;
/// When the most significant decimal digit has a place value less than this, the number
/// is certainly rounded to zero.
const ZERO_CUTOFF: i64;
/// The number of bits in the exponent.
const EXP_BITS: u8;
/// The number of bits in the significand, *including* the hidden bit.
const SIG_BITS: u8;
/// The number of bits in the significand, *excluding* the hidden bit.
const EXPLICIT_SIG_BITS: u8;
/// The maximum legal exponent in fractional representation.
const MAX_EXP: i16;
/// The minimum legal exponent in fractional representation, excluding subnormals.
const MIN_EXP: i16;
/// `MAX_EXP` for integral representation, i.e., with the shift applied.
const MAX_EXP_INT: i16;
/// `MAX_EXP` encoded (i.e., with offset bias)
const MAX_ENCODED_EXP: i16;
/// `MIN_EXP` for integral representation, i.e., with the shift applied.
const MIN_EXP_INT: i16;
/// The maximum normalized significand in integral representation.
const MAX_SIG: u64;
/// The minimal normalized significand in integral representation.
const MIN_SIG: u64;
}
// Mostly a workaround for #34344.
macro_rules! other_constants {
($type: ident) => {
const EXPLICIT_SIG_BITS: u8 = Self::SIG_BITS - 1;
const MAX_EXP: i16 = (1 << (Self::EXP_BITS - 1)) - 1;
const MIN_EXP: i16 = -Self::MAX_EXP + 1;
const MAX_EXP_INT: i16 = Self::MAX_EXP - (Self::SIG_BITS as i16 - 1);
const MAX_ENCODED_EXP: i16 = (1 << Self::EXP_BITS) - 1;
const MIN_EXP_INT: i16 = Self::MIN_EXP - (Self::SIG_BITS as i16 - 1);
const MAX_SIG: u64 = (1 << Self::SIG_BITS) - 1;
const MIN_SIG: u64 = 1 << (Self::SIG_BITS - 1);
const INFINITY: Self = $crate::$type::INFINITY;
const NAN: Self = $crate::$type::NAN;
const ZERO: Self = 0.0;
}
}
impl RawFloat for f32 {
type Bits = u32;
const SIG_BITS: u8 = 24;
const EXP_BITS: u8 = 8;
const CEIL_LOG5_OF_MAX_SIG: i16 = 11;
const MAX_NORMAL_DIGITS: usize = 35;
const INF_CUTOFF: i64 = 40;
const ZERO_CUTOFF: i64 = -48;
other_constants!(f32);
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits = self.to_bits();
let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
let mantissa = if exponent == 0 {
(bits & 0x7fffff) << 1
} else {
(bits & 0x7fffff) | 0x800000
};
// Exponent bias + mantissa shift
exponent -= 127 + 23;
(mantissa as u64, exponent, sign)
}
fn unpack(self) -> Unpacked {
let (sig, exp, _sig) = self.integer_decode();
Unpacked::new(sig, exp)
}
fn from_int(x: u64) -> f32 {
// rkruppe is uncertain whether `as` rounds correctly on all platforms.
debug_assert!(x as f32 == fp_to_float(Fp { f: x, e: 0 }));
x as f32
}
fn short_fast_pow10(e: usize) -> Self {
table::F32_SHORT_POWERS[e]
}
fn classify(self) -> FpCategory { self.classify() }
fn to_bits(self) -> Self::Bits { self.to_bits() }
fn from_bits(v: Self::Bits) -> Self { Self::from_bits(v) }
}
impl RawFloat for f64 {
type Bits = u64;
const SIG_BITS: u8 = 53;
const EXP_BITS: u8 = 11;
const CEIL_LOG5_OF_MAX_SIG: i16 = 23;
const MAX_NORMAL_DIGITS: usize = 305;
const INF_CUTOFF: i64 = 310;
const ZERO_CUTOFF: i64 = -326;
other_constants!(f64);
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits = self.to_bits();
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
(mantissa, exponent, sign)
}
fn unpack(self) -> Unpacked {
let (sig, exp, _sig) = self.integer_decode();
Unpacked::new(sig, exp)
}
fn from_int(x: u64) -> f64 {
// rkruppe is uncertain whether `as` rounds correctly on all platforms.
debug_assert!(x as f64 == fp_to_float(Fp { f: x, e: 0 }));
x as f64
}
fn short_fast_pow10(e: usize) -> Self {
table::F64_SHORT_POWERS[e]
}
fn classify(self) -> FpCategory { self.classify() }
fn to_bits(self) -> Self::Bits { self.to_bits() }
fn from_bits(v: Self::Bits) -> Self { Self::from_bits(v) }
}
/// Convert an Fp to the closest machine float type.
/// Does not handle subnormal results.
pub fn fp_to_float<T: RawFloat>(x: Fp) -> T {
let x = x.normalize();
// x.f is 64 bit, so x.e has a mantissa shift of 63
let e = x.e + 63;
if e > T::MAX_EXP {
panic!("fp_to_float: exponent {} too large", e)
} else if e > T::MIN_EXP {
encode_normal(round_normal::<T>(x))
} else {
panic!("fp_to_float: exponent {} too small", e)
}
}
/// Round the 64-bit significand to T::SIG_BITS bits with half-to-even.
/// Does not handle exponent overflow.
pub fn round_normal<T: RawFloat>(x: Fp) -> Unpacked {
let excess = 64 - T::SIG_BITS as i16;
let half: u64 = 1 << (excess - 1);
let (q, rem) = (x.f >> excess, x.f & ((1 << excess) - 1));
assert_eq!(q << excess | rem, x.f);
// Adjust mantissa shift
let k = x.e + excess;
if rem < half {
Unpacked::new(q, k)
} else if rem == half && (q % 2) == 0 {
Unpacked::new(q, k)
} else if q == T::MAX_SIG {
Unpacked::new(T::MIN_SIG, k + 1)
} else {
Unpacked::new(q + 1, k)
}
}
/// Inverse of `RawFloat::unpack()` for normalized numbers.
/// Panics if the significand or exponent are not valid for normalized numbers.
pub fn encode_normal<T: RawFloat>(x: Unpacked) -> T {
debug_assert!(T::MIN_SIG <= x.sig && x.sig <= T::MAX_SIG,
"encode_normal: significand not normalized");
// Remove the hidden bit
let sig_enc = x.sig & !(1 << T::EXPLICIT_SIG_BITS);
// Adjust the exponent for exponent bias and mantissa shift
let k_enc = x.k + T::MAX_EXP + T::EXPLICIT_SIG_BITS as i16;
debug_assert!(k_enc != 0 && k_enc < T::MAX_ENCODED_EXP,
"encode_normal: exponent out of range");
// Leave sign bit at 0 ("+"), our numbers are all positive
let bits = (k_enc as u64) << T::EXPLICIT_SIG_BITS | sig_enc;
T::from_bits(bits.try_into().unwrap_or_else(|_| unreachable!()))
}
/// Construct a subnormal. A mantissa of 0 is allowed and constructs zero.
pub fn encode_subnormal<T: RawFloat>(significand: u64) -> T {
assert!(significand < T::MIN_SIG, "encode_subnormal: not actually subnormal");
// Encoded exponent is 0, the sign bit is 0, so we just have to reinterpret the bits.
T::from_bits(significand.try_into().unwrap_or_else(|_| unreachable!()))
}
/// Approximate a bignum with an Fp. Rounds within 0.5 ULP with half-to-even.
pub fn big_to_fp(f: &Big) -> Fp {
let end = f.bit_length();
assert!(end != 0, "big_to_fp: unexpectedly, input is zero");
let start = end.saturating_sub(64);
let leading = num::get_bits(f, start, end);
// We cut off all bits prior to the index `start`, i.e., we effectively right-shift by
// an amount of `start`, so this is also the exponent we need.
let e = start as i16;
let rounded_down = Fp { f: leading, e }.normalize();
// Round (half-to-even) depending on the truncated bits.
match num::compare_with_half_ulp(f, start) {
Less => rounded_down,
Equal if leading % 2 == 0 => rounded_down,
Equal | Greater => match leading.checked_add(1) {
Some(f) => Fp { f, e }.normalize(),
None => Fp { f: 1 << 63, e: e + 1 },
}
}
}
/// Find the largest floating point number strictly smaller than the argument.
/// Does not handle subnormals, zero, or exponent underflow.
pub fn prev_float<T: RawFloat>(x: T) -> T {
match x.classify() {
Infinite => panic!("prev_float: argument is infinite"),
Nan => panic!("prev_float: argument is NaN"),
Subnormal => panic!("prev_float: argument is subnormal"),
Zero => panic!("prev_float: argument is zero"),
Normal => {
let Unpacked { sig, k } = x.unpack();
if sig == T::MIN_SIG {
encode_normal(Unpacked::new(T::MAX_SIG, k - 1))
} else {
encode_normal(Unpacked::new(sig - 1, k))
}
}
}
}
// Find the smallest floating point number strictly larger than the argument.
// This operation is saturating, i.e. next_float(inf) == inf.
// Unlike most code in this module, this function does handle zero, subnormals, and infinities.
// However, like all other code here, it does not deal with NaN and negative numbers.
pub fn next_float<T: RawFloat>(x: T) -> T {
match x.classify() {
Nan => panic!("next_float: argument is NaN"),
Infinite => T::INFINITY,
// This seems too good to be true, but it works.
// 0.0 is encoded as the all-zero word. Subnormals are 0x000m...m where m is the mantissa.
// In particular, the smallest subnormal is 0x0...01 and the largest is 0x000F...F.
// The smallest normal number is 0x0010...0, so this corner case works as well.
// If the increment overflows the mantissa, the carry bit increments the exponent as we
// want, and the mantissa bits become zero. Because of the hidden bit convention, this
// too is exactly what we want!
// Finally, f64::MAX + 1 = 7eff...f + 1 = 7ff0...0 = f64::INFINITY.
Zero | Subnormal | Normal => {
T::from_bits(x.to_bits() + T::Bits::from(1u8))
}
}
}
| 37.443548 | 98 | 0.627324 |
0aa8d77ad8a10178ea24c253486b7258564747c8
| 1,769 |
use raytracing::{
rand_f64, write_sampled_color, Camera, Color, Hittable, HittableList, Point3, Ray, Sphere, Vec3,
};
use std::rc::Rc;
fn ray_color(r: Ray, h: &dyn Hittable) -> Color {
if let Some(hit_record) = h.hit(r, 0.0, f64::INFINITY) {
return 0.5 * (hit_record.normal + Color::new(1.0, 1.0, 1.0));
}
let unit_direction = Vec3::unit(r.direction());
// t = y mapped to the range 0..1
let t = 0.5 * (unit_direction.y() + 1.0);
// linear blend of blue to white
(1.0 - t) * Color::new(1.0, 1.0, 1.0) + t * Color::new(0.5, 0.7, 1.0)
}
fn main() {
// image
let aspect_ratio = 16.0 / 9.0;
let image_width = 400u32;
let image_height = (image_width as f64 / aspect_ratio) as u32;
let samples_per_pixel = 100u32;
// world
let mut world = HittableList::default();
world.add(Rc::new(Sphere::new(Point3::new(0.0, 0.0, -1.0), 0.5)));
world.add(Rc::new(Sphere::new(Point3::new(0.0, -100.5, -1.0), 100.0)));
// camera
let cam = Camera::default();
// PPM image format specifications
println!("P3"); // colors are in ascii
println!("{} {}", image_width, image_height);
println!("{}", 255);
for y in (0..image_height).rev() {
eprintln!("Scanlines remaining: {}", y);
for x in 0..image_width {
let mut pixel_color = Color::zero();
for _s in 0..samples_per_pixel {
let x_percent = (x as f64 + rand_f64()) / (image_width as f64);
let y_percent = (y as f64 + rand_f64()) / (image_height as f64);
let r = cam.get_ray(x_percent, y_percent);
pixel_color += ray_color(r, &world);
}
write_sampled_color(pixel_color, samples_per_pixel);
}
}
}
| 34.686275 | 100 | 0.570379 |
ab37ff60044c10e3182de0eafe2b604a5d51f53e
| 33,979 |
use super::*;
/// The different ways a namespace is introduced by a use statement.
#[derive(Debug, Clone, PartialEq)]
pub enum NameIdentifier {
/// When the identifier is implicit from the path. For example, `use a/b` introduces `b`.
Implicit(Identifier),
/// When the identifier is an alias. For example, `use a/b as c` introduces `c`.
Alias(Identifier),
}
type Alias = Identifier;
#[derive(Debug, Clone, PartialEq)]
pub struct CaseBranch {
pub pattern: Identifier,
pub variable: Option<Identifier>,
pub body: Statement,
}
/// The different kinds of [Statement]s.
///
/// There are both shorter statements like `a = b + 1` as well as longer
/// statements like `if a { ... } else { ...}`. The variants here include
/// examples of how they look in the code.
///
/// Note that this shouldn't be read as a formal language specification.
#[derive(Debug, Clone, PartialEq)]
pub enum StatementKind {
/// "Imports" another file.
///
/// `use <file>`.
/// `use /<file>`.
/// `use <folder>/`.
/// `use <folder>/<file>`.
/// `use / as <alias>`.
/// `use <file> as <alias>`.
/// `use <folder>/ as <alias>`.
Use {
path: Identifier,
name: NameIdentifier,
file: PathBuf,
},
/// "Imports" variables from another file.
///
/// `from <file> use <var1>`.
/// `from <file> use <var1>, <var2>`.
/// `from <file> use (<var1>, <var2>)`.
/// `from <file> use <var1> as <alias>`.
FromUse {
path: Identifier,
imports: Vec<(Identifier, Option<Alias>)>,
file: PathBuf,
},
/// Defines a new Blob.
///
/// `A :: blob { <field>.. }`.
Blob {
name: String,
fields: HashMap<String, Type>,
},
/// Defines a new Enum.
///
/// `A :: enum <variant>.. end`.
Enum {
name: String,
variants: HashMap<String, Type>,
},
/// Assigns to a variable (`a = <expression>`), optionally with an operator
/// applied (`a += <expression>`)
Assignment {
kind: Op,
target: Assignable,
value: Expression,
},
/// Defines a new variable.
///
/// Example: `a := <expression>`.
///
/// Valid definition operators are `::`, `:=` and `: <type> =`.
Definition {
ident: Identifier,
kind: VarKind,
ty: Type,
value: Expression,
},
/// Defines a an external variable - here the type is required.
///
/// Example: `a: int = external`.
///
/// Valid definition operators are `: <type> :`, and `: <type> =`.
ExternalDefinition {
ident: Identifier,
kind: VarKind,
ty: Type,
},
/// Makes your code go either here or there.
///
/// `if <expression> <statement> [else <statement>]`.
If {
condition: Expression,
pass: Box<Statement>,
fail: Box<Statement>,
},
/// A super branchy branch.
///
/// `case <expression> do (<pattern> [<variable] <statement>)* [else <statement>] end`.
Case {
to_match: Expression,
branches: Vec<CaseBranch>,
fall_through: Box<Statement>,
},
/// Do something as long as something else evaluates to true.
///
/// `loop <expression> <statement>`.
Loop {
condition: Expression,
body: Box<Statement>,
},
/// Jump out of a loop.
///
/// `break`.
Break,
/// Go back to the start of the loop.
///
/// `continue`.
Continue,
/// Handles compile time checks of types.
///
/// `:A is :B`
IsCheck {
lhs: Type,
rhs: Type,
},
/// Returns a value from a function.
///
/// `ret <expression>`.
Ret {
value: Expression,
},
/// Groups together statements that are executed after another.
///
/// `{ <statement>.. }`.
Block {
statements: Vec<Statement>,
},
/// A free-standing expression. It's just a `<expression>`.
StatementExpression {
value: Expression,
},
/// Throws an error if it is ever evaluated.
///
/// `<!>`.
Unreachable,
EmptyStatement,
}
/// What makes up a program. Contains any [StatementKind].
#[derive(Debug, Clone)]
pub struct Statement {
pub span: Span,
pub kind: StatementKind,
pub comments: Vec<String>,
}
impl PartialEq for Statement {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind
}
}
pub fn path<'t>(ctx: Context<'t>) -> ParseResult<'t, Identifier> {
let span = ctx.span();
let mut ctx = ctx;
let mut result = String::new();
expect!(
ctx,
T::Slash | T::Identifier(_),
"Expected identifier or slash at start of use path"
);
if matches!(ctx.token(), T::Slash) {
result.push_str("/");
ctx = ctx.skip(1);
}
while let T::Identifier(f) = ctx.token() {
result.push_str(f);
ctx = ctx.skip(1);
if matches!(ctx.token(), T::Slash) {
result.push_str("/");
ctx = ctx.skip(1);
}
}
Ok((ctx, Identifier { span, name: result }))
}
pub fn use_path<'t>(ctx: Context<'t>) -> ParseResult<'t, (Identifier, PathBuf)> {
let (ctx, path_ident) = path(ctx)?;
let path = &path_ident.name;
let name = path
.trim_start_matches("/")
.trim_end_matches("/")
.to_string();
let file = {
let parent = if path.starts_with("/") {
ctx.root
} else {
ctx.file.parent().unwrap()
};
// Importing a folder is the same as importing exports.sy
// in the folder.
parent.join(if path == "/" {
format!("exports.sy")
} else if path_ident.name.ends_with("/") {
format!("{}/exports.sy", name)
} else {
format!("{}.sy", name)
})
};
Ok((ctx, (path_ident, file)))
}
fn statement_or_block<'t>(ctx: Context<'t>) -> ParseResult<'t, Statement> {
if matches!(
ctx.token(),
T::Do | T::If | T::Loop | T::Break | T::Continue | T::Ret
) {
Ok(statement(ctx)?)
} else {
let err_ctx = skip_until!(ctx, T::End);
let err = syntax_error!(
ctx,
"Expected \"do\" or a statement keyword, but found {:?}",
ctx.token()
);
Err((err_ctx, vec![err]))
}
}
pub fn block<'t>(ctx: Context<'t>) -> ParseResult<'t, Vec<Statement>> {
// To allow implicit block-openings, like "fn ->"
let mut ctx = ctx.skip_if(T::Do);
let mut errs = Vec::new();
let mut statements = Vec::new();
// Parse multiple inner statements until } or EOF
while !matches!(ctx.token(), T::Else | T::End | T::EOF) {
match statement(ctx) {
Ok((_ctx, stmt)) => {
ctx = _ctx; // assign to outer
statements.push(stmt);
}
Err((_ctx, mut err)) => {
ctx = _ctx.pop_skip_newlines(false); // assign to outer
ctx = skip_until!(ctx, T::Newline).skip_if(T::Newline);
errs.append(&mut err);
}
}
}
if errs.is_empty() {
// Special case for chaining if-else-statements
if !matches!(ctx.token(), T::End | T::Else) {
syntax_error!(ctx, "Expected 'end' after block");
}
let ctx = ctx.skip_if(T::End);
#[rustfmt::skip]
return Ok(( ctx, statements ));
} else {
Err((ctx, errs))
}
}
/// Parse a single [Statement].
pub fn statement<'t>(ctx: Context<'t>) -> ParseResult<'t, Statement> {
use StatementKind::*;
// Newlines have meaning in statements - thus they shouldn't be skipped.
let (ctx, skip_newlines) = ctx.push_skip_newlines(false);
// Get all comments since the last statement.
let mut comments = ctx.comments_since_last_statement();
let ctx = ctx.push_last_statement_location();
let span = ctx.span();
//NOTE(gu): Explicit lookahead.
let (ctx, kind) = match &ctx.tokens_lookahead::<3>() {
[T::End, ..] => {
raise_syntax_error!(ctx, "No valid statement starts with 'end'");
}
[T::Else, ..] => {
raise_syntax_error!(ctx, "No valid statement starts with 'else'");
}
[T::Newline, ..] => (ctx, EmptyStatement),
// Block: `{ <statements> }`
[T::Do, ..] => match (block(ctx), expression(ctx)) {
(Ok((ctx, statements)), _) => (ctx, Block { statements }),
(_, Ok((ctx, value))) => (ctx, StatementExpression { value }),
(Err((_, mut stmt_errs)), Err((_, mut expr_errs))) => {
let errs = vec![
syntax_error!(ctx, "Neither a valid block nor a valid expression - inspects the two errors below"),
stmt_errs.remove(0),
expr_errs.remove(0),
];
let ctx = skip_until!(ctx, T::End);
return Err((ctx, errs));
}
},
// `use path/to/file`
// `use path/to/file as alias`
[T::Use, ..] => {
let (ctx, (path_ident, file)) = use_path(ctx.skip(1))?;
let path = &path_ident.name;
let (ctx, alias) = match &ctx.tokens_lookahead::<2>() {
[T::As, T::Identifier(alias), ..] => (
ctx.skip(2),
NameIdentifier::Alias(Identifier {
span: ctx.skip(1).span(),
name: alias.clone(),
}),
),
[T::As, ..] => raise_syntax_error!(ctx.skip(1), "Expected alias"),
[..] => {
if path == "/" {
raise_syntax_error!(ctx, "Using root requires alias");
}
let span = if path.ends_with("/") {
ctx.prev().prev().span()
} else {
ctx.prev().span()
};
let name = PathBuf::from(
&path
.trim_start_matches("/")
.trim_end_matches("/")
.to_string(),
)
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_string();
(ctx, NameIdentifier::Implicit(Identifier { span, name }))
}
};
(ctx, Use { path: path_ident, name: alias, file })
}
// `from path/to/file use var`
[T::From, ..] => {
let (ctx, (path_ident, file)) = use_path(ctx.skip(1))?;
let mut ctx = expect!(ctx, T::Use, "Expected 'use' after path");
let mut imports = Vec::new();
let paren = matches!(ctx.token(), T::LeftParen);
let (ctx_, skip_paren) = if paren {
ctx = ctx.skip(1);
ctx.push_skip_newlines(true)
} else {
ctx.push_skip_newlines(false)
};
ctx = ctx_;
loop {
match ctx.token() {
T::RightParen | T::Newline => break,
T::Identifier(name) => {
let ident = Identifier { name: name.clone(), span: ctx.span() };
ctx = ctx.skip(1);
let alias = if matches!(ctx.token(), T::As) {
ctx = ctx.skip(1);
let _alias = match ctx.token() {
T::Identifier(name) => {
Some(Identifier { name: name.clone(), span: ctx.span() })
}
_ => raise_syntax_error!(ctx, "Expected identifier after 'as'"),
};
ctx = ctx.skip(1);
_alias
} else {
None
};
imports.push((ident, alias));
if !matches!(ctx.token(), T::Comma | T::RightParen | T::Newline) {
raise_syntax_error!(ctx, "Expected ',' after import");
}
ctx = ctx.skip_if(T::Comma);
}
_ => raise_syntax_error!(ctx, "Expected identifier"),
};
}
if imports.is_empty() {
raise_syntax_error!(ctx, "Something has to be imported in an import statement");
}
let ctx = ctx.pop_skip_newlines(skip_paren);
let ctx = if paren {
expect!(ctx, T::RightParen, "Expected ')' after import list")
} else {
ctx
};
(ctx, FromUse { path: path_ident, imports, file })
}
// `: A is : B`
[T::Colon, ..] => {
let ctx = ctx.skip(1);
let (ctx, lhs) = parse_type(ctx)?;
let ctx = expect!(
ctx,
T::Is,
"Expected 'is' after first type in 'is-check' statement"
);
let ctx = expect!(
ctx,
T::Colon,
"Expected ':' - only type constant are allowed in 'is-check' statements"
);
let (ctx, rhs) = parse_type(ctx)?;
(ctx, IsCheck { lhs, rhs })
}
[T::Break, ..] => (ctx.skip(1), Break),
[T::Continue, ..] => (ctx.skip(1), Continue),
[T::Unreachable, ..] => (ctx.skip(1), Unreachable),
// `ret <expression>`
[T::Ret, ..] => {
let ctx = ctx.skip(1);
let (ctx, value) = if matches!(ctx.token(), T::Newline) {
(
ctx,
Expression { span: ctx.span(), kind: ExpressionKind::Nil },
)
} else {
expression(ctx)?
};
(ctx, Ret { value })
}
// `loop <expression> <statement>`, e.g. `loop a < 10 { a += 1 }`
[T::Loop, ..] => {
let ctx = ctx.skip(1);
let (ctx, condition) = if matches!(ctx.token(), T::Do) {
(
ctx,
Expression { span: ctx.span(), kind: ExpressionKind::Bool(true) },
)
} else {
expression(ctx)?
};
let (ctx, body) = statement(ctx)?;
(ctx.prev(), Loop { condition, body: Box::new(body) })
}
// `case <expression> do (<branch>)* [else <statement> end] end`
[T::Case, ..] => {
let (ctx, skip_newlines) = ctx.push_skip_newlines(true);
let (ctx, to_match) = expression(ctx.skip(1))?;
let mut ctx = expect!(ctx, T::Do);
let mut branches = Vec::new();
loop {
match ctx.token() {
T::EOF | T::Else => {
break;
}
T::Identifier(pattern) if is_capitalized(pattern) => {
let pattern = Identifier { name: pattern.clone(), span: ctx.span() };
ctx = ctx.skip(1);
let (ctx_, variable) = match ctx.token() {
T::Identifier(capture) if !is_capitalized(capture) => (
ctx.skip(1),
Some(Identifier { name: capture.clone(), span: ctx.span() }),
),
T::Identifier(_) => {
raise_syntax_error!(
ctx,
"Variables have to start with a lowercase letter"
);
}
T::Do => (ctx, None),
_ => {
raise_syntax_error!(ctx, "Failed to parse case match arm");
}
};
let (ctx_, body) = statement_or_block(ctx_)?;
ctx = ctx_;
branches.push(CaseBranch { pattern, variable, body });
}
T::Identifier(_) => {
raise_syntax_error!(
ctx,
"Enum variants have to start with a captial letter"
);
}
_ => {
raise_syntax_error!(
ctx,
"Expected a branch - but a branch cannot start with {:?}",
ctx.token()
);
}
}
}
let ctx = expect!(ctx, T::Else, "Expected - else on case-statement");
let (ctx, fall_through) = statement_or_block(ctx)?;
let ctx = ctx.pop_skip_newlines(skip_newlines);
let ctx = expect!(ctx, T::End, "Expected 'end' to finish of case-statement");
(
ctx,
Case {
to_match,
branches,
fall_through: Box::new(fall_through),
},
)
}
// `if <expression> <statement> [else <statement>]`. Note that the else is optional.
[T::If, ..] => {
let (ctx, skip_newlines) = ctx.push_skip_newlines(true);
let (ctx, condition) = expression(ctx.skip(1))?;
let ctx = ctx.pop_skip_newlines(skip_newlines);
let (ctx, pass) = statement_or_block(ctx)?;
// else?
let (ctx, fail) = if matches!(ctx.token(), T::Else) {
statement_or_block(ctx.skip(1))?
} else {
// No else so we insert an empty statement instead.
(
ctx,
Statement {
span: ctx.span(),
kind: EmptyStatement,
comments: Vec::new(),
},
)
};
(
ctx.prev(),
If {
condition,
pass: Box::new(pass),
fail: Box::new(fail),
},
)
}
// Enum declaration: `Abc :: enum A, B, C end`
[T::Identifier(name), T::ColonColon, T::Enum, ..] => {
if !is_capitalized(name) {
raise_syntax_error!(
ctx,
"User defined types have to start with a capital letter"
);
}
let name = name.clone();
let ctx = ctx.skip(3);
let (mut ctx, skip_newlines) = ctx.push_skip_newlines(false);
let mut variants = HashMap::new();
// Parse variants: `A(..)`
loop {
match ctx.token().clone() {
T::Newline => {
ctx = ctx.skip(1);
}
// Done with variants.
T::End => {
break;
}
// Another one.
T::Identifier(variant) => {
if !is_capitalized(&variant) {
raise_syntax_error!(
ctx,
"Enum variants have to start with a capital letter"
);
}
let span = ctx.span();
ctx = ctx.skip(1);
if variants.contains_key(&variant) {
raise_syntax_error!(ctx, "Variant '{}' is declared twice", variant);
}
let (ctx_, ty) = if matches!(ctx.token(), T::End | T::Comma | T::Newline) {
(
ctx,
Type { span, kind: TypeKind::Resolved(RuntimeType::Void) },
)
} else {
let (ctx_, ty) = parse_type(ctx)?;
if !matches!(ctx_.token(), T::Comma | T::End | T::Newline) {
raise_syntax_error!(ctx, "Expected a deliminator ','");
};
(ctx_, ty)
};
ctx = ctx_;
variants.insert(variant, ty);
ctx = ctx.skip_if(T::Comma);
ctx = ctx.skip_if(T::Newline);
}
_ => {
raise_syntax_error!(
ctx,
"Expected variant name or 'end' in enum statement"
);
}
}
}
let ctx = ctx.pop_skip_newlines(skip_newlines);
let ctx = expect!(ctx, T::End, "Expected 'end' to close enum");
(ctx, Enum { name, variants })
}
// Blob declaration: `A :: blob { <fields> }
[T::Identifier(name), T::ColonColon, T::Blob, ..] => {
if !is_capitalized(name) {
raise_syntax_error!(
ctx,
"User defined types have to start with a capital letter"
);
}
let name = name.clone();
let ctx = expect!(ctx.skip(3), T::LeftBrace, "Expected '{{' to open blob");
let (mut ctx, skip_newlines) = ctx.push_skip_newlines(true);
let mut fields = HashMap::new();
// Parse fields: `a: int`
loop {
match ctx.token().clone() {
T::Newline => {
ctx = ctx.skip(1);
}
// Done with fields.
T::RightBrace => {
break;
}
// Another one.
T::Identifier(field) => {
if field == "self" {
raise_syntax_error!(ctx, "\"self\" is a reserved identifier");
}
if fields.contains_key(&field) {
raise_syntax_error!(ctx, "Field '{}' is declared twice", field);
}
ctx = expect!(ctx.skip(1), T::Colon, "Expected ':' after field name");
let (_ctx, ty) = parse_type(ctx)?;
ctx = _ctx; // assign to outer
fields.insert(field, ty);
if !matches!(ctx.token(), T::Comma | T::RightBrace) {
raise_syntax_error!(ctx, "Expected a field deliminator ','");
}
ctx = ctx.skip_if(T::Comma);
}
_ => {
raise_syntax_error!(ctx, "Expected field name or '}}' in blob statement");
}
}
}
let ctx = ctx.pop_skip_newlines(skip_newlines);
let ctx = expect!(ctx, T::RightBrace, "Expected '}}' to close blob fields");
(ctx, Blob { name, fields })
}
// Implied type declaration, e.g. `a :: 1` or `a := 1`.
[T::Identifier(name), T::ColonColon | T::ColonEqual, ..] => {
if is_capitalized(name) {
// raise_syntax_error!(ctx, "Variables have to start with a lowercase letter");
}
if name == "self" {
raise_syntax_error!(ctx, "\"self\" is a reserved identifier");
}
let ident = Identifier { name: name.clone(), span: ctx.span() };
let ctx = ctx.skip(1);
let kind = match ctx.token() {
T::ColonColon => VarKind::Const,
T::ColonEqual => VarKind::Mutable,
_ => unreachable!(),
};
let ctx = ctx.skip(1);
if matches!(ctx.token(), T::External) {
raise_syntax_error!(ctx, "External definitons have to have a type");
} else {
let (ctx, value) = expression(ctx)?;
(
ctx,
Definition {
ident,
kind,
ty: Type { span: ctx.span(), kind: TypeKind::Implied },
value,
},
)
}
}
// Variable declaration with specified type, e.g. `c : int = 3` or `b : int | bool : false`.
[T::Identifier(name), T::Colon, ..] => {
if is_capitalized(name) {
// raise_syntax_error!(ctx, "Variables have to start with a lowercase letter");
}
if name == "self" {
raise_syntax_error!(ctx, "\"self\" is a reserved identifier");
}
let ident = Identifier { name: name.clone(), span: ctx.span() };
// Skip identifier and ':'.
let ctx = ctx.skip(2);
let (ctx, kind, ty) = {
let (ctx, ty) = parse_type(ctx)?;
let kind = match ctx.token() {
T::Colon => VarKind::Const,
T::Equal => VarKind::Mutable,
t => {
raise_syntax_error!(
ctx,
"Expected ':' or '=' for definition, but got '{:?}'",
t
);
}
};
// Skip `:` or `=`.
(ctx.skip(1), kind, ty)
};
if matches!(ctx.token(), T::External) {
(ctx.skip(1), ExternalDefinition { ident, kind, ty })
} else {
// The value to define the variable to.
let (ctx, value) = expression(ctx)?;
(ctx, Definition { ident, kind, ty, value })
}
}
// Expression or assignment. We try assignment first.
_ => {
/// `a = 5`.
fn assignment<'t>(ctx: Context<'t>) -> ParseResult<'t, StatementKind> {
// The assignable to assign to.
let (ctx, target) = assignable(ctx)?;
let kind = match ctx.token() {
T::PlusEqual => Op::Add,
T::MinusEqual => Op::Sub,
T::StarEqual => Op::Mul,
T::SlashEqual => Op::Div,
T::Equal => Op::Nop,
t => {
raise_syntax_error!(ctx, "No assignment operation matches '{:?}'", t);
}
};
// The expression to assign the assignable to.
let (ctx, value) = expression(ctx.skip(1))?;
Ok((ctx, Assignment { kind, target, value }))
}
match (assignment(ctx), expression(ctx)) {
(Ok((ctx, kind)), _) => (ctx, kind),
(_, Ok((ctx, value))) => (ctx, StatementExpression { value }),
(Err((_, mut ass_errs)), Err((_, mut expr_errs))) => {
ass_errs.append(&mut expr_errs);
ass_errs.push(syntax_error!(ctx, "Neither an assignment or an expression"));
return Err((ctx, ass_errs));
}
}
}
};
// Newline, RightBrace and Else can end a statment.
// If a statement does not end, we only report it as a missing newline.
let ctx = if matches!(ctx.token(), T::End | T::Else) {
ctx
} else {
expect!(ctx, T::Newline, "Expected newline to end statement")
};
let ctx = ctx.pop_skip_newlines(skip_newlines);
comments.append(&mut ctx.comments_since_last_statement());
let ctx = ctx.push_last_statement_location();
Ok((ctx, Statement { span, kind, comments }))
}
/// Parse an outer statement.
///
/// Currently all statements are valid outer statements.
pub fn outer_statement<'t>(ctx: Context<'t>) -> ParseResult<Statement> {
let (ctx, stmt) = statement(ctx)?;
use StatementKind::*;
match stmt.kind {
#[rustfmt::skip]
Blob { .. }
| Enum { .. }
| Definition { .. }
| ExternalDefinition { .. }
| Use { .. }
| FromUse { .. }
| IsCheck { .. }
| EmptyStatement
=> Ok((ctx, stmt)),
_ => raise_syntax_error!(ctx, "Not a valid outer statement"),
}
}
#[cfg(test)]
mod test {
use super::StatementKind::*;
use super::*;
// NOTE(ed): Expressions are valid statements! :D
test!(statement, statement_expression: "1 + 1\n" => _);
test!(statement, statement_break: "break\n" => _);
test!(statement, statement_continue: "continue\n" => _);
test!(statement, statement_mut_declaration: "a := 1 + 1\n" => _);
test!(statement, statement_const_declaration: "a :: 1 + 1\n" => _);
test!(statement, statement_mut_type_declaration: "a :int= 1 + 1\n" => _);
test!(statement, statement_const_type_declaration: "a :int: 1 + 1\n" => _);
test!(statement, statement_if: "if 1 do a end\n" => _);
test!(statement, statement_if_else: "if 1 do a else do b end\n" => _);
test!(statement, statement_loop: "loop 1 { a }\n" => _);
test!(statement, statement_loop_no_condition: "loop do a end\n" => _);
test!(statement, statement_ret: "ret 1 + 1\n" => _);
test!(statement, statement_ret_newline: "ret \n" => _);
test!(statement, statement_unreach: "<!>\n" => _);
test!(statement, statement_blob_empty: "A :: blob {}\n" => _);
test!(statement, statement_blob_comma: "A :: blob { a: int, b: int }\n" => _);
test!(statement, statement_blob_comma_newline: "A :: blob { a: int,\n b: int }\n" => _);
test!(statement, statement_assign: "a = 1\n" => _);
test!(statement, statement_assign_index: "a.b = 1 + 2\n" => _);
test!(statement, statement_add_assign: "a += 2\n" => _);
test!(statement, statement_sub_assign: "a -= 2\n" => _);
test!(statement, statement_mul_assign: "a *= 2\n" => _);
test!(statement, statement_div_assign: "a /= 2\n" => _);
test!(statement, statement_assign_call: "a().b() += 2\n" => _);
test!(statement, statement_assign_call_index: "a.c().c.b /= 4\n" => _);
test!(statement, statement_idek: "a'.c'.c.b()().c = 0\n" => _);
test!(statement, statement_is_check: ":A is :B\n" => IsCheck { .. });
test!(statement, statement_is_check_nested: ":a.c.D is :b.d.D\n" => IsCheck { .. });
test!(statement, statement_if_newline: "if 1 \n\n+\n 1\n\n < 2 do end\n" => _);
test!(statement, statement_skip_newline: "(1 \n\n+\n 1\n\n)\n" => _);
test!(statement, statement_skip_newline_list: "[\n\n 1 \n\n,\n 1\n\n,]\n" => _);
test!(statement, statement_skip_newline_set: "{\n\n 1 \n\n,\n 1\n\n,}\n" => _);
test!(statement, statement_skip_newline_dict: "{\n\n 1: \n3\n,\n 1\n\n:1,}\n" => _);
test!(outer_statement, outer_statement_blob: "B :: blob {}\n" => _);
test!(outer_statement, outer_statement_blob_no_last_comma: "B :: blob { \na: A\n }\n" => _);
test!(outer_statement, outer_statement_blob_yes_last_comma: "B :: blob { \na: A,\n }\n" => _);
test!(outer_statement, outer_statement_declaration: "B :: fn -> do end\n" => _);
test!(outer_statement, outer_statement_use: "use abc\n" => _);
test!(outer_statement, outer_statement_use_rename: "use a as b\n" => _);
test!(outer_statement, outer_statement_use_subdir: "use a/b/c/d/e\n" => _);
test!(outer_statement, outer_statement_use_subdir_rename: "use a/b as c\n" => _);
test!(outer_statement, outer_statement_from: "from a/b use c\n" => _);
test!(outer_statement, outer_statement_from_many: "from b use c,d,e,f,g,h\n" => _);
test!(outer_statement, outer_statement_from_paren: "from / use (c\n,d\n)\n" => _);
test!(outer_statement, outer_statement_from_paren_one: "from / use (c)\n" => _);
test!(outer_statement, outer_statement_empty: "\n" => _);
test!(outer_statement, outer_statement_enum: "A :: enum A, B end\n" => _);
test!(outer_statement, outer_statement_enum_trailing_comma: "A :: enum A, B, end\n" => _);
test!(outer_statement, outer_statement_enum_empty: "A :: enum end\n" => _);
test!(outer_statement, outer_statement_enum_tuples: "A :: enum A(int, int), B(int,), C(), end\n" => _);
test!(outer_statement, outer_statement_enum_newlines: "A :: enum A(int, int)\n\n B(int,)\n C()\n end\n" => _);
fail!(statement, statement_blob_newline: "A :: blob { a: int\n b: int }\n" => _);
fail!(statement, statement_blob_self: "A :: blob { self: int }" => _);
fail!(statement, statement_assign_self_const: "self :: 1" => _);
fail!(statement, statement_assign_self_var: "self := 1" => _);
fail!(statement, statement_assign_self_type: "self: int = 1" => _);
fail!(statement, outer_statement_from_invalid: "from b use a!" => _);
fail!(statement, outer_statement_from_alias_invalid: "from b use a as !" => _);
}
impl Display for NameIdentifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let ident = match &self {
NameIdentifier::Implicit(ident) => {
write!(f, "Implicit(")?;
ident
}
NameIdentifier::Alias(ident) => {
write!(f, "Alias(")?;
ident
}
};
write!(f, "{})", ident.name)
}
}
| 36.536559 | 119 | 0.457871 |
01b5379ab86615ac53dd3b7dc86397404f306cb0
| 4,650 |
/// # ToneParams
///
/// Config parameters to be passed with `tone_sub()` function.
struct ToneParams {
/// First frequency.
freq1: u32,
/// Second frequency.
freq2: u32,
/// Attack (aggressive start).
attack: u32,
/// Decay (smooth fading).
decay: u32,
/// Sustain time.
sustain: u32,
/// Release time.
release: u32,
/// Volume.
volume: u32,
/// Audio channel. Each channel, except `0` and `1`, are different.
channel: u32,
/// Audio mode. Only works for channels `0` and `1`.
mode: u32,
}
impl Default for ToneParams {
fn default() -> Self {
return ToneParams {
freq1 : 500,
freq2 : 0,
attack : 0,
decay : 0,
sustain: 30,
release: 0,
volume : 100,
channel: 0,
mode : 0,
};
}
}
/// Extended `tone()` function.
///
/// # Arguments
///
/// * `params` - Config parameters.
fn tone_sub(params: ToneParams) {
tone(params.freq1 | (params.freq2 << 16), (params.attack << 24) | (params.decay << 16) | params.sustain | (params.release << 8), params.volume, params.channel | (params.mode << 2));
}
/// Musical note frequencies used by tracks.
const TRACK_NOTES: [u16; 37] = [
130, 140, 150, 160, 170, 180, 190, 200, 210,
220, 230, 250, 260, 280, 290, 310, 330, 350,
370, 390, 410, 440, 460, 490, 520, 550, 600,
620, 660, 700, 750, 780, 840, 880, 940, 980,
1000
];
/// Instruments available for use.
const TRACK_INSTRUMENTS: [(u32, u32); 5] = [
(2, 0), // Triangle
(0, 2), // Square
(0, 3), // Pulse wide
(0, 1), // Pulse narrow
(0, 0) // Sawtooth
];
/// Reserved for empty notes.
const TRACK_OPCODE_EMPTY: u8 = 0xFF;
/// This will cut-off the track, reverting it to the beginning.
const TRACK_OPCODE_END: u8 = 0xFE;
/// # Track
///
/// A *sound track* is basically one fragment of a music.
struct Track {
/// Next tone index.
next: usize,
/// Wait time until the next tone.
wait: u16,
/// Ticks per beat.
ticks: u8,
/// Instrument used by this track (see `TRACK_INSTRUMENTS`).
instrument: u8,
/// Variable Flags reserved for opcodes.
flags: (u8,u8),
/// Soundtrack tones.
tones: [(u8,u8,u8); 32],
}
impl Default for Track {
fn default() -> Self {
return Track {
next : 0,
wait : 0,
ticks : 1,
instrument: 0,
flags : (0,0),
tones : [(0, 255, 0); 32],
};
}
}
impl Track {
/// Instance a new track.
///
/// # Arguments
///
/// * `tones` - Soundtrack tones.
pub fn new(tones: [(u8,u8,u8); 32]) -> Self {
return Track {
next : 0,
wait : 0,
ticks : 1,
instrument: 0,
flags : (0,0),
tones : tones,
};
}
/// Resets the track back to beginning.
pub fn reset(&mut self) {
self.next = 0;
self.wait = 0;
}
/// Event responsible for controlling music execution.
pub fn step(&mut self) {
// When empty, proceed to next tone index...
if self.wait == 0 {
// Musical tone to be played.
let tone : (u8,u8,u8) = self.tones[self.next];
let note : u8 = tone.0;
let wait : u8 = tone.1;
let flags: u8 = tone.2;
// Instrument in use.
let instrument: usize = (self.instrument as usize) % TRACK_INSTRUMENTS.len();
// Play tone...
if note < TRACK_NOTES.len() as u8 {
tone_sub(ToneParams
{
freq1 : TRACK_NOTES[note as usize] as u32,
freq2 : 0,
attack : 0,
decay : 0,
sustain: 0,
release: (wait * self.ticks) as u32,
volume : 100,
channel: TRACK_INSTRUMENTS[instrument].0,
mode : TRACK_INSTRUMENTS[instrument].1,
}
);
}
// Proceed to next note...
self.next = (self.next + 1) % self.tones.len();
self.wait = wait as u16;
// Redirection...
if note == TRACK_OPCODE_END {
self.next = 0;
}
}
// Countdown wait time...
else {
self.wait -= 1;
}
}
}
| 26.878613 | 185 | 0.472043 |
22c8d541fa1cf222d54e19996cf9536d83029a6a
| 1,947 |
use super::operate;
use crate::prelude::*;
use inflector::cases::kebabcase::to_kebab_case;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{Signature, SyntaxShape, Value};
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str kebab-case"
}
fn signature(&self) -> Signature {
Signature::build("str kebab-case").rest(
SyntaxShape::ColumnPath,
"optionally convert text to kebab-case by column paths",
)
}
fn usage(&self) -> &str {
"converts a string to kebab-case"
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
operate(args, &to_kebab_case)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "convert a string to kebab-case",
example: "echo 'NuShell' | str kebab-case",
result: Some(vec![Value::from("nu-shell")]),
}]
}
}
#[cfg(test)]
mod tests {
use super::ShellError;
use super::{to_kebab_case, SubCommand};
use crate::commands::strings::str_::case::action;
use nu_source::Tag;
use nu_test_support::value::string;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn kebab_case_from_camel() {
let word = string("thisIsTheFirstCase");
let expected = string("this-is-the-first-case");
let actual = action(&word, Tag::unknown(), &to_kebab_case).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn kebab_case_from_screaming_snake() {
let word = string("THIS_IS_THE_SECOND_CASE");
let expected = string("this-is-the-second-case");
let actual = action(&word, Tag::unknown(), &to_kebab_case).unwrap();
assert_eq!(actual, expected);
}
}
| 27.422535 | 76 | 0.615306 |
1ea9bf4b333dfd38f715c40bccdb0b147ed37949
| 6,041 |
use crate::{light_block::LightBlock, Generator};
use tendermint::block::{self, Height};
use tendermint::chain::Info;
use std::convert::{TryFrom, TryInto};
#[derive(Clone, Debug)]
pub struct LightChain {
pub info: Info,
pub light_blocks: Vec<LightBlock>,
}
impl LightChain {
pub fn new(info: Info, light_blocks: Vec<LightBlock>) -> Self {
LightChain { info, light_blocks }
}
// TODO: make this fn more usable
// TODO: like how does someone generate a chain with different validators at each height
pub fn default_with_length(num: u64) -> Self {
let mut last_block = LightBlock::new_default(1);
let mut light_blocks: Vec<LightBlock> = vec![last_block.clone()];
for _i in 2..=num {
// add "next" light block to the vector
last_block = last_block.next();
light_blocks.push(last_block.clone());
}
let id = last_block.chain_id().parse().unwrap();
let height = last_block.height().try_into().unwrap();
let last_block_hash = last_block.header.map(|h| h.generate().unwrap().hash());
let last_block_id = last_block_hash.map(|hash| block::Id {
hash,
part_set_header: Default::default(),
});
let info = Info {
id,
height,
last_block_id,
// TODO: Not sure yet what this time means
time: None,
};
Self::new(info, light_blocks)
}
/// expects at least one LightBlock in the Chain
pub fn advance_chain(&mut self) -> &LightBlock {
let last_light_block = self
.light_blocks
.last()
.expect("Cannot find testgen light block");
let new_light_block = last_light_block.next();
self.info.height = Height::try_from(new_light_block.height())
.expect("failed to convert from u64 to Height");
let last_block_id_hash = new_light_block
.header
.as_ref()
.expect("missing header in new light block")
.generate()
.expect("failed to generate header")
.hash();
self.info.last_block_id = Some(block::Id {
hash: last_block_id_hash,
part_set_header: Default::default(),
});
self.light_blocks.push(new_light_block);
self.light_blocks.last().unwrap() // safe because of push above
}
/// fetches a block from LightChain at a certain height
/// it returns None if a block does not exist for the target_height
pub fn block(&self, target_height: u64) -> Option<&LightBlock> {
self.light_blocks
.iter()
.find(|lb| lb.height() == target_height)
}
/// fetches a mutable block from LightChain at a certain height
/// it returns None if a block does not exist for the target_height
pub fn block_mut(&mut self, target_height: u64) -> Option<&mut LightBlock> {
self.light_blocks
.iter_mut()
.find(|lb| lb.height() == target_height)
}
/// fetches the latest block from LightChain
pub fn latest_block(&self) -> &LightBlock {
self.light_blocks
.last()
.expect("cannot find last light block")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_advance_chain() {
let mut light_chain = LightChain::default_with_length(1);
let advance_1 = light_chain.advance_chain();
assert_eq!(2, advance_1.height());
assert_eq!(2, light_chain.info.height.value());
let advance_2 = light_chain.advance_chain();
assert_eq!(3, advance_2.height());
assert_eq!(3, light_chain.info.height.value());
}
#[test]
fn test_block() {
let mut light_chain = LightChain::default_with_length(1);
let first_block = light_chain.block(1);
assert_eq!(1, first_block.unwrap().height());
light_chain.advance_chain();
let second_block = light_chain.block(2);
assert_eq!(2, second_block.unwrap().height());
}
#[test]
fn test_latest_block() {
let mut light_chain = LightChain::default_with_length(1);
let first_block = light_chain.latest_block();
assert_eq!(1, first_block.height());
light_chain.advance_chain();
let second_block = light_chain.latest_block();
assert_eq!(2, second_block.height());
}
#[test]
fn test_light_chain_with_length() {
const CHAIN_HEIGHT: u64 = 10;
let chain = LightChain::default_with_length(CHAIN_HEIGHT);
let blocks = chain
.light_blocks
.into_iter()
.flat_map(|lb| lb.generate())
.collect::<Vec<_>>();
// we have as many blocks as the height of the chain
assert_eq!(blocks.len(), chain.info.height.value() as usize);
assert_eq!(blocks.len(), CHAIN_HEIGHT as usize);
let first_block = blocks.first().unwrap();
let last_block = blocks.last().unwrap();
// the first block is at height 1
assert_eq!(first_block.signed_header.header.height.value(), 1);
// the first block does not have a last_block_id
assert!(first_block.signed_header.header.last_block_id.is_none());
// the last block is at the chain height
assert_eq!(last_block.signed_header.header.height, chain.info.height);
for i in 1..blocks.len() {
let prv = &blocks[i - 1];
let cur = &blocks[i];
// the height of the current block is the successor of the previous block
assert_eq!(
cur.signed_header.header.height.value(),
prv.signed_header.header.height.value() + 1
);
// the last_block_id hash is equal to the previous block's hash
assert_eq!(
cur.signed_header.header.last_block_id.map(|lbi| lbi.hash),
Some(prv.signed_header.header.hash())
);
}
}
}
| 32.132979 | 92 | 0.597087 |
bfe8b8dc9596afcb98b32137df7c319465ce9c73
| 9,410 |
#[macro_use]
extern crate log;
mod cli;
use anyhow::anyhow;
use lpc55::bootloader::Bootloader;
fn main() {
pretty_env_logger::init_custom_env("SOLO2_LOG");
info!("solo2 CLI startup");
let args = cli::cli().get_matches();
if let Err(err) = try_main(args) {
eprintln!("Error: {}", err);
std::process::exit(1);
}
}
fn try_main(args: clap::ArgMatches<'_>) -> anyhow::Result<()> {
let uuid = args
.value_of("uuid")
// if uuid is Some, parse and fail on invalidity (no silent failure)
.map(|uuid| solo2::Uuid::from_hex(uuid))
.transpose()?;
if let Some(args) = args.subcommand_matches("app") {
use solo2::apps::App;
if let Some(args) = args.subcommand_matches("admin") {
info!("interacting with admin app");
use solo2::apps::admin::App as AdminApp;
if args.subcommand_matches("aid").is_some() {
println!("{}", hex::encode(AdminApp::aid()).to_uppercase());
return Ok(());
}
let mut app = AdminApp::new(uuid)?;
let answer_to_select = app.select()?;
info!("answer to select: {}", &hex::encode(answer_to_select));
if args.subcommand_matches("boot-to-bootrom").is_some() {
app.boot_to_bootrom()?;
}
if args.subcommand_matches("reboot").is_some() {
info!("attempting reboot");
app.reboot()?;
}
if args.subcommand_matches("uuid").is_some() {
let uuid = app.uuid()?;
println!("{}", hex::encode_upper(uuid.to_be_bytes()));
}
if args.subcommand_matches("version").is_some() {
let version = app.version()?;
println!("{}", version);
}
}
if let Some(args) = args.subcommand_matches("ndef") {
info!("interacting with NDEF app");
use solo2::apps::ndef::App as NdefApp;
if args.subcommand_matches("aid").is_some() {
println!("{}", hex::encode(NdefApp::aid()).to_uppercase());
return Ok(());
}
let mut app = NdefApp::new(uuid)?;
app.select()?;
if args.subcommand_matches("capabilities").is_some() {
let capabilities = app.capabilities()?;
println!("{}", hex::encode(capabilities));
}
if args.subcommand_matches("data").is_some() {
let data = app.data()?;
println!("{}", hex::encode(data));
}
}
// if let Some(args) = args.subcommand_matches("oath") {
// info!("interacting with OATH app");
// use solo2::apps::oath::{App, Command};
// if args.subcommand_matches("aid").is_some() {
// App::print_aid();
// return Ok(());
// }
// let mut app = App::new(uuid)?;
// app.select()?;
// let command: Command = Command::try_from(args)?;
// match command {
// Command::Register(register) => {
// let credential_id = app.register(register)?;
// println!("{}", credential_id);
// }
// Command::Authenticate(authenticate) => {
// let code = app.authenticate(authenticate)?;
// println!("{}", code);
// }
// Command::Delete(label) => {
// app.delete(label)?;
// }
// Command::List => app.list()?,
// Command::Reset => app.reset()?,
// }
// }
if let Some(args) = args.subcommand_matches("piv") {
info!("interacting with PIV app");
use solo2::apps::piv::App;
if args.subcommand_matches("aid").is_some() {
println!("{}", hex::encode(App::aid()).to_uppercase());
return Ok(());
}
let mut app = App::new(uuid)?;
app.select()?;
}
if let Some(args) = args.subcommand_matches("provisioner") {
info!("interacting with Provisioner app");
use solo2::apps::provisioner::App;
if args.subcommand_matches("aid").is_some() {
println!("{}", hex::encode(App::aid()).to_uppercase());
return Ok(());
}
let mut app = App::new(uuid)?;
app.select()?;
if args.subcommand_matches("generate-ed255-key").is_some() {
let public_key = app.generate_trussed_ed255_attestation_key()?;
println!("{}", hex::encode(public_key));
}
if args.subcommand_matches("generate-p256-key").is_some() {
let public_key = app.generate_trussed_p256_attestation_key()?;
println!("{}", hex::encode(public_key));
}
if args.subcommand_matches("generate-x255-key").is_some() {
let public_key = app.generate_trussed_x255_attestation_key()?;
println!("{}", hex::encode(public_key));
}
if args.subcommand_matches("reformat-filesystem").is_some() {
app.reformat_filesystem()?;
}
if let Some(args) = args.subcommand_matches("store-ed255-cert") {
let cert_file = args.value_of("DER").unwrap();
let certificate = std::fs::read(cert_file)?;
app.store_trussed_ed255_attestation_certificate(&certificate)?;
}
if let Some(args) = args.subcommand_matches("store-p256-cert") {
let cert_file = args.value_of("DER").unwrap();
let certificate = std::fs::read(cert_file)?;
app.store_trussed_p256_attestation_certificate(&certificate)?;
}
if let Some(args) = args.subcommand_matches("store-x255-cert") {
let cert_file = args.value_of("DER").unwrap();
let certificate = std::fs::read(cert_file)?;
app.store_trussed_x255_attestation_certificate(&certificate)?;
}
if let Some(args) = args.subcommand_matches("store-t1-pubkey") {
let pubkey_file = args.value_of("BYTES").unwrap();
let public_key: [u8; 32] = std::fs::read(pubkey_file)?.as_slice().try_into()?;
app.store_trussed_t1_intermediate_public_key(public_key)?;
}
if args.subcommand_matches("boot-to-bootrom").is_some() {
app.boot_to_bootrom()?;
}
if args.subcommand_matches("uuid").is_some() {
let uuid = app.uuid()?;
println!("{}", hex::encode_upper(uuid.to_be_bytes()));
}
if let Some(args) = args.subcommand_matches("write-file") {
let file = args.value_of("DATA").unwrap();
let data = std::fs::read(file)?;
let path = args.value_of("PATH").unwrap();
app.write_file(&data, path)?;
}
}
if let Some(args) = args.subcommand_matches("tester") {
info!("interacting with Tester app");
use solo2::apps::tester::App;
if args.subcommand_matches("aid").is_some() {
println!("{}", hex::encode(App::aid()).to_uppercase());
return Ok(());
}
let mut app = App::new(uuid)?;
app.select()?;
}
}
#[cfg(not(feature = "dev-pki"))]
if args.subcommand_matches("dev-pki").is_some() {
return Err(anyhow!(
"Compile with `--features dev-pki` for dev PKI support!"
));
}
#[cfg(feature = "dev-pki")]
if let Some(args) = args.subcommand_matches("dev-pki") {
if let Some(args) = args.subcommand_matches("fido") {
let (aaguid, key_trussed, key_pem, cert) = solo2::dev_pki::generate_selfsigned_fido();
info!("\n{}", key_pem);
info!("\n{}", cert.serialize_pem()?);
std::fs::write(args.value_of("KEY").unwrap(), &key_trussed)?;
std::fs::write(args.value_of("CERT").unwrap(), &cert.serialize_der()?)?;
println!("{}", hex::encode_upper(aaguid));
}
}
if let Some(args) = args.subcommand_matches("bootloader") {
if args.subcommand_matches("reboot").is_some() {
let bootloader = solo2::device::find_bootloader(uuid)?;
bootloader.reboot();
}
if args.subcommand_matches("ls").is_some() {
let bootloaders = Bootloader::list();
for bootloader in bootloaders {
println!("{:?}", &bootloader);
}
}
}
if let Some(_args) = args.subcommand_matches("list") {
let devices = solo2::Device::list();
for device in devices {
println!("{}", &device);
}
}
if let Some(args) = args.subcommand_matches("update") {
let skip_major_check = args.is_present("yes");
let update_all = args.is_present("all");
let sb2file = args.value_of("FIRMWARE").map(|s| s.to_string());
solo2::update::run_update_procedure(sb2file, uuid, skip_major_check, update_all)?;
}
Ok(())
}
| 37.943548 | 98 | 0.511902 |
2113daf2d8de61f06c6baa4ef459799c6a1b9540
| 13,929 |
use std::ffi::{CStr, CString, OsStr};
use std::io::{Error, ErrorKind, Result};
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::ptr;
use std::str;
use libparted_sys::{
ped_constraint_any, ped_device_begin_external_access, ped_device_check, ped_device_close,
ped_device_end_external_access, ped_device_get, ped_device_get_constraint,
ped_device_get_minimal_aligned_constraint, ped_device_get_minimum_alignment,
ped_device_get_next, ped_device_get_optimal_aligned_constraint,
ped_device_get_optimum_alignment, ped_device_is_busy, ped_device_open, ped_device_probe_all,
ped_device_sync, ped_device_sync_fast, ped_device_write, ped_disk_clobber, ped_disk_probe,
PedDevice,
};
pub use libparted_sys::PedDeviceType as DeviceType;
pub use libparted_sys::_PedCHSGeometry as CHSGeometry;
use super::{cvt, Alignment, Constraint, ConstraintSource, DiskType, Geometry};
pub struct Device<'a> {
pub(crate) device: *mut PedDevice,
pub(crate) phantom: PhantomData<&'a PedDevice>,
pub(crate) is_droppable: bool,
}
pub struct DeviceIter<'a>(*mut PedDevice, PhantomData<&'a PedDevice>);
pub struct DeviceExternalAccess<'a, 'b: 'a>(&'a mut Device<'b>);
macro_rules! get_bool {
($field:tt) => {
pub fn $field(&self) -> bool {
unsafe { *self.device }.$field != 0
}
};
}
macro_rules! get_geometry {
($kind:tt) => {
pub fn $kind(&self) -> CHSGeometry {
unsafe { (*self.device).$kind }
}
};
}
impl<'a> Device<'a> {
fn new_(device: *mut PedDevice) -> Device<'a> {
Device {
device,
phantom: PhantomData,
is_droppable: true,
}
}
/// Returns the first bad sector if a bad sector was found.
///
/// # Binding Note
///
/// Not 100% sure if this is what this method does, as libparted's source
/// code did not document the behavior of the function. Am basing this
/// off the `check()` method that was documented for **Geometry**.
pub fn check(&self, start: i64, count: i64) -> Option<u64> {
let mut buffer: Vec<u8> = Vec::with_capacity(8192);
let buffer_ptr = buffer.as_mut_slice().as_mut_ptr() as *mut c_void;
match unsafe { ped_device_check(self.device, buffer_ptr, start, count) } {
-1 => None,
bad_sector => Some(bad_sector as u64),
}
}
/// Return the type of partition table detected on `dev`
pub fn probe(&self) -> Option<DiskType> {
let disk_type = unsafe { ped_disk_probe(self.device) };
if disk_type.is_null() {
None
} else {
Some(DiskType {
type_: disk_type,
phantom: PhantomData,
})
}
}
/// Attempts to detect all devices, constructing an **Iterator** which will
/// contain a list of all of the devices. If you want to use a device that isn't
/// on the list, use the `new()` method, or an OS-specific constructor such as
/// `new_from_store()`.
pub fn devices<'b>(probe: bool) -> DeviceIter<'b> {
if probe {
unsafe { ped_device_probe_all() }
}
DeviceIter(ptr::null_mut(), PhantomData)
}
/// Obtains a handle to the device, but does not open it.
pub fn get<P: AsRef<Path>>(path: P) -> Result<Device<'a>> {
// Convert the supplied path into a C-compatible string.
let os_str = path.as_ref().as_os_str();
let cstr = CString::new(os_str.as_bytes())
.map_err(|err| Error::new(ErrorKind::InvalidData, format!("Inavlid data: {}", err)))?;
// Then attempt to get the device.
let mut device = Device::new_(cvt(unsafe { ped_device_get(cstr.as_ptr()) })?);
device.is_droppable = false;
Ok(device)
}
/// Attempts to open the device.
pub fn open(&mut self) -> Result<()> {
cvt(unsafe { ped_device_open(self.device) })?;
self.is_droppable = true;
Ok(())
}
/// Attempts to get the device of the given `path`, then attempts to open that device.
pub fn new<P: AsRef<Path>>(path: P) -> Result<Device<'a>> {
let mut device = Device::get(path)?;
device.open()?;
Ok(device)
}
#[allow(clippy::missing_safety_doc)]
pub unsafe fn from_ped_device(device: *mut PedDevice) -> Device<'a> {
Device::new_(device)
}
#[allow(clippy::missing_safety_doc)]
pub unsafe fn ped_device(&self) -> *mut PedDevice {
self.device
}
/// Begins external access mode.
///
/// External access mode allows you to safely do I/O on the device. If a device is open,
/// then you should not do any I/O on that device, such as by calling an external program
/// like e2fsck, unless you put it in external access mode. You should not use any libparted
/// commands that do I/O to a device while a device is in external access mode.
///
/// # Note:
///
/// You should not close a device while it is in external access mode.
pub fn external_access<'b>(&'b mut self) -> Result<DeviceExternalAccess<'a, 'b>> {
cvt(unsafe { ped_device_begin_external_access(self.device) })?;
Ok(DeviceExternalAccess(self))
}
/// Flushes all write-behind caches that might be holding up writes.
///
/// It is slow because it guarantees cache coherency among all relevant caches.
pub fn sync(&mut self) -> Result<()> {
cvt(unsafe { ped_device_sync(self.device) })?;
Ok(())
}
/// Flushes all write-behind caches that might be holding writes.
///
/// It does not ensure cache coherency with other caches.
pub fn sync_fast(&mut self) -> Result<()> {
cvt(unsafe { ped_device_sync_fast(self.device) })?;
Ok(())
}
/// Indicates whether the device is busy.
pub fn is_busy(&self) -> bool {
unsafe { ped_device_is_busy(self.device) != 0 }
}
/// Attempts to write the data within the buffer to the device, starting
/// at the **start_sector**, and spanning across **sectors**.
pub fn write_to_sectors(
&mut self,
buffer: &[u8],
start_sector: i64,
sectors: i64,
) -> Result<()> {
let total_size = self.sector_size() as usize * sectors as usize;
// Ensure that the data will fit within the region of sectors.
debug_assert!(buffer.len() <= total_size);
// Write as much data as needed to fill the entire sector, writing
// zeros in the unused space, and obtaining a pointer to the buffer.
let mut sector_buffer: Vec<u8> = Vec::with_capacity(total_size);
sector_buffer.extend_from_slice(buffer);
sector_buffer.extend((buffer.len()..total_size).map(|_| b'0'));
let sector_ptr = sector_buffer.as_slice().as_ptr() as *const c_void;
// Then attempt to write the data to the device.
cvt(unsafe { ped_device_write(self.device, sector_ptr, start_sector, sectors) })?;
Ok(())
}
/// Get a constraint that represents hardware requirements on geometry.
///
/// This function will return a constraint representing the limits imposed by the size
/// of the disk. It will not provide any alignment constraints.
///
/// Alignment constraint may be desirable when using media that has a physical
/// sector size that is a multiple of the logical sector size, as in this case proper
/// partition alignment can benefit disk performance significantly.
///
/// # Note:
///
/// When you want a constraint with alignment info, use the following methods:
/// - `Device::get_minimal_aligned_constraint()`
/// - `Device::get_optimal_aligned_constraint()`
pub fn get_constraint<'b>(&self) -> Result<Constraint<'b>> {
Ok(Constraint {
constraint: cvt(unsafe { ped_device_get_constraint(self.device) })?,
source: ConstraintSource::New,
phantom: PhantomData,
})
}
/// Return a constraint that any region on the given device will satisfy.
pub fn constraint_any<'b>(&self) -> Option<Constraint<'b>> {
let constraint = unsafe { ped_constraint_any(self.device) };
if constraint.is_null() {
None
} else {
Some(Constraint {
constraint,
source: ConstraintSource::New,
phantom: PhantomData,
})
}
}
pub fn constraint_from_start_end<'b>(
&self,
range_start: &Geometry,
range_end: &Geometry,
) -> Result<Constraint<'b>> {
let alignment_any = Alignment::new(0, 1).unwrap();
Constraint::new(
&alignment_any,
&alignment_any,
range_start,
range_end,
1,
self.length() as i64,
)
}
/// Get a constraint that represents hardware requirements on geometry and alignment.
///
/// This function will return a constraint representing the limits imposed by the size of
/// the disk and the minimal alignment requirements for proper performance of the disk.
pub fn get_minimal_aligned_constraint<'b>(&self) -> Result<Constraint<'b>> {
Ok(Constraint {
constraint: cvt(unsafe { ped_device_get_minimal_aligned_constraint(self.device) })?,
source: ConstraintSource::New,
phantom: PhantomData,
})
}
/// Get a constraint that represents hardware requirements on geometry and alignment.
///
/// This function will return a constraint representing the limits imposed by the size of
/// the disk and the alignment requirements for optimal performance of the disk.
pub fn get_optimal_aligned_constraint<'b>(&self) -> Result<Constraint<'b>> {
Ok(Constraint {
constraint: cvt(unsafe { ped_device_get_optimal_aligned_constraint(self.device) })?,
source: ConstraintSource::New,
phantom: PhantomData,
})
}
/// Get an alignment that represents minimum hardware requirements on alignment.
///
/// When using media that has a physical sector size that is a multiple of the logical sector
/// size, it is desirable to have disk accesses (and thus partitions) properly aligned. Having
/// partitions not aligned to the minimum hardware requirements may lead to a performance
/// penalty.
///
/// The returned alignment describes the alignment for the start sector of the partition.
/// The end sector should be aligned too. To get the end sector alignment, decrease the
/// returned alignment's offset by 1.
pub fn get_minimum_alignment<'b>(&self) -> Option<Alignment<'b>> {
let alignment = unsafe { ped_device_get_minimum_alignment(self.device) };
if alignment.is_null() {
None
} else {
Some(Alignment {
alignment,
phantom: PhantomData,
})
}
}
/// Get an alignment that represents the hardware requirements for optimal performance.
///
/// The returned alignment describes the alignment for the start sector of the partition.
/// The end sector should be aligned too. To get the end alignment, decrease the returned
/// alignment's offset by 1.
pub fn get_optimum_alignment<'b>(&self) -> Option<Alignment<'b>> {
let alignment = unsafe { ped_device_get_optimum_alignment(self.device) };
if alignment.is_null() {
None
} else {
Some(Alignment {
alignment,
phantom: PhantomData,
})
}
}
/// Remove all identifying signatures of a partition table.
pub fn clobber(&mut self) -> Result<()> {
cvt(unsafe { ped_disk_clobber(self.device) })?;
Ok(())
}
pub fn model(&self) -> &str {
unsafe { str::from_utf8_unchecked(CStr::from_ptr((*self.device).model).to_bytes()) }
}
pub fn path(&self) -> &Path {
let cstr = unsafe { CStr::from_ptr((*self.device).path) };
let os_str = OsStr::from_bytes(cstr.to_bytes());
Path::new(os_str)
}
pub fn type_(&self) -> DeviceType {
unsafe { (*self.device).type_ as DeviceType }
}
pub fn sector_size(&self) -> u64 {
unsafe { (*self.device).sector_size as u64 }
}
pub fn phys_sector_size(&self) -> u64 {
unsafe { (*self.device).phys_sector_size as u64 }
}
pub fn length(&self) -> u64 {
unsafe { (*self.device).length as u64 }
}
pub fn open_count(&self) -> isize {
unsafe { (*self.device).open_count as isize }
}
get_bool!(read_only);
get_bool!(external_mode);
get_bool!(dirty);
get_bool!(boot_dirty);
get_geometry!(hw_geom);
get_geometry!(bios_geom);
pub fn host(&self) -> i16 {
unsafe { (*self.device).host as i16 }
}
pub fn did(&self) -> i16 {
unsafe { (*self.device).did as i16 }
}
// TODO: arch_specific
}
impl<'a> Iterator for DeviceIter<'a> {
type Item = Device<'a>;
fn next(&mut self) -> Option<Device<'a>> {
let device = unsafe { ped_device_get_next(self.0) };
if device.is_null() {
None
} else {
self.0 = device;
let mut device = unsafe { Device::from_ped_device(device) };
device.is_droppable = false;
Some(device)
}
}
}
impl<'a> Drop for Device<'a> {
fn drop(&mut self) {
unsafe {
if self.open_count() > 0 && self.is_droppable {
ped_device_close(self.device);
}
}
}
}
impl<'a, 'b> Drop for DeviceExternalAccess<'a, 'b> {
fn drop(&mut self) {
unsafe {
ped_device_end_external_access((self.0).device);
}
}
}
| 34.735661 | 98 | 0.612463 |
9b933480617dffad4bfb5a44bb86f603650efbf4
| 1,927 |
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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.
// Parity Ethereum 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 Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use jsonrpc_core::Error;
use jsonrpc_core::futures::{self, Future};
use jsonrpc_core::futures::sync::oneshot;
use v1::helpers::errors;
pub type Res<T> = Result<T, Error>;
pub struct Sender<T> {
sender: oneshot::Sender<Res<T>>,
}
impl<T> Sender<T> {
pub fn send(self, data: Res<T>) {
let res = self.sender.send(data);
if res.is_err() {
debug!(target: "rpc", "Responding to a no longer active request.");
}
}
}
pub struct Receiver<T> {
receiver: oneshot::Receiver<Res<T>>,
}
impl<T> Future for Receiver<T> {
type Item = T;
type Error = Error;
fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
let res = self.receiver.poll();
match res {
Ok(futures::Async::NotReady) => Ok(futures::Async::NotReady),
Ok(futures::Async::Ready(Ok(res))) => Ok(futures::Async::Ready(res)),
Ok(futures::Async::Ready(Err(err))) => Err(err),
Err(e) => {
debug!(target: "rpc", "Responding to a canceled request: {:?}", e);
Err(errors::internal("Request was canceled by client.", e))
},
}
}
}
pub fn oneshot<T>() -> (Sender<T>, Receiver<T>) {
let (tx, rx) = futures::oneshot();
(Sender {
sender: tx,
}, Receiver {
receiver: rx,
})
}
| 28.338235 | 75 | 0.675662 |
2fdd2b33b66aff4b7bff4372a478e4229165ed3e
| 10,674 |
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
// #[PerformanceCriticalPath]
use super::encoded::RawEncodeSnapshot;
use crate::storage::kv::Result;
use crate::storage::kv::{Cursor, ScanMode, Snapshot};
use crate::storage::Statistics;
use api_version::{APIV1TTL, APIV2};
use engine_traits::{CfName, IterOptions, DATA_KEY_PREFIX_LEN};
use kvproto::kvrpcpb::{ApiVersion, KeyRange};
use std::time::Duration;
use tikv_util::time::Instant;
use txn_types::{Key, KvPair};
use yatp::task::future::reschedule;
const MAX_TIME_SLICE: Duration = Duration::from_millis(2);
const MAX_BATCH_SIZE: usize = 1024;
pub enum RawStore<S: Snapshot> {
V1(RawStoreInner<S>),
V1TTL(RawStoreInner<RawEncodeSnapshot<S, APIV1TTL>>),
V2(RawStoreInner<RawEncodeSnapshot<S, APIV2>>),
}
impl<'a, S: Snapshot> RawStore<S> {
pub fn new(snapshot: S, api_version: ApiVersion) -> Self {
match api_version {
ApiVersion::V1 => RawStore::V1(RawStoreInner::new(snapshot)),
ApiVersion::V1ttl => RawStore::V1TTL(RawStoreInner::new(
RawEncodeSnapshot::from_snapshot(snapshot),
)),
ApiVersion::V2 => RawStore::V2(RawStoreInner::new(RawEncodeSnapshot::from_snapshot(
snapshot,
))),
}
}
pub fn raw_get_key_value(
&self,
cf: CfName,
key: &Key,
stats: &mut Statistics,
) -> Result<Option<Vec<u8>>> {
match self {
RawStore::V1(inner) => inner.raw_get_key_value(cf, key, stats),
RawStore::V1TTL(inner) => inner.raw_get_key_value(cf, key, stats),
RawStore::V2(inner) => inner.raw_get_key_value(cf, key, stats),
}
}
pub fn raw_get_key_ttl(
&self,
cf: CfName,
key: &'a Key,
stats: &'a mut Statistics,
) -> Result<Option<u64>> {
match self {
RawStore::V1(_) => panic!("get ttl on non-ttl store"),
RawStore::V1TTL(inner) => inner.snapshot.get_key_ttl_cf(cf, key, stats),
RawStore::V2(inner) => inner.snapshot.get_key_ttl_cf(cf, key, stats),
}
}
pub async fn forward_raw_scan(
&'a self,
cf: CfName,
start_key: &'a Key,
end_key: Option<&'a Key>,
limit: usize,
statistics: &'a mut Statistics,
key_only: bool,
) -> Result<Vec<Result<KvPair>>> {
let mut option = IterOptions::default();
if let Some(end) = end_key {
option.set_upper_bound(end.as_encoded(), DATA_KEY_PREFIX_LEN);
}
match self {
RawStore::V1(inner) => {
if key_only {
option.set_key_only(key_only);
}
inner
.forward_raw_scan(cf, start_key, limit, statistics, option, key_only)
.await
}
RawStore::V1TTL(inner) => {
inner
.forward_raw_scan(cf, start_key, limit, statistics, option, key_only)
.await
}
RawStore::V2(inner) => {
inner
.forward_raw_scan(cf, start_key, limit, statistics, option, key_only)
.await
}
}
}
pub async fn reverse_raw_scan(
&'a self,
cf: CfName,
start_key: &'a Key,
end_key: Option<&'a Key>,
limit: usize,
statistics: &'a mut Statistics,
key_only: bool,
) -> Result<Vec<Result<KvPair>>> {
let mut option = IterOptions::default();
if let Some(end) = end_key {
option.set_lower_bound(end.as_encoded(), DATA_KEY_PREFIX_LEN);
}
match self {
RawStore::V1(inner) => {
if key_only {
option.set_key_only(key_only);
}
inner
.reverse_raw_scan(cf, start_key, limit, statistics, option, key_only)
.await
}
RawStore::V1TTL(inner) => {
inner
.reverse_raw_scan(cf, start_key, limit, statistics, option, key_only)
.await
}
RawStore::V2(inner) => {
inner
.reverse_raw_scan(cf, start_key, limit, statistics, option, key_only)
.await
}
}
}
pub async fn raw_checksum_ranges(
&'a self,
cf: CfName,
ranges: Vec<KeyRange>,
statistics: &'a mut Statistics,
) -> Result<(u64, u64, u64)> {
match self {
RawStore::V1(inner) => inner.raw_checksum_ranges(cf, ranges, statistics).await,
RawStore::V1TTL(inner) => inner.raw_checksum_ranges(cf, ranges, statistics).await,
RawStore::V2(inner) => inner.raw_checksum_ranges(cf, ranges, statistics).await,
}
}
}
pub struct RawStoreInner<S: Snapshot> {
snapshot: S,
}
impl<'a, S: Snapshot> RawStoreInner<S> {
pub fn new(snapshot: S) -> Self {
RawStoreInner { snapshot }
}
pub fn raw_get_key_value(
&self,
cf: CfName,
key: &Key,
stats: &mut Statistics,
) -> Result<Option<Vec<u8>>> {
// no scan_count for this kind of op.
let key_len = key.as_encoded().len();
self.snapshot.get_cf(cf, key).map(|value| {
stats.data.flow_stats.read_keys = 1;
stats.data.flow_stats.read_bytes =
key_len + value.as_ref().map(|v| v.len()).unwrap_or(0);
value
})
}
/// Scan raw keys in [`start_key`, `end_key`), returns at most `limit` keys. If `end_key` is
/// `None`, it means unbounded.
///
/// If `key_only` is true, the value corresponding to the key will not be read. Only scanned
/// keys will be returned.
pub async fn forward_raw_scan(
&'a self,
cf: CfName,
start_key: &'a Key,
limit: usize,
statistics: &'a mut Statistics,
option: IterOptions,
key_only: bool,
) -> Result<Vec<Result<KvPair>>> {
if limit == 0 {
return Ok(vec![]);
}
let mut cursor = Cursor::new(self.snapshot.iter_cf(cf, option)?, ScanMode::Forward, false);
let statistics = statistics.mut_cf_statistics(cf);
if !cursor.seek(start_key, statistics)? {
return Ok(vec![]);
}
let mut pairs = vec![];
let mut row_count = 0;
let mut time_slice_start = Instant::now();
while cursor.valid()? {
row_count += 1;
if row_count >= MAX_BATCH_SIZE {
if time_slice_start.saturating_elapsed() > MAX_TIME_SLICE {
reschedule().await;
time_slice_start = Instant::now();
}
row_count = 0;
}
pairs.push(Ok((
cursor.key(statistics).to_owned(),
if key_only {
vec![]
} else {
cursor.value(statistics).to_owned()
},
)));
if pairs.len() < limit {
cursor.next(statistics);
} else {
break;
}
}
Ok(pairs)
}
/// Scan raw keys in [`end_key`, `start_key`) in reverse order, returns at most `limit` keys. If
/// `start_key` is `None`, it means it's unbounded.
///
/// If `key_only` is true, the value
/// corresponding to the key will not be read out. Only scanned keys will be returned.
pub async fn reverse_raw_scan(
&'a self,
cf: CfName,
start_key: &'a Key,
limit: usize,
statistics: &'a mut Statistics,
option: IterOptions,
key_only: bool,
) -> Result<Vec<Result<KvPair>>> {
if limit == 0 {
return Ok(vec![]);
}
let mut cursor = Cursor::new(
self.snapshot.iter_cf(cf, option)?,
ScanMode::Backward,
false,
);
let statistics = statistics.mut_cf_statistics(cf);
if !cursor.reverse_seek(start_key, statistics)? {
return Ok(vec![]);
}
let mut pairs = vec![];
let mut row_count = 0;
let mut time_slice_start = Instant::now();
while cursor.valid()? {
row_count += 1;
if row_count >= MAX_BATCH_SIZE {
if time_slice_start.saturating_elapsed() > MAX_TIME_SLICE {
reschedule().await;
time_slice_start = Instant::now();
}
row_count = 0;
}
pairs.push(Ok((
cursor.key(statistics).to_owned(),
if key_only {
vec![]
} else {
cursor.value(statistics).to_owned()
},
)));
if pairs.len() < limit {
cursor.prev(statistics);
} else {
break;
}
}
Ok(pairs)
}
pub async fn raw_checksum_ranges(
&'a self,
cf: CfName,
ranges: Vec<KeyRange>,
statistics: &'a mut Statistics,
) -> Result<(u64, u64, u64)> {
let mut total_bytes = 0;
let mut total_kvs = 0;
let mut digest = crc64fast::Digest::new();
let mut row_count = 0;
let mut time_slice_start = Instant::now();
let statistics = statistics.mut_cf_statistics(cf);
for r in ranges {
let mut opts = IterOptions::new(None, None, false);
opts.set_upper_bound(r.get_end_key(), DATA_KEY_PREFIX_LEN);
let mut cursor =
Cursor::new(self.snapshot.iter_cf(cf, opts)?, ScanMode::Forward, false);
cursor.seek(&Key::from_encoded(r.get_start_key().to_vec()), statistics)?;
while cursor.valid()? {
row_count += 1;
if row_count >= MAX_BATCH_SIZE {
if time_slice_start.saturating_elapsed() > MAX_TIME_SLICE {
reschedule().await;
time_slice_start = Instant::now();
}
row_count = 0;
}
let k = cursor.key(statistics);
let v = cursor.value(statistics);
digest.write(k);
digest.write(v);
total_kvs += 1;
total_bytes += k.len() + v.len();
cursor.next(statistics);
}
}
Ok((digest.sum64(), total_kvs, total_bytes as u64))
}
}
| 33.35625 | 100 | 0.516863 |
7adb8370d05d657d4e0bb856fa871add177e21b3
| 1,160 |
use std::collections::HashSet;
#[aoc_generator(day6)]
pub fn input_generator(input: &str) -> Vec<Vec<Vec<char>>> {
input
.split("\n\n")
.map(|group| {
group
.lines()
.map(|person| person.chars().collect())
.collect()
})
.collect::<Vec<_>>()
}
#[aoc(day6, part1)]
pub fn part1(groups: &[Vec<Vec<char>>]) -> usize {
let group_counts = groups.iter().map(|group| {
let answers = group.iter().flatten().collect::<HashSet<_>>();
answers.len()
});
group_counts.sum()
}
#[aoc(day6, part2)]
pub fn part2(groups: &[Vec<Vec<char>>]) -> usize {
let group_counts = groups.iter().map(|group| {
let answers = group
.iter()
.map(|person| person.iter().cloned().collect::<HashSet<char>>())
.fold(None, |left: Option<HashSet<char>>, right| {
Some(match left {
None => right,
Some(left) => left.intersection(&right).cloned().collect(),
})
})
.unwrap();
answers.len()
});
group_counts.sum()
}
| 27.619048 | 79 | 0.487931 |
f4229c8d477c9a239fdf16fa9fcfb39d9b884e52
| 13,961 |
use crate::generate::cpp::constants::{
custom_scalar_strings, enum_member_substitutions, pseudo_enums, reserved_words,
suffixed_enum_names, suffixed_value_names, PseudoEnumSpec,
};
use crate::model;
use crate::model::builtin::BuiltinString;
use crate::model::create::{Create, CreateError, CreateResult};
use crate::model::enumeration::OtherField;
use crate::model::post_process::PostProcess;
use crate::model::scalar::{Bound, NumericData, Range, ScalarNumeric};
use crate::model::symbol::Symbol;
use crate::model::transform::Transform;
use crate::model::Def::Enumeration;
use crate::model::{Def, DefaultCreate};
use crate::xsd::choice::{Choice, ChoiceItem};
use crate::xsd::complex_type::{Children, ComplexType, Parent};
use crate::xsd::element::{ElementDef, ElementRef};
use crate::xsd::id::{Id, RootNodeType};
use crate::xsd::primitives::Numeric;
use crate::xsd::primitives::{BaseType, Character, PrefixedString, Primitive};
use crate::xsd::restriction::Facet;
use crate::xsd::{complex_type, element, simple_type, Entry, Xsd};
use indexmap::set::IndexSet;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct MxModeler {
enum_member_substitutions: HashMap<String, String>,
suffixed_enum_names: IndexSet<String>,
suffixed_value_names: HashMap<String, String>,
reserved_words: IndexSet<String>,
pseudo_enums: HashMap<String, PseudoEnumSpec>,
custom_scalar_strings: IndexSet<&'static str>,
}
impl Transform for MxModeler {
fn name(&self) -> &'static str {
"mx-cpp"
}
fn transform(&self, entry: &Entry, xsd: &Xsd) -> Result<Entry, CreateError> {
let mut cloned = entry.clone();
if let Entry::SimpleType(st) = &mut cloned {
let symbolized = Symbol::new(st.name.as_str());
if self.suffixed_enum_names.contains(symbolized.pascal()) {
st.name.push_str("-enum");
}
}
Ok(cloned)
}
}
impl Create for MxModeler {
fn name(&self) -> &'static str {
"mx-cpp"
}
fn create(&self, entry: &Entry, xsd: &Xsd) -> CreateResult {
if let Some(spec) = self.pseudo_enums.get(entry.id().display().as_str()) {
return create_pseudo_enum(entry, spec);
}
if let Id::Root(rid) = entry.id() {
if rid.type_() == RootNodeType::ComplexType {
if rid.name().as_ref() == "dynamics" {
return self.create_dynamics(entry);
}
}
}
Ok(None)
}
}
impl PostProcess for MxModeler {
fn name(&self) -> &'static str {
"mx-cpp"
}
fn process(&self, model: &Def, xsd: &Xsd) -> Result<Def, CreateError> {
if let Def::Enumeration(enumer) = model {
let mut cloned = enumer.clone();
for (i, member) in cloned.members.iter_mut().enumerate() {
// add an underscore as a suffix to camel case representations that would otherwise
// collide with reserved words in C++.
if self.reserved_words.contains(member.camel()) {
let mut replacement = member.camel().to_owned();
replacement.push('_');
member.set_camel(replacement)
}
// replace certain enum representations that would be illegal in C++, e.g. 16th.
if let Some(replacement) = self.enum_member_substitutions.get(member.original()) {
member.replace(replacement);
}
// replace an empty string value with some kind of symbol name.
if member.original() == "" {
member.replace("emptystring");
}
if i == 0 && member.original() == cloned.default.original() {
if member.renamed_to() != cloned.default.renamed_to() {
cloned.default.replace(member.renamed_to());
}
if member.camel() != cloned.default.camel() {
cloned.default.set_camel(member.camel());
}
}
}
return Ok(Def::Enumeration(cloned));
} else if let Def::ScalarString(scalar_string) = model {
if self
.custom_scalar_strings
.contains(scalar_string.name.original())
{
return Ok(Def::CustomScalarString(scalar_string.clone()));
} else if let Some(new_name) =
self.suffixed_value_names.get(scalar_string.name.original())
{
let mut st = scalar_string.clone();
st.name.replace(&new_name);
return Ok(Def::ScalarString(st));
}
} else if let Def::ScalarNumber(scalar_number) = model {
match scalar_number {
ScalarNumeric::Decimal(n) => {
if let Some(new_name) = self.suffixed_value_names.get(n.name.original()) {
let mut n = n.clone();
n.name.replace(&new_name);
return Ok(Def::ScalarNumber(ScalarNumeric::Decimal(n)));
}
}
ScalarNumeric::Integer(n) => {
let mut is_changed = false;
let n = if n.name.original() == "accordion-middle" {
let mut changed = n.clone();
changed.range.min = Some(Bound::Inclusive(0));
changed.documentation.push_str(
"\n\nNote: MusicXML specifies the minimum allowable value \
as 1, however test documents exist that have a value of 0. This library supports \
a minimum value of 0. Per https://github.com/w3c/musicxml/issues/134, the correct \
representation for 0 dots is to omit the element, so it is possible to create \
invalid MusicXML by setting the value to 0 here.",
);
is_changed = true;
changed
} else {
n.clone()
};
// note: accordion-middle is one of the values that is renamed here. if it were
// not, it would need to be explicitly returned.
if let Some(new_name) = self.suffixed_value_names.get(n.name.original()) {
is_changed = true;
let mut mut_num = n.clone();
mut_num.name.replace(&new_name);
return Ok(Def::ScalarNumber(ScalarNumeric::Integer(mut_num)));
}
}
}
} else if let Def::DerivedSimpleType(derived) = model {
match derived.name.original() {
"positive-divisions" => {
let replacement = NumericData {
name: derived.name.clone(),
base_type: Numeric::Decimal,
documentation: derived.documentation.clone(),
range: Range {
min: Some(Bound::Exclusive(0.0)),
max: None,
},
};
return Ok(Def::ScalarNumber(ScalarNumeric::Decimal(replacement)));
}
unhandled => {
return Err(CreateError {
message: format!("Unhandled DerivedSimpleType: '{}'", unhandled),
})
}
}
}
Ok(model.clone())
}
}
impl MxModeler {
pub fn new() -> Self {
Self {
enum_member_substitutions: enum_member_substitutions(),
suffixed_enum_names: suffixed_enum_names(),
suffixed_value_names: suffixed_value_names(),
reserved_words: reserved_words(),
pseudo_enums: pseudo_enums(),
custom_scalar_strings: custom_scalar_strings(),
}
}
fn create_dynamics(&self, entry: &Entry) -> CreateResult {
let (ct, p, choice) = self.unwrap_dynamics(entry)?;
let mut enumer = model::enumeration::Enumeration {
/// TODO - get the name in a generic manner
name: Symbol::new("dynamics enum"),
members: vec![],
documentation: entry.documentation(),
default: Symbol::new("mf"),
other_field: None,
};
for c in &choice.choices {
let mut is_other_field_found = false;
if let Some(name) = self.unwrap_empty_element(c)? {
enumer.members.push(Symbol::new(name));
} else {
let other_field_name = self.unwrap_other_field(c)?;
if enumer.other_field.is_some() {
return Err(CreateError {
message: "create_dynamics: multiple 'other' fields found".to_string(),
});
}
enumer.other_field = Some(OtherField {
name: Symbol::new(other_field_name),
type_: BuiltinString::String,
wrapper_class_name: Symbol::new("dynamics value"),
})
}
}
// TODO - also create the 'wrapping' element named 'dynamics'
Ok(Some(vec![Def::Enumeration(enumer)]))
}
fn unwrap_dynamics<'a>(
&self,
entry: &'a Entry,
) -> std::result::Result<(&'a ComplexType, &'a Parent, &'a Choice), CreateError> {
let ct = if let Entry::ComplexType(ct) = entry {
ct
} else {
return Err(CreateError {
message: "create_dynamics: wrong type".to_string(),
});
};
let p = if let complex_type::Payload::Parent(p) = &ct.payload {
p
} else {
return Err(CreateError {
message: "create_dynamics: expected parent".to_string(),
});
};
let children = if let Some(children) = &p.children {
children
} else {
return Err(CreateError {
message: "create_dynamics: expected children".to_string(),
});
};
let choice = if let Children::Choice(choice) = children {
choice
} else {
return Err(CreateError {
message: "create_dynamics: expected choice".to_string(),
});
};
Ok((ct, p, choice))
}
fn unwrap_empty_element<'a>(
&self,
c: &'a ChoiceItem,
) -> std::result::Result<Option<&'a str>, CreateError> {
let ref_: &ElementRef = if let ChoiceItem::Element(wrapped) = c {
let ref_ = if let element::Element::Reference(ref_) = wrapped {
ref_
} else {
return Err(CreateError {
message: "unwrap_empty_element: expected ElementDef".to_string(),
});
};
ref_
} else {
return Err(CreateError {
message: "unwrap_empty_element: expected Element".to_string(),
});
};
if ref_.type_ == BaseType::Custom("empty".to_owned()) {
Ok(Some(ref_.name.as_str()))
} else {
Ok(None)
}
}
fn unwrap_simple_element<'a>(
&self,
c: &'a ChoiceItem,
) -> std::result::Result<Option<(&'a str, &'a BaseType)>, CreateError> {
let ref_: &ElementRef = if let ChoiceItem::Element(wrapped) = c {
let ref_ = if let element::Element::Reference(ref_) = wrapped {
ref_
} else {
return Err(CreateError {
message: "unwrap_empty_element: expected ElementDef".to_string(),
});
};
ref_
} else {
return Err(CreateError {
message: "unwrap_empty_element: expected Element".to_string(),
});
};
/// TODO - allow all base types?
if ref_.type_.is_string() || ref_.type_.is_token() {
Ok(Some((ref_.name.as_str(), &ref_.type_)))
} else {
Ok(None)
}
}
fn unwrap_other_field<'a>(
&self,
c: &'a ChoiceItem,
) -> std::result::Result<&'a str, CreateError> {
let found_stuff = if let Some(other_field) = self.unwrap_simple_element(c)? {
other_field
} else {
return Err(CreateError {
message: "create_dynamics: unable to unwrap the 'other' field".to_string(),
});
};
if *found_stuff.1 != BaseType::String {
return return Err(CreateError {
message: format!(
"unwrap_other_field: unsupported 'other' field type '{}'",
found_stuff.1.name()
),
});
}
Ok(found_stuff.0)
}
}
fn create_pseudo_enum(entry: &Entry, spec: &PseudoEnumSpec) -> CreateResult {
let original = entry.id().name();
let rename = format!("{}-enum", original);
let mut symbol = Symbol::new(original);
symbol.replace(rename);
let mut enumer = model::enumeration::Enumeration {
name: symbol,
members: vec![],
documentation: entry.documentation(),
default: Symbol::new(spec.default_value.as_str()),
other_field: Some(OtherField {
name: Symbol::new(spec.extra_field_name.as_str()),
// TODO - check if it's actually xs:token
type_: BuiltinString::String,
wrapper_class_name: Symbol::new(spec.class_name.as_str()),
}),
};
for s in &spec.members {
enumer.members.push(Symbol::new(s.as_str()));
}
Ok(Some(vec![Def::Enumeration(enumer)]))
}
| 38.997207 | 107 | 0.524604 |
d9671684c617a7888cca0f0cf82beb99cdb24679
| 8,206 |
use anyhow::Result;
use clap::{App, AppSettings, Arg};
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::sync::Arc;
use tokio::time::Duration;
use webrtc::api::APIBuilder;
use webrtc::data::data_channel::data_channel_message::DataChannelMessage;
use webrtc::data::data_channel::data_channel_parameters::DataChannelParameters;
use webrtc::data::data_channel::RTCDataChannel;
use webrtc::data::sctp_transport::sctp_transport_capabilities::SCTPTransportCapabilities;
use webrtc::media::dtls_transport::dtls_parameters::DTLSParameters;
use webrtc::media::ice_transport::ice_parameters::RTCIceParameters;
use webrtc::media::ice_transport::ice_role::RTCIceRole;
use webrtc::peer::ice::ice_candidate::RTCIceCandidate;
use webrtc::peer::ice::ice_gather::RTCIceGatherOptions;
use webrtc::peer::ice::ice_server::RTCIceServer;
use webrtc::util::math_rand_alpha;
#[tokio::main]
async fn main() -> Result<()> {
let mut app = App::new("ortc")
.version("0.1.0")
.author("Rain Liu <[email protected]>")
.about("An example of ORTC.")
.setting(AppSettings::DeriveDisplayOrder)
.setting(AppSettings::SubcommandsNegateReqs)
.arg(
Arg::with_name("FULLHELP")
.help("Prints more detailed help information")
.long("fullhelp"),
)
.arg(
Arg::with_name("debug")
.long("debug")
.short("d")
.help("Prints debug log information"),
)
.arg(
Arg::with_name("offer")
.long("offer")
.help("Act as the offerer if set."),
);
let matches = app.clone().get_matches();
if matches.is_present("FULLHELP") {
app.print_long_help().unwrap();
std::process::exit(0);
}
let is_offer = matches.is_present("offer");
let debug = matches.is_present("debug");
if debug {
env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();
}
// Everything below is the Pion WebRTC (ORTC) API! Thanks for using it ❤️.
// Prepare ICE gathering options
let ice_options = RTCIceGatherOptions {
ice_servers: vec![RTCIceServer {
urls: vec!["stun:stun.l.google.com:19302".to_owned()],
..Default::default()
}],
..Default::default()
};
// Create an API object
let api = APIBuilder::new().build();
// Create the ICE gatherer
let gatherer = Arc::new(api.new_ice_gatherer(ice_options)?);
// Construct the ICE transport
let ice = Arc::new(api.new_ice_transport(Arc::clone(&gatherer)));
// Construct the DTLS transport
let dtls = Arc::new(api.new_dtls_transport(Arc::clone(&ice), vec![])?);
// Construct the SCTP transport
let sctp = Arc::new(api.new_sctp_transport(Arc::clone(&dtls))?);
// Handle incoming data channels
sctp.on_data_channel(Box::new(|d: Arc<RTCDataChannel>| {
let d_label = d.label().to_owned();
let d_id = d.id();
println!("New DataChannel {} {}", d_label, d_id);
// Register the handlers
Box::pin(async move {
let d2 = Arc::clone(&d);
let d_label2 = d_label.clone();
let d_id2 = d_id.clone();
d.on_open(Box::new(move || {
println!("Data channel '{}'-'{}' open. Random messages will now be sent to any connected DataChannels every 5 seconds", d_label2, d_id2);
Box::pin(async move {
let _ = handle_on_open(d2).await;
})
})).await;
// Register text message handling
d.on_message(Box::new(move |msg: DataChannelMessage| {
let msg_str = String::from_utf8(msg.data.to_vec()).unwrap();
print!("Message from DataChannel '{}': '{}'\n", d_label, msg_str);
Box::pin(async {})
})).await;
})
})).await;
let (gather_finished_tx, mut gather_finished_rx) = tokio::sync::mpsc::channel::<()>(1);
let mut gather_finished_tx = Some(gather_finished_tx);
gatherer
.on_local_candidate(Box::new(move |c: Option<RTCIceCandidate>| {
if c.is_none() {
gather_finished_tx.take();
}
Box::pin(async {})
}))
.await;
// Gather candidates
gatherer.gather().await?;
let _ = gather_finished_rx.recv().await;
let ice_candidates = gatherer.get_local_candidates().await?;
let ice_parameters = gatherer.get_local_parameters().await?;
let dtls_parameters = dtls.get_local_parameters()?;
let sctp_capabilities = sctp.get_capabilities();
let local_signal = Signal {
ice_candidates,
ice_parameters,
dtls_parameters,
sctp_capabilities,
};
// Exchange the information
let json_str = serde_json::to_string(&local_signal)?;
let b64 = signal::encode(&json_str);
println!("{}", b64);
let line = signal::must_read_stdin()?;
let json_str = signal::decode(line.as_str())?;
let remote_signal = serde_json::from_str::<Signal>(&json_str)?;
let ice_role = if is_offer {
RTCIceRole::Controlling
} else {
RTCIceRole::Controlled
};
ice.set_remote_candidates(&remote_signal.ice_candidates)
.await?;
// Start the ICE transport
ice.start(&remote_signal.ice_parameters, Some(ice_role))
.await?;
// Start the DTLS transport
dtls.start(remote_signal.dtls_parameters).await?;
// Start the SCTP transport
sctp.start(remote_signal.sctp_capabilities).await?;
// Construct the data channel as the offerer
if is_offer {
let id = 1u16;
let dc_params = DataChannelParameters {
label: "Foo".to_owned(),
id,
..Default::default()
};
let d = Arc::new(api.new_data_channel(sctp, dc_params).await?);
// Register the handlers
// channel.OnOpen(handleOnOpen(channel)) // TODO: OnOpen on handle ChannelAck
// Temporary alternative
let d2 = Arc::clone(&d);
tokio::spawn(async move {
let _ = handle_on_open(d2).await;
});
let d_label = d.label().to_owned();
d.on_message(Box::new(move |msg: DataChannelMessage| {
let msg_str = String::from_utf8(msg.data.to_vec()).unwrap();
print!("Message from DataChannel '{}': '{}'\n", d_label, msg_str);
Box::pin(async {})
}))
.await;
}
println!("Press ctlr-c to stop");
tokio::signal::ctrl_c().await.unwrap();
Ok(())
}
// Signal is used to exchange signaling info.
// This is not part of the ORTC spec. You are free
// to exchange this information any way you want.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Signal {
#[serde(rename = "iceCandidates")]
ice_candidates: Vec<RTCIceCandidate>, // `json:"iceCandidates"`
#[serde(rename = "iceParameters")]
ice_parameters: RTCIceParameters, // `json:"iceParameters"`
#[serde(rename = "dtlsParameters")]
dtls_parameters: DTLSParameters, // `json:"dtlsParameters"`
#[serde(rename = "sctpCapabilities")]
sctp_capabilities: SCTPTransportCapabilities, // `json:"sctpCapabilities"`
}
async fn handle_on_open(d: Arc<RTCDataChannel>) -> Result<()> {
let mut result = Result::<usize>::Ok(0);
while result.is_ok() {
let timeout = tokio::time::sleep(Duration::from_secs(5));
tokio::pin!(timeout);
tokio::select! {
_ = timeout.as_mut() =>{
let message = math_rand_alpha(15);
println!("Sending '{}'", message);
result = d.send_text(message).await;
}
};
}
Ok(())
}
| 32.307087 | 153 | 0.58701 |
d96bfb0a4fea213f82bd102ebec12cdb62fba505
| 2,595 |
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
pub mod cmd_resp;
pub mod config;
pub mod fsm;
pub mod memory;
pub mod msg;
pub mod transport;
#[macro_use]
pub mod util;
mod async_io;
mod bootstrap;
mod compaction_guard;
mod hibernate_state;
mod local_metrics;
mod metrics;
mod peer;
mod peer_storage;
mod read_queue;
mod region_snapshot;
mod replication_mode;
mod snap;
mod txn_ext;
mod worker;
pub use self::bootstrap::{
bootstrap_store, clear_prepare_bootstrap_cluster, clear_prepare_bootstrap_key, initial_region,
prepare_bootstrap_cluster,
};
pub use self::compaction_guard::CompactionGuardGeneratorFactory;
pub use self::config::Config;
pub use self::fsm::{DestroyPeerJob, RaftRouter, StoreInfo};
pub use self::hibernate_state::{GroupState, HibernateState};
pub use self::memory::*;
pub use self::metrics::RAFT_ENTRY_FETCHES_VEC;
pub use self::msg::{
Callback, CasualMessage, ExtCallback, InspectedRaftMessage, MergeResultKind, PeerMsg, PeerTick,
RaftCmdExtraOpts, RaftCommand, ReadCallback, ReadResponse, SignificantMsg, StoreMsg, StoreTick,
WriteCallback, WriteResponse,
};
pub use self::peer::{
AbstractPeer, Peer, PeerStat, ProposalContext, RequestInspector, RequestPolicy,
};
pub use self::peer_storage::{
clear_meta, do_snapshot, write_initial_apply_state, write_initial_raft_state, write_peer_state,
PeerStorage, RaftlogFetchResult, SnapState, INIT_EPOCH_CONF_VER, INIT_EPOCH_VER,
MAX_INIT_ENTRY_COUNT, RAFT_INIT_LOG_INDEX, RAFT_INIT_LOG_TERM,
};
pub use self::read_queue::ReadIndexContext;
pub use self::region_snapshot::{RegionIterator, RegionSnapshot};
pub use self::replication_mode::{GlobalReplicationState, StoreGroup};
pub use self::snap::{
check_abort, copy_snapshot,
snap_io::{apply_sst_cf_file, build_sst_cf_file},
ApplyOptions, Error as SnapError, SnapEntry, SnapKey, SnapManager, SnapManagerBuilder,
Snapshot, SnapshotStatistics,
};
pub use self::transport::{
CasualRouter, ProposalRouter, SignificantRouter, StoreRouter, Transport,
};
pub use self::txn_ext::{PeerPessimisticLocks, PessimisticLockPair, TxnExt};
pub use self::util::{RegionReadProgress, RegionReadProgressRegistry};
pub use self::worker::RefreshConfigTask;
pub use self::worker::{
AutoSplitController, FlowStatistics, FlowStatsReporter, PdTask, QueryStats, ReadDelegate,
ReadStats, SplitConfig, SplitConfigManager, TrackVer, WriteStats,
};
pub use self::worker::{CheckLeaderRunner, CheckLeaderTask};
pub use self::worker::{KeyEntry, LocalReader, RegionTask};
pub use self::worker::{SplitCheckRunner, SplitCheckTask};
| 35.547945 | 99 | 0.792293 |
03ce72b0e114cdf1745a7ec723820247944c2f7f
| 2,690 |
extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;
use std::mem;
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, Parser},
spanned::Spanned,
parse_quote,
};
#[proc_macro_attribute]
pub fn quickcheck(_args: TokenStream, input: TokenStream) -> TokenStream {
let output = match syn::Item::parse.parse(input.clone()) {
Ok(syn::Item::Fn(mut item_fn)) => {
let mut inputs = syn::punctuated::Punctuated::new();
let mut errors = Vec::new();
item_fn.decl.inputs.iter().for_each(|input| match *input {
syn::FnArg::Captured(syn::ArgCaptured { ref ty, .. }) => {
inputs.push(parse_quote!(_: #ty));
},
_ => {
errors.push(syn::parse::Error::new(
input.span(),
"unsupported kind of function argument",
))
},
});
if errors.is_empty() {
let attrs = mem::replace(&mut item_fn.attrs, Vec::new());
let name = &item_fn.ident;
let fn_type = syn::TypeBareFn {
lifetimes: None,
unsafety: item_fn.unsafety.clone(),
abi: item_fn.abi.clone(),
fn_token: <syn::Token![fn]>::default(),
paren_token: syn::token::Paren::default(),
inputs,
variadic: item_fn.decl.variadic.clone(),
output: item_fn.decl.output.clone(),
};
quote! {
#[test]
#(#attrs)*
fn #name() {
#item_fn
::quickcheck::quickcheck(#name as #fn_type)
}
}
} else {
errors.iter().map(syn::parse::Error::to_compile_error).collect()
}
},
Ok(syn::Item::Static(mut item_static)) => {
let attrs = mem::replace(&mut item_static.attrs, Vec::new());
let name = &item_static.ident;
quote! {
#[test]
#(#attrs)*
fn #name() {
#item_static
::quickcheck::quickcheck(#name)
}
}
},
_ => {
let span = proc_macro2::TokenStream::from(input).span();
let msg = "#[quickcheck] is only supported on statics and functions";
syn::parse::Error::new(span, msg).to_compile_error()
}
};
output.into()
}
| 31.647059 | 81 | 0.45316 |
627202e60e32890d86283fbdc3cd0953ece09459
| 114 |
//! The grammar definition.
pub mod consts;
pub mod parse_tree;
pub mod pattern;
pub mod repr;
// pub mod token;
| 14.25 | 27 | 0.719298 |
754708b4cbf614311e5a3b4499f53d300838aee5
| 3,486 |
#[doc = r" Value read from the register"]
pub struct R {
bits: u16,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u16,
}
impl super::PACKET_RAM_1_131 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct LSBYTER {
bits: u8,
}
impl LSBYTER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct MSBYTER {
bits: u8,
}
impl MSBYTER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _LSBYTEW<'a> {
w: &'a mut W,
}
impl<'a> _LSBYTEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u16) << OFFSET);
self.w.bits |= ((value & MASK) as u16) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MSBYTEW<'a> {
w: &'a mut W,
}
impl<'a> _MSBYTEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u16) << OFFSET);
self.w.bits |= ((value & MASK) as u16) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
self.bits
}
#[doc = "Bits 0:7 - LSBYTE"]
#[inline]
pub fn lsbyte(&self) -> LSBYTER {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u16) as u8
};
LSBYTER { bits }
}
#[doc = "Bits 8:15 - MSBYTE"]
#[inline]
pub fn msbyte(&self) -> MSBYTER {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u16) as u8
};
MSBYTER { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u16) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:7 - LSBYTE"]
#[inline]
pub fn lsbyte(&mut self) -> _LSBYTEW {
_LSBYTEW { w: self }
}
#[doc = "Bits 8:15 - MSBYTE"]
#[inline]
pub fn msbyte(&mut self) -> _MSBYTEW {
_MSBYTEW { w: self }
}
}
| 23.714286 | 59 | 0.49082 |
db24e4c8bf5b0ec270b0d8cec22c50fd9f80051c
| 50,863 |
// Miniscript
// Written in 2018 by
// Andrew Poelstra <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Satisfaction and Dissatisfaction
//!
//! Traits and implementations to support producing witnesses for Miniscript
//! scriptpubkeys.
//!
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use std::{cmp, i64, mem};
use bitcoin;
use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d};
use bitcoin::secp256k1::XOnlyPublicKey;
use bitcoin::util::taproot::{ControlBlock, LeafVersion, TapLeafHash};
use crate::miniscript::limits::{
HEIGHT_TIME_THRESHOLD, SEQUENCE_LOCKTIME_DISABLE_FLAG, SEQUENCE_LOCKTIME_TYPE_FLAG,
};
use crate::util::witness_size;
use crate::{Miniscript, MiniscriptKey, ScriptContext, Terminal, ToPublicKey};
/// Type alias for 32 byte Preimage.
pub type Preimage32 = [u8; 32];
/// Trait describing a lookup table for signatures, hash preimages, etc.
/// Every method has a default implementation that simply returns `None`
/// on every query. Users are expected to override the methods that they
/// have data for.
pub trait Satisfier<Pk: MiniscriptKey + ToPublicKey> {
/// Given a public key, look up an ECDSA signature with that key
fn lookup_ecdsa_sig(&self, _: &Pk) -> Option<bitcoin::EcdsaSig> {
None
}
/// Lookup the tap key spend sig
fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::SchnorrSig> {
None
}
/// Given a public key and a associated leaf hash, look up an schnorr signature with that key
fn lookup_tap_leaf_script_sig(&self, _: &Pk, _: &TapLeafHash) -> Option<bitcoin::SchnorrSig> {
None
}
/// Obtain a reference to the control block for a ver and script
fn lookup_tap_control_block_map(
&self,
) -> Option<&BTreeMap<ControlBlock, (bitcoin::Script, LeafVersion)>> {
None
}
/// Given a `Pkh`, lookup corresponding `Pk`
fn lookup_pkh_pk(&self, _: &Pk::Hash) -> Option<Pk> {
None
}
/// Given a keyhash, look up the EC signature and the associated key
/// Even if signatures for public key Hashes are not available, the users
/// can use this map to provide pkh -> pk mapping which can be useful
/// for dissatisfying pkh.
fn lookup_pkh_ecdsa_sig(
&self,
_: &Pk::Hash,
) -> Option<(bitcoin::PublicKey, bitcoin::EcdsaSig)> {
None
}
/// Given a keyhash, look up the schnorr signature and the associated key
/// Even if signatures for public key Hashes are not available, the users
/// can use this map to provide pkh -> pk mapping which can be useful
/// for dissatisfying pkh.
fn lookup_pkh_tap_leaf_script_sig(
&self,
_: &(Pk::Hash, TapLeafHash),
) -> Option<(XOnlyPublicKey, bitcoin::SchnorrSig)> {
None
}
/// Given a SHA256 hash, look up its preimage
fn lookup_sha256(&self, _: sha256::Hash) -> Option<Preimage32> {
None
}
/// Given a HASH256 hash, look up its preimage
fn lookup_hash256(&self, _: sha256d::Hash) -> Option<Preimage32> {
None
}
/// Given a RIPEMD160 hash, look up its preimage
fn lookup_ripemd160(&self, _: ripemd160::Hash) -> Option<Preimage32> {
None
}
/// Given a HASH160 hash, look up its preimage
fn lookup_hash160(&self, _: hash160::Hash) -> Option<Preimage32> {
None
}
/// Assert whether an relative locktime is satisfied
fn check_older(&self, _: u32) -> bool {
false
}
/// Assert whether a absolute locktime is satisfied
fn check_after(&self, _: u32) -> bool {
false
}
}
// Allow use of `()` as a "no conditions available" satisfier
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for () {}
/// Newtype around `u32` which implements `Satisfier` using `n` as an
/// relative locktime
pub struct Older(pub u32);
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for Older {
fn check_older(&self, n: u32) -> bool {
if self.0 & SEQUENCE_LOCKTIME_DISABLE_FLAG != 0 {
return true;
}
/* If nSequence encodes a relative lock-time, this mask is
* applied to extract that lock-time from the sequence field. */
const SEQUENCE_LOCKTIME_MASK: u32 = 0x0000ffff;
let mask = SEQUENCE_LOCKTIME_MASK | SEQUENCE_LOCKTIME_TYPE_FLAG;
let masked_n = n & mask;
let masked_seq = self.0 & mask;
if masked_n < SEQUENCE_LOCKTIME_TYPE_FLAG && masked_seq >= SEQUENCE_LOCKTIME_TYPE_FLAG {
false
} else {
masked_n <= masked_seq
}
}
}
/// Newtype around `u32` which implements `Satisfier` using `n` as an
/// absolute locktime
pub struct After(pub u32);
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for After {
fn check_after(&self, n: u32) -> bool {
// if n > self.0; we will be returning false anyways
if n < HEIGHT_TIME_THRESHOLD && self.0 >= HEIGHT_TIME_THRESHOLD {
false
} else {
n <= self.0
}
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for HashMap<Pk, bitcoin::EcdsaSig> {
fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<bitcoin::EcdsaSig> {
self.get(key).copied()
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
for HashMap<(Pk, TapLeafHash), bitcoin::SchnorrSig>
{
fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option<bitcoin::SchnorrSig> {
// Unfortunately, there is no way to get a &(a, b) from &a and &b without allocating
// If we change the signature the of lookup_tap_leaf_script_sig to accept a tuple. We would
// face the same problem while satisfying PkK.
// We use this signature to optimize for the psbt common use case.
self.get(&(key.clone(), *h)).copied()
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for HashMap<Pk::Hash, (Pk, bitcoin::EcdsaSig)>
where
Pk: MiniscriptKey + ToPublicKey,
{
fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<bitcoin::EcdsaSig> {
self.get(&key.to_pubkeyhash()).map(|x| x.1)
}
fn lookup_pkh_pk(&self, pk_hash: &Pk::Hash) -> Option<Pk> {
self.get(pk_hash).map(|x| x.0.clone())
}
fn lookup_pkh_ecdsa_sig(
&self,
pk_hash: &Pk::Hash,
) -> Option<(bitcoin::PublicKey, bitcoin::EcdsaSig)> {
self.get(pk_hash)
.map(|&(ref pk, sig)| (pk.to_public_key(), sig))
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
for HashMap<(Pk::Hash, TapLeafHash), (Pk, bitcoin::SchnorrSig)>
where
Pk: MiniscriptKey + ToPublicKey,
{
fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option<bitcoin::SchnorrSig> {
self.get(&(key.to_pubkeyhash(), *h)).map(|x| x.1)
}
fn lookup_pkh_tap_leaf_script_sig(
&self,
pk_hash: &(Pk::Hash, TapLeafHash),
) -> Option<(XOnlyPublicKey, bitcoin::SchnorrSig)> {
self.get(pk_hash)
.map(|&(ref pk, sig)| (pk.to_x_only_pubkey(), sig))
}
}
impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &'a S {
fn lookup_ecdsa_sig(&self, p: &Pk) -> Option<bitcoin::EcdsaSig> {
(**self).lookup_ecdsa_sig(p)
}
fn lookup_tap_leaf_script_sig(&self, p: &Pk, h: &TapLeafHash) -> Option<bitcoin::SchnorrSig> {
(**self).lookup_tap_leaf_script_sig(p, h)
}
fn lookup_pkh_pk(&self, pkh: &Pk::Hash) -> Option<Pk> {
(**self).lookup_pkh_pk(pkh)
}
fn lookup_pkh_ecdsa_sig(
&self,
pkh: &Pk::Hash,
) -> Option<(bitcoin::PublicKey, bitcoin::EcdsaSig)> {
(**self).lookup_pkh_ecdsa_sig(pkh)
}
fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::SchnorrSig> {
(**self).lookup_tap_key_spend_sig()
}
fn lookup_pkh_tap_leaf_script_sig(
&self,
pkh: &(Pk::Hash, TapLeafHash),
) -> Option<(XOnlyPublicKey, bitcoin::SchnorrSig)> {
(**self).lookup_pkh_tap_leaf_script_sig(pkh)
}
fn lookup_tap_control_block_map(
&self,
) -> Option<&BTreeMap<ControlBlock, (bitcoin::Script, LeafVersion)>> {
(**self).lookup_tap_control_block_map()
}
fn lookup_sha256(&self, h: sha256::Hash) -> Option<Preimage32> {
(**self).lookup_sha256(h)
}
fn lookup_hash256(&self, h: sha256d::Hash) -> Option<Preimage32> {
(**self).lookup_hash256(h)
}
fn lookup_ripemd160(&self, h: ripemd160::Hash) -> Option<Preimage32> {
(**self).lookup_ripemd160(h)
}
fn lookup_hash160(&self, h: hash160::Hash) -> Option<Preimage32> {
(**self).lookup_hash160(h)
}
fn check_older(&self, t: u32) -> bool {
(**self).check_older(t)
}
fn check_after(&self, t: u32) -> bool {
(**self).check_after(t)
}
}
impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &'a mut S {
fn lookup_ecdsa_sig(&self, p: &Pk) -> Option<bitcoin::EcdsaSig> {
(**self).lookup_ecdsa_sig(p)
}
fn lookup_tap_leaf_script_sig(&self, p: &Pk, h: &TapLeafHash) -> Option<bitcoin::SchnorrSig> {
(**self).lookup_tap_leaf_script_sig(p, h)
}
fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::SchnorrSig> {
(**self).lookup_tap_key_spend_sig()
}
fn lookup_pkh_pk(&self, pkh: &Pk::Hash) -> Option<Pk> {
(**self).lookup_pkh_pk(pkh)
}
fn lookup_pkh_ecdsa_sig(
&self,
pkh: &Pk::Hash,
) -> Option<(bitcoin::PublicKey, bitcoin::EcdsaSig)> {
(**self).lookup_pkh_ecdsa_sig(pkh)
}
fn lookup_pkh_tap_leaf_script_sig(
&self,
pkh: &(Pk::Hash, TapLeafHash),
) -> Option<(XOnlyPublicKey, bitcoin::SchnorrSig)> {
(**self).lookup_pkh_tap_leaf_script_sig(pkh)
}
fn lookup_tap_control_block_map(
&self,
) -> Option<&BTreeMap<ControlBlock, (bitcoin::Script, LeafVersion)>> {
(**self).lookup_tap_control_block_map()
}
fn lookup_sha256(&self, h: sha256::Hash) -> Option<Preimage32> {
(**self).lookup_sha256(h)
}
fn lookup_hash256(&self, h: sha256d::Hash) -> Option<Preimage32> {
(**self).lookup_hash256(h)
}
fn lookup_ripemd160(&self, h: ripemd160::Hash) -> Option<Preimage32> {
(**self).lookup_ripemd160(h)
}
fn lookup_hash160(&self, h: hash160::Hash) -> Option<Preimage32> {
(**self).lookup_hash160(h)
}
fn check_older(&self, t: u32) -> bool {
(**self).check_older(t)
}
fn check_after(&self, t: u32) -> bool {
(**self).check_after(t)
}
}
macro_rules! impl_tuple_satisfier {
($($ty:ident),*) => {
#[allow(non_snake_case)]
impl<$($ty,)* Pk> Satisfier<Pk> for ($($ty,)*)
where
Pk: MiniscriptKey + ToPublicKey,
$($ty: Satisfier< Pk>,)*
{
fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<bitcoin::EcdsaSig> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_ecdsa_sig(key) {
return Some(result);
}
)*
None
}
fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::SchnorrSig> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_tap_key_spend_sig() {
return Some(result);
}
)*
None
}
fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option<bitcoin::SchnorrSig> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_tap_leaf_script_sig(key, h) {
return Some(result);
}
)*
None
}
fn lookup_pkh_ecdsa_sig(
&self,
key_hash: &Pk::Hash,
) -> Option<(bitcoin::PublicKey, bitcoin::EcdsaSig)> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_pkh_ecdsa_sig(key_hash) {
return Some(result);
}
)*
None
}
fn lookup_pkh_tap_leaf_script_sig(
&self,
key_hash: &(Pk::Hash, TapLeafHash),
) -> Option<(XOnlyPublicKey, bitcoin::SchnorrSig)> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_pkh_tap_leaf_script_sig(key_hash) {
return Some(result);
}
)*
None
}
fn lookup_pkh_pk(
&self,
key_hash: &Pk::Hash,
) -> Option<Pk> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_pkh_pk(key_hash) {
return Some(result);
}
)*
None
}
fn lookup_tap_control_block_map(
&self,
) -> Option<&BTreeMap<ControlBlock, (bitcoin::Script, LeafVersion)>> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_tap_control_block_map() {
return Some(result);
}
)*
None
}
fn lookup_sha256(&self, h: sha256::Hash) -> Option<Preimage32> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_sha256(h) {
return Some(result);
}
)*
None
}
fn lookup_hash256(&self, h: sha256d::Hash) -> Option<Preimage32> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_hash256(h) {
return Some(result);
}
)*
None
}
fn lookup_ripemd160(&self, h: ripemd160::Hash) -> Option<Preimage32> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_ripemd160(h) {
return Some(result);
}
)*
None
}
fn lookup_hash160(&self, h: hash160::Hash) -> Option<Preimage32> {
let &($(ref $ty,)*) = self;
$(
if let Some(result) = $ty.lookup_hash160(h) {
return Some(result);
}
)*
None
}
fn check_older(&self, n: u32) -> bool {
let &($(ref $ty,)*) = self;
$(
if $ty.check_older(n) {
return true;
}
)*
false
}
fn check_after(&self, n: u32) -> bool {
let &($(ref $ty,)*) = self;
$(
if $ty.check_after(n) {
return true;
}
)*
false
}
}
}
}
impl_tuple_satisfier!(A);
impl_tuple_satisfier!(A, B);
impl_tuple_satisfier!(A, B, C);
impl_tuple_satisfier!(A, B, C, D);
impl_tuple_satisfier!(A, B, C, D, E);
impl_tuple_satisfier!(A, B, C, D, E, F);
impl_tuple_satisfier!(A, B, C, D, E, F, G);
impl_tuple_satisfier!(A, B, C, D, E, F, G, H);
/// A witness, if available, for a Miniscript fragment
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Witness {
/// Witness Available and the value of the witness
Stack(Vec<Vec<u8>>),
/// Third party can possibly satisfy the fragment but we cannot
/// Witness Unavailable
Unavailable,
/// No third party can produce a satisfaction without private key
/// Witness Impossible
Impossible,
}
impl PartialOrd for Witness {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Witness {
fn cmp(&self, other: &Self) -> cmp::Ordering {
match (self, other) {
(&Witness::Stack(ref v1), &Witness::Stack(ref v2)) => {
let w1 = witness_size(v1);
let w2 = witness_size(v2);
w1.cmp(&w2)
}
(&Witness::Stack(_), _) => cmp::Ordering::Less,
(_, &Witness::Stack(_)) => cmp::Ordering::Greater,
(&Witness::Impossible, &Witness::Unavailable) => cmp::Ordering::Less,
(&Witness::Unavailable, &Witness::Impossible) => cmp::Ordering::Greater,
(&Witness::Impossible, &Witness::Impossible) => cmp::Ordering::Equal,
(&Witness::Unavailable, &Witness::Unavailable) => cmp::Ordering::Equal,
}
}
}
impl Witness {
/// Turn a signature into (part of) a satisfaction
fn signature<Pk: ToPublicKey, S: Satisfier<Pk>, Ctx: ScriptContext>(
sat: S,
pk: &Pk,
leaf_hash: &TapLeafHash,
) -> Self {
match Ctx::sig_type() {
super::context::SigType::Ecdsa => match sat.lookup_ecdsa_sig(pk) {
Some(sig) => Witness::Stack(vec![sig.to_vec()]),
// Signatures cannot be forged
None => Witness::Impossible,
},
super::context::SigType::Schnorr => match sat.lookup_tap_leaf_script_sig(pk, leaf_hash)
{
Some(sig) => Witness::Stack(vec![sig.to_vec()]),
// Signatures cannot be forged
None => Witness::Impossible,
},
}
}
/// Turn a public key related to a pkh into (part of) a satisfaction
fn pkh_public_key<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, pkh: &Pk::Hash) -> Self {
match sat.lookup_pkh_pk(pkh) {
Some(pk) => Witness::Stack(vec![pk.to_public_key().to_bytes()]),
// public key hashes are assumed to be unavailable
// instead of impossible since it is the same as pub-key hashes
None => Witness::Unavailable,
}
}
/// Turn a key/signature pair related to a pkh into (part of) a satisfaction
fn pkh_signature<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, pkh: &Pk::Hash) -> Self {
match sat.lookup_pkh_ecdsa_sig(pkh) {
Some((pk, sig)) => Witness::Stack(vec![sig.to_vec(), pk.to_public_key().to_bytes()]),
None => Witness::Impossible,
}
}
/// Turn a hash preimage into (part of) a satisfaction
fn ripemd160_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: ripemd160::Hash) -> Self {
match sat.lookup_ripemd160(h) {
Some(pre) => Witness::Stack(vec![pre.to_vec()]),
// Note hash preimages are unavailable instead of impossible
None => Witness::Unavailable,
}
}
/// Turn a hash preimage into (part of) a satisfaction
fn hash160_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: hash160::Hash) -> Self {
match sat.lookup_hash160(h) {
Some(pre) => Witness::Stack(vec![pre.to_vec()]),
// Note hash preimages are unavailable instead of impossible
None => Witness::Unavailable,
}
}
/// Turn a hash preimage into (part of) a satisfaction
fn sha256_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: sha256::Hash) -> Self {
match sat.lookup_sha256(h) {
Some(pre) => Witness::Stack(vec![pre.to_vec()]),
// Note hash preimages are unavailable instead of impossible
None => Witness::Unavailable,
}
}
/// Turn a hash preimage into (part of) a satisfaction
fn hash256_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: sha256d::Hash) -> Self {
match sat.lookup_hash256(h) {
Some(pre) => Witness::Stack(vec![pre.to_vec()]),
// Note hash preimages are unavailable instead of impossible
None => Witness::Unavailable,
}
}
}
impl Witness {
/// Produce something like a 32-byte 0 push
fn hash_dissatisfaction() -> Self {
Witness::Stack(vec![vec![0; 32]])
}
/// Construct a satisfaction equivalent to an empty stack
fn empty() -> Self {
Witness::Stack(vec![])
}
/// Construct a satisfaction equivalent to `OP_1`
fn push_1() -> Self {
Witness::Stack(vec![vec![1]])
}
/// Construct a satisfaction equivalent to a single empty push
fn push_0() -> Self {
Witness::Stack(vec![vec![]])
}
/// Concatenate, or otherwise combine, two satisfactions
fn combine(one: Self, two: Self) -> Self {
match (one, two) {
(Witness::Impossible, _) | (_, Witness::Impossible) => Witness::Impossible,
(Witness::Unavailable, _) | (_, Witness::Unavailable) => Witness::Unavailable,
(Witness::Stack(mut a), Witness::Stack(b)) => {
a.extend(b);
Witness::Stack(a)
}
}
}
}
/// A (dis)satisfaction of a Miniscript fragment
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Satisfaction {
/// The actual witness stack
pub stack: Witness,
/// Whether or not this (dis)satisfaction has a signature somewhere
/// in it
pub has_sig: bool,
}
impl Satisfaction {
// produce a non-malleable satisafaction for thesh frag
fn thresh<Pk, Ctx, Sat, F>(
k: usize,
subs: &[Arc<Miniscript<Pk, Ctx>>],
stfr: &Sat,
root_has_sig: bool,
leaf_hash: &TapLeafHash,
min_fn: &mut F,
) -> Self
where
Pk: MiniscriptKey + ToPublicKey,
Ctx: ScriptContext,
Sat: Satisfier<Pk>,
F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
{
let mut sats = subs
.iter()
.map(|s| {
Self::satisfy_helper(
&s.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
&mut Self::thresh,
)
})
.collect::<Vec<_>>();
// Start with the to-return stack set to all dissatisfactions
let mut ret_stack = subs
.iter()
.map(|s| {
Self::dissatisfy_helper(
&s.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
&mut Self::thresh,
)
})
.collect::<Vec<_>>();
// Sort everything by (sat cost - dissat cost), except that
// satisfactions without signatures beat satisfactions with
// signatures
let mut sat_indices = (0..subs.len()).collect::<Vec<_>>();
sat_indices.sort_by_key(|&i| {
let stack_weight = match (&sats[i].stack, &ret_stack[i].stack) {
(&Witness::Unavailable, _) | (&Witness::Impossible, _) => i64::MAX,
// This can only be the case when we have PkH without the corresponding
// Pubkey.
(_, &Witness::Unavailable) | (_, &Witness::Impossible) => i64::MIN,
(&Witness::Stack(ref s), &Witness::Stack(ref d)) => {
witness_size(s) as i64 - witness_size(d) as i64
}
};
let is_impossible = sats[i].stack == Witness::Impossible;
// First consider the candidates that are not impossible to satisfy
// by any party. Among those first consider the ones that have no sig
// because third party can malleate them if they are not chosen.
// Lastly, choose by weight.
(is_impossible, sats[i].has_sig, stack_weight)
});
for i in 0..k {
mem::swap(&mut ret_stack[sat_indices[i]], &mut sats[sat_indices[i]]);
}
// We preferably take satisfactions that are not impossible
// If we cannot find `k` satisfactions that are not impossible
// then the threshold branch is impossible to satisfy
// For example, the fragment thresh(2, hash, 0, 0, 0)
// is has an impossible witness
assert!(k > 0);
if sats[sat_indices[k - 1]].stack == Witness::Impossible {
Satisfaction {
stack: Witness::Impossible,
// If the witness is impossible, we don't care about the
// has_sig flag
has_sig: false,
}
}
// We are now guaranteed that all elements in `k` satisfactions
// are not impossible(we sort by is_impossible bool).
// The above loop should have taken everything without a sig
// (since those were sorted higher than non-sigs). If there
// are remaining non-sig satisfactions this indicates a
// malleability vector
// For example, the fragment thresh(2, hash, hash, 0, 0)
// is uniquely satisfyiable because there is no satisfaction
// for the 0 fragment
else if k < sat_indices.len()
&& !sats[sat_indices[k]].has_sig
&& sats[sat_indices[k]].stack != Witness::Impossible
{
// All arguments should be `d`, so dissatisfactions have no
// signatures; and in this branch we assume too many weak
// arguments, so none of the satisfactions should have
// signatures either.
for sat in &ret_stack {
assert!(!sat.has_sig);
}
Satisfaction {
stack: Witness::Unavailable,
has_sig: false,
}
} else {
// Otherwise flatten everything out
Satisfaction {
has_sig: ret_stack.iter().any(|sat| sat.has_sig),
stack: ret_stack.into_iter().fold(Witness::empty(), |acc, next| {
Witness::combine(next.stack, acc)
}),
}
}
}
// produce a possily malleable satisafaction for thesh frag
fn thresh_mall<Pk, Ctx, Sat, F>(
k: usize,
subs: &[Arc<Miniscript<Pk, Ctx>>],
stfr: &Sat,
root_has_sig: bool,
leaf_hash: &TapLeafHash,
min_fn: &mut F,
) -> Self
where
Pk: MiniscriptKey + ToPublicKey,
Ctx: ScriptContext,
Sat: Satisfier<Pk>,
F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
{
let mut sats = subs
.iter()
.map(|s| {
Self::satisfy_helper(
&s.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
&mut Self::thresh_mall,
)
})
.collect::<Vec<_>>();
// Start with the to-return stack set to all dissatisfactions
let mut ret_stack = subs
.iter()
.map(|s| {
Self::dissatisfy_helper(
&s.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
&mut Self::thresh_mall,
)
})
.collect::<Vec<_>>();
// Sort everything by (sat cost - dissat cost), except that
// satisfactions without signatures beat satisfactions with
// signatures
let mut sat_indices = (0..subs.len()).collect::<Vec<_>>();
sat_indices.sort_by_key(|&i| {
// For malleable satifactions, directly choose smallest weights
match (&sats[i].stack, &ret_stack[i].stack) {
(&Witness::Unavailable, _) | (&Witness::Impossible, _) => i64::MAX,
// This is only possible when one of the branches has PkH
(_, &Witness::Unavailable) | (_, &Witness::Impossible) => i64::MIN,
(&Witness::Stack(ref s), &Witness::Stack(ref d)) => {
witness_size(s) as i64 - witness_size(d) as i64
}
}
});
// swap the satisfactions
for i in 0..k {
mem::swap(&mut ret_stack[sat_indices[i]], &mut sats[sat_indices[i]]);
}
// combine the witness
// no non-malleability checks needed
Satisfaction {
has_sig: ret_stack.iter().any(|sat| sat.has_sig),
stack: ret_stack.into_iter().fold(Witness::empty(), |acc, next| {
Witness::combine(next.stack, acc)
}),
}
}
fn minimum(sat1: Self, sat2: Self) -> Self {
// If there is only one available satisfaction, we must choose that
// regardless of has_sig marker.
// This handles the case where both are impossible.
match (&sat1.stack, &sat2.stack) {
(&Witness::Impossible, _) => return sat2,
(_, &Witness::Impossible) => return sat1,
_ => {}
}
match (sat1.has_sig, sat2.has_sig) {
// If neither option has a signature, this is a malleability
// vector, so choose neither one.
(false, false) => Satisfaction {
stack: Witness::Unavailable,
has_sig: false,
},
// If only one has a signature, take the one that doesn't; a
// third party could malleate by removing the signature, but
// can't malleate if he'd have to add it
(false, true) => Satisfaction {
stack: sat1.stack,
has_sig: false,
},
(true, false) => Satisfaction {
stack: sat2.stack,
has_sig: false,
},
// If both have a signature associated with them, choose the
// cheaper one (where "cheaper" is defined such that available
// things are cheaper than unavailable ones)
(true, true) => Satisfaction {
stack: cmp::min(sat1.stack, sat2.stack),
has_sig: true,
},
}
}
// calculate the minimum witness allowing witness malleability
fn minimum_mall(sat1: Self, sat2: Self) -> Self {
match (&sat1.stack, &sat2.stack) {
// If there is only one possible satisfaction, use it regardless
// of the other one
(&Witness::Impossible, _) | (&Witness::Unavailable, _) => return sat2,
(_, &Witness::Impossible) | (_, &Witness::Unavailable) => return sat1,
_ => {}
}
Satisfaction {
stack: cmp::min(sat1.stack, sat2.stack),
// The fragment is has_sig only if both of the
// fragments are has_sig
has_sig: sat1.has_sig && sat2.has_sig,
}
}
// produce a non-malleable satisfaction
fn satisfy_helper<Pk, Ctx, Sat, F, G>(
term: &Terminal<Pk, Ctx>,
stfr: &Sat,
root_has_sig: bool,
leaf_hash: &TapLeafHash,
min_fn: &mut F,
thresh_fn: &mut G,
) -> Self
where
Pk: MiniscriptKey + ToPublicKey,
Ctx: ScriptContext,
Sat: Satisfier<Pk>,
F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
G: FnMut(
usize,
&[Arc<Miniscript<Pk, Ctx>>],
&Sat,
bool,
&TapLeafHash,
&mut F,
) -> Satisfaction,
{
match *term {
Terminal::PkK(ref pk) => Satisfaction {
stack: Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash),
has_sig: true,
},
Terminal::PkH(ref pkh) => Satisfaction {
stack: Witness::pkh_signature(stfr, pkh),
has_sig: true,
},
Terminal::After(t) => Satisfaction {
stack: if stfr.check_after(t) {
Witness::empty()
} else if root_has_sig {
// If the root terminal has signature, the
// signature covers the nLockTime and nSequence
// values. The sender of the transaction should
// take care that it signs the value such that the
// timelock is not met
Witness::Impossible
} else {
Witness::Unavailable
},
has_sig: false,
},
Terminal::Older(t) => Satisfaction {
stack: if stfr.check_older(t) {
Witness::empty()
} else if root_has_sig {
// If the root terminal has signature, the
// signature covers the nLockTime and nSequence
// values. The sender of the transaction should
// take care that it signs the value such that the
// timelock is not met
Witness::Impossible
} else {
Witness::Unavailable
},
has_sig: false,
},
Terminal::Ripemd160(h) => Satisfaction {
stack: Witness::ripemd160_preimage(stfr, h),
has_sig: false,
},
Terminal::Hash160(h) => Satisfaction {
stack: Witness::hash160_preimage(stfr, h),
has_sig: false,
},
Terminal::Sha256(h) => Satisfaction {
stack: Witness::sha256_preimage(stfr, h),
has_sig: false,
},
Terminal::Hash256(h) => Satisfaction {
stack: Witness::hash256_preimage(stfr, h),
has_sig: false,
},
Terminal::True => Satisfaction {
stack: Witness::empty(),
has_sig: false,
},
Terminal::False => Satisfaction {
stack: Witness::Impossible,
has_sig: false,
},
Terminal::Alt(ref sub)
| Terminal::Swap(ref sub)
| Terminal::Check(ref sub)
| Terminal::Verify(ref sub)
| Terminal::NonZero(ref sub)
| Terminal::ZeroNotEqual(ref sub) => {
Self::satisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn)
}
Terminal::DupIf(ref sub) => {
let sat = Self::satisfy_helper(
&sub.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
Satisfaction {
stack: Witness::combine(sat.stack, Witness::push_1()),
has_sig: sat.has_sig,
}
}
Terminal::AndV(ref l, ref r) | Terminal::AndB(ref l, ref r) => {
let l_sat =
Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let r_sat =
Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
Satisfaction {
stack: Witness::combine(r_sat.stack, l_sat.stack),
has_sig: l_sat.has_sig || r_sat.has_sig,
}
}
Terminal::AndOr(ref a, ref b, ref c) => {
let a_sat =
Self::satisfy_helper(&a.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let a_nsat = Self::dissatisfy_helper(
&a.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
let b_sat =
Self::satisfy_helper(&b.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let c_sat =
Self::satisfy_helper(&c.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
min_fn(
Satisfaction {
stack: Witness::combine(b_sat.stack, a_sat.stack),
has_sig: a_sat.has_sig || b_sat.has_sig,
},
Satisfaction {
stack: Witness::combine(c_sat.stack, a_nsat.stack),
has_sig: a_nsat.has_sig || c_sat.has_sig,
},
)
}
Terminal::OrB(ref l, ref r) => {
let l_sat =
Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let r_sat =
Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let l_nsat = Self::dissatisfy_helper(
&l.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
let r_nsat = Self::dissatisfy_helper(
&r.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
assert!(!l_nsat.has_sig);
assert!(!r_nsat.has_sig);
min_fn(
Satisfaction {
stack: Witness::combine(r_sat.stack, l_nsat.stack),
has_sig: r_sat.has_sig,
},
Satisfaction {
stack: Witness::combine(r_nsat.stack, l_sat.stack),
has_sig: l_sat.has_sig,
},
)
}
Terminal::OrD(ref l, ref r) | Terminal::OrC(ref l, ref r) => {
let l_sat =
Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let r_sat =
Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let l_nsat = Self::dissatisfy_helper(
&l.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
assert!(!l_nsat.has_sig);
min_fn(
l_sat,
Satisfaction {
stack: Witness::combine(r_sat.stack, l_nsat.stack),
has_sig: r_sat.has_sig,
},
)
}
Terminal::OrI(ref l, ref r) => {
let l_sat =
Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let r_sat =
Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
min_fn(
Satisfaction {
stack: Witness::combine(l_sat.stack, Witness::push_1()),
has_sig: l_sat.has_sig,
},
Satisfaction {
stack: Witness::combine(r_sat.stack, Witness::push_0()),
has_sig: r_sat.has_sig,
},
)
}
Terminal::Thresh(k, ref subs) => {
thresh_fn(k, subs, stfr, root_has_sig, leaf_hash, min_fn)
}
Terminal::Multi(k, ref keys) => {
// Collect all available signatures
let mut sig_count = 0;
let mut sigs = Vec::with_capacity(k);
for pk in keys {
match Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash) {
Witness::Stack(sig) => {
sigs.push(sig);
sig_count += 1;
}
Witness::Impossible => {}
Witness::Unavailable => unreachable!(
"Signature satisfaction without witness must be impossible"
),
}
}
if sig_count < k {
Satisfaction {
stack: Witness::Impossible,
has_sig: false,
}
} else {
// Throw away the most expensive ones
for _ in 0..sig_count - k {
let max_idx = sigs
.iter()
.enumerate()
.max_by_key(|&(_, v)| v.len())
.unwrap()
.0;
sigs[max_idx] = vec![];
}
Satisfaction {
stack: sigs.into_iter().fold(Witness::push_0(), |acc, sig| {
Witness::combine(acc, Witness::Stack(sig))
}),
has_sig: true,
}
}
}
Terminal::MultiA(k, ref keys) => {
// Collect all available signatures
let mut sig_count = 0;
let mut sigs = vec![vec![vec![]]; keys.len()];
for (i, pk) in keys.iter().rev().enumerate() {
match Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash) {
Witness::Stack(sig) => {
sigs[i] = sig;
sig_count += 1;
// This a privacy issue, we are only selecting the first available
// sigs. Incase pk at pos 1 is not selected, we know we did not have access to it
// bitcoin core also implements the same logic for MULTISIG, so I am not bothering
// permuting the sigs for now
if sig_count == k {
break;
}
}
Witness::Impossible => {}
Witness::Unavailable => unreachable!(
"Signature satisfaction without witness must be impossible"
),
}
}
if sig_count < k {
Satisfaction {
stack: Witness::Impossible,
has_sig: false,
}
} else {
Satisfaction {
stack: sigs.into_iter().fold(Witness::empty(), |acc, sig| {
Witness::combine(acc, Witness::Stack(sig))
}),
has_sig: true,
}
}
}
}
}
// Helper function to produce a dissatisfaction
fn dissatisfy_helper<Pk, Ctx, Sat, F, G>(
term: &Terminal<Pk, Ctx>,
stfr: &Sat,
root_has_sig: bool,
leaf_hash: &TapLeafHash,
min_fn: &mut F,
thresh_fn: &mut G,
) -> Self
where
Pk: MiniscriptKey + ToPublicKey,
Ctx: ScriptContext,
Sat: Satisfier<Pk>,
F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
G: FnMut(
usize,
&[Arc<Miniscript<Pk, Ctx>>],
&Sat,
bool,
&TapLeafHash,
&mut F,
) -> Satisfaction,
{
match *term {
Terminal::PkK(..) => Satisfaction {
stack: Witness::push_0(),
has_sig: false,
},
Terminal::PkH(ref pkh) => Satisfaction {
stack: Witness::combine(Witness::push_0(), Witness::pkh_public_key(stfr, pkh)),
has_sig: false,
},
Terminal::False => Satisfaction {
stack: Witness::empty(),
has_sig: false,
},
Terminal::True => Satisfaction {
stack: Witness::Impossible,
has_sig: false,
},
Terminal::Older(_) => Satisfaction {
stack: Witness::Impossible,
has_sig: false,
},
Terminal::After(_) => Satisfaction {
stack: Witness::Impossible,
has_sig: false,
},
Terminal::Sha256(_)
| Terminal::Hash256(_)
| Terminal::Ripemd160(_)
| Terminal::Hash160(_) => Satisfaction {
stack: Witness::hash_dissatisfaction(),
has_sig: false,
},
Terminal::Alt(ref sub)
| Terminal::Swap(ref sub)
| Terminal::Check(ref sub)
| Terminal::ZeroNotEqual(ref sub) => {
Self::dissatisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn)
}
Terminal::DupIf(_) | Terminal::NonZero(_) => Satisfaction {
stack: Witness::push_0(),
has_sig: false,
},
Terminal::Verify(_) => Satisfaction {
stack: Witness::Impossible,
has_sig: false,
},
Terminal::AndV(ref v, ref other) => {
let vsat =
Self::satisfy_helper(&v.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
let odissat = Self::dissatisfy_helper(
&other.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
Satisfaction {
stack: Witness::combine(odissat.stack, vsat.stack),
has_sig: vsat.has_sig || odissat.has_sig,
}
}
Terminal::AndB(ref l, ref r)
| Terminal::OrB(ref l, ref r)
| Terminal::OrD(ref l, ref r)
| Terminal::AndOr(ref l, _, ref r) => {
let lnsat = Self::dissatisfy_helper(
&l.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
let rnsat = Self::dissatisfy_helper(
&r.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
Satisfaction {
stack: Witness::combine(rnsat.stack, lnsat.stack),
has_sig: rnsat.has_sig || lnsat.has_sig,
}
}
Terminal::OrC(..) => Satisfaction {
stack: Witness::Impossible,
has_sig: false,
},
Terminal::OrI(ref l, ref r) => {
let lnsat = Self::dissatisfy_helper(
&l.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
let dissat_1 = Satisfaction {
stack: Witness::combine(lnsat.stack, Witness::push_1()),
has_sig: lnsat.has_sig,
};
let rnsat = Self::dissatisfy_helper(
&r.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
let dissat_2 = Satisfaction {
stack: Witness::combine(rnsat.stack, Witness::push_0()),
has_sig: rnsat.has_sig,
};
// Dissatisfactions don't need to non-malleable. Use minimum_mall always
Satisfaction::minimum_mall(dissat_1, dissat_2)
}
Terminal::Thresh(_, ref subs) => Satisfaction {
stack: subs.iter().fold(Witness::empty(), |acc, sub| {
let nsat = Self::dissatisfy_helper(
&sub.node,
stfr,
root_has_sig,
leaf_hash,
min_fn,
thresh_fn,
);
assert!(!nsat.has_sig);
Witness::combine(nsat.stack, acc)
}),
has_sig: false,
},
Terminal::Multi(k, _) => Satisfaction {
stack: Witness::Stack(vec![vec![]; k + 1]),
has_sig: false,
},
Terminal::MultiA(_, ref pks) => Satisfaction {
stack: Witness::Stack(vec![vec![]; pks.len()]),
has_sig: false,
},
}
}
/// Produce a satisfaction non-malleable satisfaction
pub(super) fn satisfy<
Pk: MiniscriptKey + ToPublicKey,
Ctx: ScriptContext,
Sat: Satisfier<Pk>,
>(
term: &Terminal<Pk, Ctx>,
stfr: &Sat,
root_has_sig: bool,
leaf_hash: &TapLeafHash,
) -> Self {
Self::satisfy_helper(
term,
stfr,
root_has_sig,
leaf_hash,
&mut Satisfaction::minimum,
&mut Satisfaction::thresh,
)
}
/// Produce a satisfaction(possibly malleable)
pub(super) fn satisfy_mall<
Pk: MiniscriptKey + ToPublicKey,
Ctx: ScriptContext,
Sat: Satisfier<Pk>,
>(
term: &Terminal<Pk, Ctx>,
stfr: &Sat,
root_has_sig: bool,
leaf_hash: &TapLeafHash,
) -> Self {
Self::satisfy_helper(
term,
stfr,
root_has_sig,
leaf_hash,
&mut Satisfaction::minimum_mall,
&mut Satisfaction::thresh_mall,
)
}
}
| 35.494068 | 110 | 0.493699 |
08fcc97083e16039fa6e24f6129aa36cbe437fbf
| 2,894 |
#![ allow (unused_imports) ]
#![ allow (unused_import_braces) ]
pub(crate) use crate::accepter::*;
pub(crate) use crate::cli::*;
pub(crate) use crate::configuration::*;
pub(crate) use crate::connection::*;
pub(crate) use crate::errors::*;
pub(crate) use crate::exports::*;
pub(crate) use crate::handler::*;
pub(crate) use crate::server::*;
pub(crate) use crate::sanitize::*;
pub(crate) use crate::routes::*;
pub(crate) use crate::profiling::*;
pub(crate) use ::std::*;
pub(crate) use ::std::prelude::v1::*;
pub(crate) use ::std::convert::From;
pub(crate) use ::std::convert::Into;
pub(crate) use ::std::convert::TryInto;
pub(crate) use ::std::convert::TryFrom;
pub(crate) use ::std::error::Error;
pub(crate) use ::std::future::Future;
#[ cfg (feature = "futures") ]
pub(crate) use ::futures::FutureExt as _;
#[ cfg (feature = "futures") ]
pub(crate) use ::futures::TryFutureExt as _;
pub(crate) use ::std::marker::PhantomData;
pub(crate) use ::std::ops::Deref;
pub(crate) use ::std::pin::Pin;
pub(crate) use ::std::sync::Arc;
pub(crate) use ::std::sync::RwLock;
pub(crate) use ::std::task::Poll;
pub(crate) use ::std::task::Context;
pub(crate) mod futures {
#[ cfg (feature = "futures") ]
pub(crate) use ::futures::{
FutureExt,
TryFutureExt,
ready,
};
}
pub(crate) mod hyper {
#[ cfg (feature = "hyper") ]
pub(crate) use ::hyper::{
service::Service,
service::service_fn,
service::make_service_fn,
};
#[ cfg (feature = "hyper--server-http") ]
pub(crate) use ::hyper::{
server::conn::Http,
server::Builder,
rt::Executor,
};
#[ cfg (feature = "hyper--server") ]
pub(crate) use ::hyper::{
server::accept::Accept,
};
}
pub(crate) mod tokio {
#[ cfg (feature = "tokio--net") ]
pub(crate) use ::tokio::io::{
AsyncWrite,
AsyncRead,
ReadBuf,
};
#[ cfg (feature = "tokio--net") ]
pub(crate) use ::tokio::net::{
TcpListener,
TcpStream,
};
#[ cfg (feature = "tokio--rt") ]
pub(crate) use ::tokio::runtime::{
Runtime,
Builder as RuntimeBuilder,
};
#[ cfg (feature = "tokio--rt") ]
pub(crate) use ::tokio::task::{
spawn,
};
#[ cfg (feature = "tokio--rt") ]
pub(crate) use ::tokio::signal::{
ctrl_c,
};
}
#[ cfg (feature = "http") ]
pub(crate) use ::http;
#[ cfg (feature = "http-body") ]
pub(crate) use ::http_body;
#[ cfg (feature = "bytes") ]
pub(crate) use ::bytes;
#[ cfg (feature = "rustls") ]
pub(crate) use ::rustls;
#[ cfg (feature = "tokio-rustls") ]
pub(crate) use ::tokio_rustls as tokio_rustls;
#[ cfg (feature = "rustls-pemfile") ]
pub(crate) use ::rustls_pemfile as rustls_pem;
#[ cfg (feature = "native-tls") ]
pub(crate) use ::native_tls as natls;
#[ cfg (feature = "tokio-native-tls") ]
pub(crate) use ::tokio_native_tls as tokio_natls;
#[ cfg (feature = "path-tree") ]
pub(crate) use ::path_tree;
#[ cfg (feature = "argparse") ]
pub(crate) use ::argparse;
| 19.821918 | 49 | 0.62094 |
ef3c4b546c621ce54826b3c3e5010c882a54a7da
| 4,723 |
use crate::utils::{match_qpath, paths, snippet, snippet_with_macro_callsite, span_lint_and_sugg};
use if_chain::if_chain;
use rustc::declare_lint_pass;
use rustc::hir::*;
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintPass};
use rustc::ty::Ty;
use rustc_errors::Applicability;
use rustc_session::declare_tool_lint;
declare_clippy_lint! {
/// **What it does:** Checks for usages of `Err(x)?`.
///
/// **Why is this bad?** The `?` operator is designed to allow calls that
/// can fail to be easily chained. For example, `foo()?.bar()` or
/// `foo(bar()?)`. Because `Err(x)?` can't be used that way (it will
/// always return), it is more clear to write `return Err(x)`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// fn foo(fail: bool) -> Result<i32, String> {
/// if fail {
/// Err("failed")?;
/// }
/// Ok(0)
/// }
/// ```
/// Could be written:
///
/// ```rust
/// fn foo(fail: bool) -> Result<i32, String> {
/// if fail {
/// return Err("failed".into());
/// }
/// Ok(0)
/// }
/// ```
pub TRY_ERR,
style,
"return errors explicitly rather than hiding them behind a `?`"
}
declare_lint_pass!(TryErr => [TRY_ERR]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TryErr {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
// Looks for a structure like this:
// match ::std::ops::Try::into_result(Err(5)) {
// ::std::result::Result::Err(err) =>
// #[allow(unreachable_code)]
// return ::std::ops::Try::from_error(::std::convert::From::from(err)),
// ::std::result::Result::Ok(val) =>
// #[allow(unreachable_code)]
// val,
// };
if_chain! {
if !in_external_macro(cx.tcx.sess, expr.span);
if let ExprKind::Match(ref match_arg, _, MatchSource::TryDesugar) = expr.kind;
if let ExprKind::Call(ref match_fun, ref try_args) = match_arg.kind;
if let ExprKind::Path(ref match_fun_path) = match_fun.kind;
if match_qpath(match_fun_path, &paths::TRY_INTO_RESULT);
if let Some(ref try_arg) = try_args.get(0);
if let ExprKind::Call(ref err_fun, ref err_args) = try_arg.kind;
if let Some(ref err_arg) = err_args.get(0);
if let ExprKind::Path(ref err_fun_path) = err_fun.kind;
if match_qpath(err_fun_path, &paths::RESULT_ERR);
if let Some(return_type) = find_err_return_type(cx, &expr.kind);
then {
let err_type = cx.tables.expr_ty(err_arg);
let origin_snippet = if err_arg.span.from_expansion() {
snippet_with_macro_callsite(cx, err_arg.span, "_")
} else {
snippet(cx, err_arg.span, "_")
};
let suggestion = if err_type == return_type {
format!("return Err({})", origin_snippet)
} else {
format!("return Err({}.into())", origin_snippet)
};
span_lint_and_sugg(
cx,
TRY_ERR,
expr.span,
"returning an `Err(_)` with the `?` operator",
"try this",
suggestion,
Applicability::MachineApplicable
);
}
}
}
}
// In order to determine whether to suggest `.into()` or not, we need to find the error type the
// function returns. To do that, we look for the From::from call (see tree above), and capture
// its output type.
fn find_err_return_type<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx ExprKind<'_>) -> Option<Ty<'tcx>> {
if let ExprKind::Match(_, ref arms, MatchSource::TryDesugar) = expr {
arms.iter().find_map(|ty| find_err_return_type_arm(cx, ty))
} else {
None
}
}
// Check for From::from in one of the match arms.
fn find_err_return_type_arm<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arm: &'tcx Arm<'_>) -> Option<Ty<'tcx>> {
if_chain! {
if let ExprKind::Ret(Some(ref err_ret)) = arm.body.kind;
if let ExprKind::Call(ref from_error_path, ref from_error_args) = err_ret.kind;
if let ExprKind::Path(ref from_error_fn) = from_error_path.kind;
if match_qpath(from_error_fn, &paths::TRY_FROM_ERROR);
if let Some(from_error_arg) = from_error_args.get(0);
then {
Some(cx.tables.expr_ty(from_error_arg))
} else {
None
}
}
}
| 38.398374 | 109 | 0.548804 |
d7f5540b6ce7e4ff83be24224694ab0025f279d8
| 880 |
//! The user_details module provides all user retrieval related functionality that is required for the authentication process.
use downcast_rs::impl_downcast;
use downcast_rs::Downcast;
pub mod attachment;
pub mod request_extension;
/// Marker trait for a user object to put into the request context.
pub trait UserDetails: Downcast + UserDetailsClone {}
impl_downcast!(UserDetails);
/// A user details object must be cloneable.
/// Therefore it has to implement the `UserDetailsClone` trait to be cloneable as a boxed object.
pub trait UserDetailsClone {
fn clone_box(&self) -> Box<dyn UserDetails>;
}
impl<U> UserDetailsClone for U
where
U: 'static + UserDetails + Clone,
{
fn clone_box(&self) -> Box<dyn UserDetails> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn UserDetails> {
fn clone(&self) -> Self {
self.clone_box()
}
}
| 26.666667 | 126 | 0.720455 |
f40314e102484ebdb1243563f7bfcdf2eac8eefe
| 475 |
#![allow(clippy::module_inception)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::large_enum_variant)]
#![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "package-2019-09-16-preview")]
pub mod package_2019_09_16_preview;
#[cfg(all(feature = "package-2019-09-16-preview", not(feature = "no-default-version")))]
pub use package_2019_09_16_preview::{models, operations, operations::Client, operations::ClientBuilder, operations::Error};
| 47.5 | 123 | 0.747368 |
89ca2d0c9e9c07a127ff1c69182ef7d816ab12c5
| 6,676 |
#[doc = "Register `RAMn1` reader"]
pub struct R(crate::R<RAMN1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<RAMN1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<RAMN1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<RAMN1_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `RAMn1` writer"]
pub struct W(crate::W<RAMN1_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<RAMN1_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<RAMN1_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<RAMN1_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `DATA_BYTE_3` reader - Data byte 3 of Rx/Tx frame."]
pub struct DATA_BYTE_3_R(crate::FieldReader<u8, u8>);
impl DATA_BYTE_3_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
DATA_BYTE_3_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DATA_BYTE_3_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DATA_BYTE_3` writer - Data byte 3 of Rx/Tx frame."]
pub struct DATA_BYTE_3_W<'a> {
w: &'a mut W,
}
impl<'a> DATA_BYTE_3_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) | (value as u32 & 0xff);
self.w
}
}
#[doc = "Field `DATA_BYTE_2` reader - Data byte 2 of Rx/Tx frame."]
pub struct DATA_BYTE_2_R(crate::FieldReader<u8, u8>);
impl DATA_BYTE_2_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
DATA_BYTE_2_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DATA_BYTE_2_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DATA_BYTE_2` writer - Data byte 2 of Rx/Tx frame."]
pub struct DATA_BYTE_2_W<'a> {
w: &'a mut W,
}
impl<'a> DATA_BYTE_2_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 << 8)) | ((value as u32 & 0xff) << 8);
self.w
}
}
#[doc = "Field `DATA_BYTE_1` reader - Data byte 1 of Rx/Tx frame."]
pub struct DATA_BYTE_1_R(crate::FieldReader<u8, u8>);
impl DATA_BYTE_1_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
DATA_BYTE_1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DATA_BYTE_1_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DATA_BYTE_1` writer - Data byte 1 of Rx/Tx frame."]
pub struct DATA_BYTE_1_W<'a> {
w: &'a mut W,
}
impl<'a> DATA_BYTE_1_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 `DATA_BYTE_0` reader - Data byte 0 of Rx/Tx frame."]
pub struct DATA_BYTE_0_R(crate::FieldReader<u8, u8>);
impl DATA_BYTE_0_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
DATA_BYTE_0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DATA_BYTE_0_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DATA_BYTE_0` writer - Data byte 0 of Rx/Tx frame."]
pub struct DATA_BYTE_0_W<'a> {
w: &'a mut W,
}
impl<'a> DATA_BYTE_0_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 << 24)) | ((value as u32 & 0xff) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Data byte 3 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_3(&self) -> DATA_BYTE_3_R {
DATA_BYTE_3_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - Data byte 2 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_2(&self) -> DATA_BYTE_2_R {
DATA_BYTE_2_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - Data byte 1 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_1(&self) -> DATA_BYTE_1_R {
DATA_BYTE_1_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - Data byte 0 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_0(&self) -> DATA_BYTE_0_R {
DATA_BYTE_0_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Data byte 3 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_3(&mut self) -> DATA_BYTE_3_W {
DATA_BYTE_3_W { w: self }
}
#[doc = "Bits 8:15 - Data byte 2 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_2(&mut self) -> DATA_BYTE_2_W {
DATA_BYTE_2_W { w: self }
}
#[doc = "Bits 16:23 - Data byte 1 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_1(&mut self) -> DATA_BYTE_1_W {
DATA_BYTE_1_W { w: self }
}
#[doc = "Bits 24:31 - Data byte 0 of Rx/Tx frame."]
#[inline(always)]
pub fn data_byte_0(&mut self) -> DATA_BYTE_0_W {
DATA_BYTE_0_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 = "Embedded RAM\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 [ramn1](index.html) module"]
pub struct RAMN1_SPEC;
impl crate::RegisterSpec for RAMN1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ramn1::R](R) reader structure"]
impl crate::Readable for RAMN1_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [ramn1::W](W) writer structure"]
impl crate::Writable for RAMN1_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets RAMn1 to value 0"]
impl crate::Resettable for RAMN1_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 31.051163 | 398 | 0.591522 |
0839fa3658cdc1ecd5313c356384d8a557edf835
| 22,163 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 crate::utils::*;
use std::convert::TryFrom;
use std::prelude::v1::*;
use teaclave_proto::teaclave_management_service::*;
use teaclave_proto::teaclave_scheduler_service::*;
use teaclave_test_utils::test_case;
use teaclave_types::*;
use url::Url;
fn authorized_client(user_id: &str) -> TeaclaveManagementClient {
get_management_client(user_id)
}
#[test_case]
fn test_register_input_file() {
let url = Url::parse("https://external-storage.com/filepath?presigned_token").unwrap();
let cmac = FileAuthTag::mock();
let request = RegisterInputFileRequest::new(url, cmac, FileCrypto::default());
let response = authorized_client("mock_user").register_input_file(request);
assert!(response.is_ok());
}
#[test_case]
fn test_register_output_file() {
let url = Url::parse("https://external-storage.com/filepath?presigned_token").unwrap();
let crypto_info = FileCrypto::new("aes-gcm-128", &[0x90u8; 16], &[0x89u8; 12]).unwrap();
let request = RegisterOutputFileRequest::new(url, crypto_info);
let response = authorized_client("mock_user").register_output_file(request);
assert!(response.is_ok());
}
#[test_case]
fn test_register_fusion_output() {
let request = RegisterFusionOutputRequest::new(vec!["mock_user", "mock_user_b"]);
let response = authorized_client("mock_user").register_fusion_output(request);
assert!(response.is_ok());
let request = RegisterFusionOutputRequest::new(vec!["mock_user_c", "mock_user_b"]);
let response = authorized_client("mock_user").register_fusion_output(request);
assert!(response.is_err());
}
#[test_case]
fn test_register_input_from_output() {
let user1_output_id =
ExternalID::try_from("output-00000000-0000-0000-0000-000000000001").unwrap();
// not a owner
let request = RegisterInputFromOutputRequest::new(user1_output_id.clone());
let response = authorized_client("mock_user_c").register_input_from_output(request);
assert!(response.is_err());
// output not ready
let url = Url::parse("https://external-storage.com/filepath?presigned_token").unwrap();
let crypto_info = FileCrypto::default();
let mut client = authorized_client("mock_user1");
let request = RegisterOutputFileRequest::new(url, crypto_info);
let response = client.register_output_file(request).unwrap();
let request = RegisterInputFromOutputRequest::new(response.data_id);
let response = client.register_input_from_output(request);
assert!(response.is_err());
let request = RegisterInputFromOutputRequest::new(user1_output_id);
let response = client.register_input_from_output(request);
assert!(response.is_ok());
}
#[test_case]
fn test_get_output_file() {
let url = Url::parse("https://external-storage.com/filepath?presigned_token").unwrap();
let crypto_info = FileCrypto::default();
let request = RegisterOutputFileRequest::new(url, crypto_info);
let mut client = authorized_client("mock_user");
let response = client.register_output_file(request).unwrap();
let data_id = response.data_id;
let request = GetOutputFileRequest::new(data_id.clone());
let response = client.get_output_file(request);
assert!(response.is_ok());
let request = GetOutputFileRequest::new(data_id);
let response = authorized_client("mock_another_user").get_output_file(request);
assert!(response.is_err());
}
#[test_case]
fn test_get_input_file() {
let url = Url::parse("https://external-storage.com/filepath?presigned_token").unwrap();
let cmac = FileAuthTag::mock();
let crypto_info = FileCrypto::default();
let mut client = authorized_client("mock_user");
let request = RegisterInputFileRequest::new(url, cmac, crypto_info);
let response = client.register_input_file(request).unwrap();
let data_id = response.data_id;
let request = GetInputFileRequest::new(data_id.clone());
let response = client.get_input_file(request);
assert!(response.is_ok());
let mut client = authorized_client("mock_another_user");
let request = GetInputFileRequest::new(data_id);
let response = client.get_input_file(request);
assert!(response.is_err());
}
#[test_case]
fn test_register_function() {
let function_input = FunctionInput::new("input", "input_desc");
let function_output = FunctionOutput::new("output", "output_desc");
let request = RegisterFunctionRequestBuilder::new()
.name("mock_function")
.executor_type(ExecutorType::Python)
.payload(b"def entrypoint:\n\treturn".to_vec())
.public(true)
.arguments(vec!["arg"])
.inputs(vec![function_input])
.outputs(vec![function_output])
.build();
let mut client = authorized_client("mock_user");
let response = client.register_function(request);
assert!(response.is_ok());
}
#[test_case]
fn test_get_function() {
let function_input = FunctionInput::new("input", "input_desc");
let function_output = FunctionOutput::new("output", "output_desc");
let request = RegisterFunctionRequestBuilder::new()
.name("mock_function")
.executor_type(ExecutorType::Python)
.payload(b"def entrypoint:\n\treturn".to_vec())
.public(false)
.arguments(vec!["arg"])
.inputs(vec![function_input])
.outputs(vec![function_output])
.build();
let mut client = authorized_client("mock_user");
let response = client.register_function(request).unwrap();
let function_id = response.function_id;
let request = GetFunctionRequest::new(function_id.clone());
let response = client.get_function(request);
assert!(response.is_ok());
let mut client = authorized_client("mock_unauthorized_user");
let request = GetFunctionRequest::new(function_id);
let response = client.get_function(request);
assert!(response.is_err());
let function_id =
ExternalID::try_from("function-00000000-0000-0000-0000-000000000001").unwrap();
let request = GetFunctionRequest::new(function_id);
let response = client.get_function(request);
assert!(response.is_ok());
}
fn create_valid_task_request() -> CreateTaskRequest {
let function_id =
ExternalID::try_from("function-00000000-0000-0000-0000-000000000001").unwrap();
let input_owners = hashmap!(
"input" => vec!["mock_user1"],
"input2" => vec!["mock_user2", "mock_user3"]
);
let output_owners = hashmap!(
"output" => vec!["mock_user1"],
"output2" => vec!["mock_user2", "mock_user3"]
);
CreateTaskRequest::new()
.function_id(function_id)
.function_arguments(hashmap!("arg1" => "data1", "arg2" => "data2"))
.executor(Executor::MesaPy)
.inputs_ownership(input_owners)
.outputs_ownership(output_owners)
}
#[test_case]
fn test_create_task() {
let mut client = authorized_client("mock_user");
let request = CreateTaskRequest::new().executor(Executor::MesaPy);
let response = client.create_task(request);
assert!(response.is_err());
let request = create_valid_task_request();
let response = client.create_task(request);
assert!(response.is_ok());
let mut request = create_valid_task_request();
request.function_arguments.inner_mut().remove("arg1");
let response = client.create_task(request);
assert!(response.is_err());
let mut request = create_valid_task_request();
request = request.inputs_ownership(hashmap!(
"input2" => vec!["mock_user2", "mock_user3"]
));
let response = client.create_task(request);
assert!(response.is_err());
let mut request = create_valid_task_request();
request = request.outputs_ownership(hashmap!(
"output2" => vec!["mock_user2", "mock_user3"]
));
let response = client.create_task(request);
assert!(response.is_err());
}
#[test_case]
fn test_get_task() {
let mut client = authorized_client("mock_user");
let request = create_valid_task_request();
let response = client.create_task(request).unwrap();
let task_id = response.task_id;
let request = GetTaskRequest::new(task_id);
let response = client.get_task(request).unwrap();
assert!(response.participants.len() == 4);
let participants = vec!["mock_user1", "mock_user3", "mock_user2", "mock_user"];
for name in participants {
assert!(response.participants.contains(&UserID::from(name)));
}
}
#[test_case]
fn test_assign_data() {
let mut client = authorized_client("mock_user");
let mut client1 = authorized_client("mock_user1");
let mut client2 = authorized_client("mock_user2");
let mut client3 = authorized_client("mock_user3");
let request = create_valid_task_request();
let response = client.create_task(request).unwrap();
let task_id = response.task_id;
// not a participant
let request = AssignDataRequest::new(task_id.clone(), hashmap!(), hashmap!());
let mut unknown_client = authorized_client("non-participant");
let response = unknown_client.assign_data(request);
assert!(response.is_err());
// !input_file.owner.contains(user_id)
let url = Url::parse("https://path").unwrap();
let cmac = FileAuthTag::mock();
let request = RegisterInputFileRequest::new(url, cmac, FileCrypto::default());
let response = client2.register_input_file(request).unwrap();
let input_file_id_user2 = response.data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input" => input_file_id_user2.clone()),
hashmap!(),
);
let response = client1.assign_data(request);
assert!(response.is_err());
// !output_file.owner.contains(user_id)
let url = Url::parse("https://output_file_path").unwrap();
let request = RegisterOutputFileRequest::new(url, FileCrypto::default());
let response = client2.register_output_file(request).unwrap();
let output_file_id_user2 = response.data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output" => output_file_id_user2.clone()),
);
let response = client1.assign_data(request);
assert!(response.is_err());
let existing_outfile_id_user1 =
ExternalID::try_from("output-00000000-0000-0000-0000-000000000001").unwrap();
// output_file.cmac.is_some()
let request = GetOutputFileRequest::new(existing_outfile_id_user1.clone());
client1.get_output_file(request).unwrap();
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output" => existing_outfile_id_user1),
);
let response = client1.assign_data(request);
assert!(response.is_err());
// !fusion_data.owner_id_list.contains(user_id)
let file_id2 = ExternalID::try_from("input-00000000-0000-0000-0000-000000000002").unwrap();
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input" => file_id2.clone()),
hashmap!(),
);
let response = client1.assign_data(request);
assert!(response.is_err());
// inputs_ownership doesn't contain the name
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("none" => input_file_id_user2.clone()),
hashmap!(),
);
let response = client2.assign_data(request);
assert!(response.is_err());
// outputs_ownership doesn't contain the name
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("none" => output_file_id_user2.clone()),
);
let response = client2.assign_data(request);
assert!(response.is_err());
//input file: OwnerList != user_id
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input2" => input_file_id_user2.clone()),
hashmap!(),
);
let response = client2.assign_data(request);
assert!(response.is_err());
// input file: OwnerList != user_id
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input" => input_file_id_user2),
hashmap!(),
);
let response = client2.assign_data(request);
assert!(response.is_err());
// output file OwnerList != uids
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output2" => output_file_id_user2.clone()),
);
let response = client2.assign_data(request);
assert!(response.is_err());
// output file: OwnerList != uids
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output1" => output_file_id_user2),
);
let response = client2.assign_data(request);
assert!(response.is_err());
// assign all the data
let url = Url::parse("input://path").unwrap();
let cmac = FileAuthTag::mock();
let request = RegisterInputFileRequest::new(url, cmac, FileCrypto::default());
let response = client1.register_input_file(request);
let input_file_id_user1 = response.unwrap().data_id;
let url = Url::parse("https://output_file_path").unwrap();
let request = RegisterOutputFileRequest::new(url, FileCrypto::default());
let response = client1.register_output_file(request);
let output_file_id_user1 = response.unwrap().data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input" => input_file_id_user1.clone()),
hashmap!("output" => output_file_id_user1),
);
let response = client1.assign_data(request);
assert!(response.is_ok());
let request =
AssignDataRequest::new(task_id.clone(), hashmap!("input2" => file_id2), hashmap!());
let response = client3.assign_data(request);
assert!(response.is_ok());
let request = RegisterFusionOutputRequest::new(vec!["mock_user2", "mock_user3"]);
let response = client3.register_fusion_output(request).unwrap();
let fusion_output = response.data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output2" => fusion_output),
);
let response = client3.assign_data(request);
assert!(response.is_ok());
let request = GetTaskRequest::new(task_id.clone());
let response = client3.get_task(request).unwrap();
assert_eq!(response.status, TaskStatus::DataAssigned);
// task.status != Created
let request = AssignDataRequest::new(
task_id,
hashmap!("input" => input_file_id_user1),
hashmap!(),
);
let response = client1.assign_data(request);
assert!(response.is_err());
}
#[test_case]
fn test_approve_task() {
let mut client = authorized_client("mock_user");
let mut client1 = authorized_client("mock_user1");
let mut client2 = authorized_client("mock_user2");
let mut client3 = authorized_client("mock_user3");
let request = create_valid_task_request();
let response = client.create_task(request).unwrap();
let task_id = response.task_id;
// task_status != ready
let request = ApproveTaskRequest::new(task_id.clone());
let response = client1.approve_task(request);
assert!(response.is_err());
// assign all the data
let url = Url::parse("input://path").unwrap();
let cmac = FileAuthTag::mock();
let request = RegisterInputFileRequest::new(url, cmac, FileCrypto::default());
let response = client1.register_input_file(request).unwrap();
let input_file_id_user1 = response.data_id;
let url = Url::parse("https://output_file_path").unwrap();
let request = RegisterOutputFileRequest::new(url, FileCrypto::default());
let response = client1.register_output_file(request).unwrap();
let output_file_id_user1 = response.data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input" => input_file_id_user1),
hashmap!("output" => output_file_id_user1),
);
let response = client1.assign_data(request);
assert!(response.is_ok());
let input_file_id_user2 =
ExternalID::try_from("input-00000000-0000-0000-0000-000000000002").unwrap();
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input2" => input_file_id_user2),
hashmap!(),
);
let response = client2.assign_data(request);
assert!(response.is_ok());
let request = RegisterFusionOutputRequest::new(vec!["mock_user2", "mock_user3"]);
let response = client3.register_fusion_output(request);
let fusion_output = response.unwrap().data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output2" => fusion_output),
);
let response = client3.assign_data(request);
assert!(response.is_ok());
let request = GetTaskRequest::new(task_id.clone());
let response = client2.get_task(request).unwrap();
assert_eq!(response.status, TaskStatus::DataAssigned);
// user_id not in task.participants
let mut unknown_client = authorized_client("non-participant");
let request = ApproveTaskRequest::new(task_id.clone());
let response = unknown_client.approve_task(request);
assert!(response.is_err());
//all participants approve the task
let request = ApproveTaskRequest::new(task_id.clone());
let response = client.approve_task(request);
assert!(response.is_ok());
let request = ApproveTaskRequest::new(task_id.clone());
let response = client1.approve_task(request);
assert!(response.is_ok());
let request = ApproveTaskRequest::new(task_id.clone());
let response = client2.approve_task(request);
assert!(response.is_ok());
let request = ApproveTaskRequest::new(task_id.clone());
let response = client3.approve_task(request);
assert!(response.is_ok());
let request = GetTaskRequest::new(task_id);
let response = client2.get_task(request).unwrap();
assert_eq!(response.status, TaskStatus::Approved);
}
#[test_case]
fn test_invoke_task() {
let mut client = authorized_client("mock_user");
let mut client1 = authorized_client("mock_user1");
let mut client2 = authorized_client("mock_user2");
let mut client3 = authorized_client("mock_user3");
let request = create_valid_task_request();
let response = client.create_task(request);
assert!(response.is_ok());
let task_id = response.unwrap().task_id;
// assign all the data
let url = Url::parse("input://path").unwrap();
let cmac = FileAuthTag::mock();
let request = RegisterInputFileRequest::new(url, cmac, FileCrypto::default());
let response = client1.register_input_file(request).unwrap();
let input_file_id_user1 = response.data_id;
let url = Url::parse("https://output_file_path").unwrap();
let request = RegisterOutputFileRequest::new(url, FileCrypto::default());
let response = client1.register_output_file(request).unwrap();
let output_file_id_user1 = response.data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input" => input_file_id_user1),
hashmap!("output" => output_file_id_user1),
);
client1.assign_data(request).unwrap();
let input_file_id_user2 =
ExternalID::try_from("input-00000000-0000-0000-0000-000000000002").unwrap();
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!("input2" => input_file_id_user2),
hashmap!(),
);
let response = client2.assign_data(request);
assert!(response.is_ok());
let request = RegisterFusionOutputRequest::new(vec!["mock_user2", "mock_user3"]);
let response = client3.register_fusion_output(request);
let fusion_output = response.unwrap().data_id;
let request = AssignDataRequest::new(
task_id.clone(),
hashmap!(),
hashmap!("output2" => fusion_output),
);
let response = client3.assign_data(request);
assert!(response.is_ok());
// task status != Approved
let request = InvokeTaskRequest::new(task_id.clone());
let response = client.invoke_task(request);
assert!(response.is_err());
//all participants approve the task
let request = ApproveTaskRequest::new(task_id.clone());
client.approve_task(request).unwrap();
let request = ApproveTaskRequest::new(task_id.clone());
client1.approve_task(request).unwrap();
let request = ApproveTaskRequest::new(task_id.clone());
client2.approve_task(request).unwrap();
let request = ApproveTaskRequest::new(task_id.clone());
client3.approve_task(request).unwrap();
let request = GetTaskRequest::new(task_id.clone());
let response = client2.get_task(request).unwrap();
assert_eq!(response.status, TaskStatus::Approved);
// user_id != task.creator
let request = InvokeTaskRequest::new(task_id.clone());
let response = client2.invoke_task(request);
assert!(response.is_err());
// invoke task
let request = InvokeTaskRequest::new(task_id.clone());
client.invoke_task(request).unwrap();
let request = GetTaskRequest::new(task_id);
let response = client2.get_task(request).unwrap();
assert_eq!(response.status, TaskStatus::Staged);
let request = PullTaskRequest {};
let mut scheduler_client = get_scheduler_client();
let response = scheduler_client.pull_task(request);
assert!(response.is_ok());
}
| 37.123953 | 95 | 0.686189 |
6ac0d8a9c293128be1c27a9ee26e35650c6d5017
| 4,870 |
// Copyright 2014 M. Rizky Luthfianto.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
lazy_static! {
// taken from https://github.com/seqan/seqan/blob/master/include%2Fseqan
// %2Fscore%2Fscore_matrix_data.h#L806
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
static ref MAT: ndarray::Array2<i32> = ndarray::Array::from_shape_vec((27, 27), vec![
2, 0, -2, 0, 0, -3, 1, -1, -1, -2, -1, -2, -1, 0, 0, 1, 0, -2, 1, 1, 0, 0,
-6, -3, 0, 0, -8,
0, 3, -4, 3, 3, -4, 0, 1, -2, -3, 1, -3, -2, 2, -1, -1, 1, -1, 0, 0, -1, -2,
-5, -3, 2, -1, -8,
-2, -4, 12, -5, -5, -4, -3, -3, -2, -4, -5, -6, -5, -4, -3, -3, -5, -4, 0, -2, -3, -2,
-8, 0, -5, -3, -8,
0, 3, -5, 4, 3, -6, 1, 1, -2, -3, 0, -4, -3, 2, -1, -1, 2, -1, 0, 0, -1, -2,
-7, -4, 3, -1, -8,
0, 3, -5, 3, 4, -5, 0, 1, -2, -3, 0, -3, -2, 1, -1, -1, 2, -1, 0, 0, -1, -2,
-7, -4, 3, -1, -8,
-3, -4, -4, -6, -5, 9, -5, -2, 1, 2, -5, 2, 0, -3, -2, -5, -5, -4, -3, -3, -2, -1,
0, 7, -5, -2, -8,
1, 0, -3, 1, 0, -5, 5, -2, -3, -4, -2, -4, -3, 0, -1, 0, -1, -3, 1, 0, -1, -1,
-7, -5, 0, -1, -8,
-1, 1, -3, 1, 1, -2, -2, 6, -2, -2, 0, -2, -2, 2, -1, 0, 3, 2, -1, -1, -1, -2,
-3, 0, 2, -1, -8,
-1, -2, -2, -2, -2, 1, -3, -2, 5, 4, -2, 2, 2, -2, -1, -2, -2, -2, -1, 0, -1, 4,
-5, -1, -2, -1, -8,
-2, -3, -4, -3, -3, 2, -4, -2, 4, 4, -3, 4, 3, -3, -1, -3, -2, -3, -2, -1, -1, 3,
-4, -1, -3, -1, -8,
-1, 1, -5, 0, 0, -5, -2, 0, -2, -3, 5, -3, 0, 1, -1, -1, 1, 3, 0, 0, -1, -2,
-3, -4, 0, -1, -8,
-2, -3, -6, -4, -3, 2, -4, -2, 2, 4, -3, 6, 4, -3, -1, -3, -2, -3, -3, -2, -1, 2,
-2, -1, -3, -1, -8,
-1, -2, -5, -3, -2, 0, -3, -2, 2, 3, 0, 4, 6, -2, -1, -2, -1, 0, -2, -1, -1, 2,
-4, -2, -2, -1, -8,
0, 2, -4, 2, 1, -3, 0, 2, -2, -3, 1, -3, -2, 2, 0, 0, 1, 0, 1, 0, 0, -2,
-4, -2, 1, 0, -8,
0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, -1,
-4, -2, -1, -1, -8,
1, -1, -3, -1, -1, -5, 0, 0, -2, -3, -1, -3, -2, 0, -1, 6, 0, 0, 1, 0, -1, -1,
-6, -5, 0, -1, -8,
0, 1, -5, 2, 2, -5, -1, 3, -2, -2, 1, -2, -1, 1, -1, 0, 4, 1, -1, -1, -1, -2,
-5, -4, 3, -1, -8,
-2, -1, -4, -1, -1, -4, -3, 2, -2, -3, 3, -3, 0, 0, -1, 0, 1, 6, 0, -1, -1, -2,
2, -4, 0, -1, -8,
1, 0, 0, 0, 0, -3, 1, -1, -1, -2, 0, -3, -2, 1, 0, 1, -1, 0, 2, 1, 0, -1,
-2, -3, 0, 0, -8,
1, 0, -2, 0, 0, -3, 0, -1, 0, -1, 0, -2, -1, 0, 0, 0, -1, -1, 1, 3, 0, 0,
-5, -3, -1, 0, -8,
0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, -1,
-4, -2, -1, -1, -8,
0, -2, -2, -2, -2, -1, -1, -2, 4, 3, -2, 2, 2, -2, -1, -1, -2, -2, -1, 0, -1, 4,
-6, -2, -2, -1, -8,
-6, -5, -8, -7, -7, 0, -7, -3, -5, -4, -3, -2, -4, -4, -4, -6, -5, 2, -2, -5, -4, -6,
17, 0, -6, -4, -8,
-3, -3, 0, -4, -4, 7, -5, 0, -1, -1, -4, -1, -2, -2, -2, -5, -4, -4, -3, -3, -2, -2,
0, 10, -4, -2, -8,
0, 2, -5, 3, 3, -5, 0, 2, -2, -3, 0, -3, -2, 1, -1, 0, 3, 0, 0, -1, -1, -2,
-6, -4, 3, -1, -8,
0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, -1,
-4, -2, -1, -1, -8,
-8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8,
-8, -8, -8, -8, 1,
]).unwrap();
}
#[inline]
fn lookup(a: u8) -> usize {
if a == b'Y' {
23
} else if a == b'Z' {
24
} else if a == b'X' {
25
} else if a == b'*' {
26
} else {
(a - 65) as usize
}
}
/// Return the PAM250 substitution matrix score of [a, b]
///
/// # Example
///
/// ```
/// use bio::scores::pam250;
/// assert_eq!(pam250(b'H', b'A'), -1);
/// ```
pub fn pam250(a: u8, b: u8) -> i32 {
let a = lookup(a);
let b = lookup(b);
MAT[(a, b)]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pam250() {
let score1 = pam250(b'A', b'A');
assert_eq!(score1, 2);
let score2 = pam250(b'*', b'*');
assert_eq!(score2, 1);
let score3 = pam250(b'A', b'*');
assert_eq!(score3, -8);
let score4 = pam250(b'*', b'*');
assert_eq!(score4, 1);
let score5 = pam250(b'X', b'X');
assert_eq!(score5, -1);
let score6 = pam250(b'X', b'Z');
assert_eq!(score6, -1);
}
}
| 41.271186 | 95 | 0.316632 |
b95649ad68730237a7cd32bfecb294b4a309aa76
| 3,932 |
use std::{marker::PhantomData, sync::Arc};
use futures_util::stream::BoxStream;
use futures_util::{
future,
stream::{self, StreamExt},
TryStreamExt,
};
use log::info;
use crate::{
errors::Result,
types::{
block::BlockRef, query_result::stream_blocks::BlockStream, Block, Cmd, Query, Row,
Rows, Complex, Simple
},
ClientHandle,
};
pub(crate) mod stream_blocks;
/// Result of a query or statement execution.
pub struct QueryResult<'a> {
pub(crate) client: &'a mut ClientHandle,
pub(crate) query: Query,
}
impl<'a> QueryResult<'a> {
/// Fetch data from table. It returns a block that contains all rows.
pub async fn fetch_all(self) -> Result<Block<Complex>> {
let blocks = self
.stream_blocks_(false)
.try_fold(Vec::new(), |mut blocks, block| {
if !block.is_empty() {
blocks.push(block);
}
future::ready(Ok(blocks))
})
.await?;
Ok(Block::concat(blocks.as_slice()))
}
/// Method that produces a stream of blocks containing rows
///
/// example:
///
/// ```rust
/// # use std::env;
/// # use clickhouse_rs::{Pool, errors::Result};
/// # use futures_util::{future, TryStreamExt};
/// #
/// # let mut rt = tokio::runtime::Runtime::new().unwrap();
/// # let ret: Result<()> = rt.block_on(async {
/// #
/// # let database_url = env::var("DATABASE_URL")
/// # .unwrap_or("tcp://localhost:9000?compression=lz4".into());
/// #
/// # let sql_query = "SELECT number FROM system.numbers LIMIT 100000";
/// # let pool = Pool::new(database_url);
/// #
/// let mut c = pool.get_handle().await?;
/// let mut result = c.query(sql_query)
/// .stream_blocks()
/// .try_for_each(|block| {
/// println!("{:?}\nblock counts: {} rows", block, block.row_count());
/// future::ready(Ok(()))
/// }).await?;
/// # Ok(())
/// # });
/// # ret.unwrap()
/// ```
pub fn stream_blocks(self) -> BoxStream<'a, Result<Block>> {
self.stream_blocks_(true)
}
fn stream_blocks_(self, skip_first_block: bool) -> BoxStream<'a, Result<Block>> {
let query = self.query.clone();
self.client
.wrap_stream::<'a, _>(move |c: &'a mut ClientHandle| {
info!("[send query] {}", query.get_sql());
c.pool.detach();
let context = c.context.clone();
let inner = c
.inner
.take()
.unwrap()
.call(Cmd::SendQuery(query, context));
BlockStream::<'a>::new(c, inner, skip_first_block)
})
}
/// Method that produces a stream of rows
pub fn stream(self) -> BoxStream<'a, Result<Row<'a, Simple>>> {
Box::pin(
self.stream_blocks()
.map(|block_ret| {
let result: BoxStream<'a, Result<Row<'a, Simple>>> = match block_ret {
Ok(block) => {
let block = Arc::new(block);
let block_ref = BlockRef::Owned(block);
Box::pin(
stream::iter(Rows {
row: 0,
block_ref,
kind: PhantomData,
})
.map(|row| -> Result<Row<'static, Simple>> { Ok(row) }),
)
}
Err(err) => Box::pin(stream::once(future::err(err))),
};
result
})
.flatten(),
)
}
}
| 31.96748 | 90 | 0.458037 |
22702d646fab6977896d40dbfa331500c96a857f
| 536 |
#[macro_export]
macro_rules! version {
() => {
&*format!(
"{}{}",
env!("CARGO_PKG_VERSION"),
if option_env!("CI_TAG").is_none() {
format!(
" [channel={} commit={}]",
option_env!("CHANNEL").unwrap_or("unknown"),
option_env!("CI_COMMIT").unwrap_or("unknown"),
)
} else {
"".to_string()
},
)
};
}
pub mod input_parsers;
pub mod input_validators;
| 24.363636 | 66 | 0.414179 |
0a5a3267531fdf8a77f00f829afca684c0abf4a6
| 2,108 |
// This file was generated by gir (d50d839) from gir-files (???)
// DO NOT EDIT
use Object;
use Pad;
use PadDirection;
use PadTemplate;
use ProxyPad;
use ffi;
use glib;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
pub struct GhostPad(Object<ffi::GstGhostPad, ffi::GstGhostPadClass>): ProxyPad, Pad, Object;
match fn {
get_type => || ffi::gst_ghost_pad_get_type(),
}
}
impl GhostPad {
pub fn new_no_target<'a, P: Into<Option<&'a str>>>(name: P, dir: PadDirection) -> GhostPad {
assert_initialized_main_thread!();
let name = name.into();
let name = name.to_glib_none();
unsafe {
Pad::from_glib_none(ffi::gst_ghost_pad_new_no_target(name.0, dir.to_glib())).downcast_unchecked()
}
}
pub fn new_no_target_from_template<'a, P: Into<Option<&'a str>>>(name: P, templ: &PadTemplate) -> GhostPad {
skip_assert_initialized!();
let name = name.into();
let name = name.to_glib_none();
unsafe {
Pad::from_glib_none(ffi::gst_ghost_pad_new_no_target_from_template(name.0, templ.to_glib_none().0)).downcast_unchecked()
}
}
}
unsafe impl Send for GhostPad {}
unsafe impl Sync for GhostPad {}
pub trait GhostPadExt {
fn get_target(&self) -> Option<Pad>;
fn set_target<'a, P: IsA<Pad> + 'a, Q: Into<Option<&'a P>>>(&self, newtarget: Q) -> Result<(), glib::error::BoolError>;
}
impl<O: IsA<GhostPad>> GhostPadExt for O {
fn get_target(&self) -> Option<Pad> {
unsafe {
from_glib_full(ffi::gst_ghost_pad_get_target(self.to_glib_none().0))
}
}
fn set_target<'a, P: IsA<Pad> + 'a, Q: Into<Option<&'a P>>>(&self, newtarget: Q) -> Result<(), glib::error::BoolError> {
let newtarget = newtarget.into();
let newtarget = newtarget.to_glib_none();
unsafe {
glib::error::BoolError::from_glib(ffi::gst_ghost_pad_set_target(self.to_glib_none().0, newtarget.0), "Failed to set target")
}
}
}
| 29.690141 | 136 | 0.633776 |
f9954087b4aced97ecc64a46bd40e9b062aeb1ef
| 8,671 |
//! A Loop Invariant Code Motion optimization pass
use cursor::{Cursor, FuncCursor};
use dominator_tree::DominatorTree;
use entity::{EntityList, ListPool};
use flowgraph::{BasicBlock, ControlFlowGraph};
use fx::FxHashSet;
use ir::{DataFlowGraph, Ebb, Function, Inst, InstBuilder, Layout, Opcode, Type, Value};
use loop_analysis::{Loop, LoopAnalysis};
use std::vec::Vec;
use timing;
/// Performs the LICM pass by detecting loops within the CFG and moving
/// loop-invariant instructions out of them.
/// Changes the CFG and domtree in-place during the operation.
pub fn do_licm(
func: &mut Function,
cfg: &mut ControlFlowGraph,
domtree: &mut DominatorTree,
loop_analysis: &mut LoopAnalysis,
) {
let _tt = timing::licm();
debug_assert!(cfg.is_valid());
debug_assert!(domtree.is_valid());
debug_assert!(loop_analysis.is_valid());
for lp in loop_analysis.loops() {
// For each loop that we want to optimize we determine the set of loop-invariant
// instructions
let invariant_insts = remove_loop_invariant_instructions(lp, func, cfg, loop_analysis);
// Then we create the loop's pre-header and fill it with the invariant instructions
// Then we remove the invariant instructions from the loop body
if !invariant_insts.is_empty() {
// If the loop has a natural pre-header we use it, otherwise we create it.
let mut pos;
match has_pre_header(&func.layout, cfg, domtree, loop_analysis.loop_header(lp)) {
None => {
let pre_header =
create_pre_header(loop_analysis.loop_header(lp), func, cfg, domtree);
pos = FuncCursor::new(func).at_last_inst(pre_header);
}
// If there is a natural pre-header we insert new instructions just before the
// related jumping instruction (which is not necessarily at the end).
Some((_, last_inst)) => {
pos = FuncCursor::new(func).at_inst(last_inst);
}
};
// The last instruction of the pre-header is the termination instruction (usually
// a jump) so we need to insert just before this.
for inst in invariant_insts {
pos.insert_inst(inst);
}
}
}
// We have to recompute the domtree to account for the changes
cfg.compute(func);
domtree.compute(func, cfg);
}
// Insert a pre-header before the header, modifying the function layout and CFG to reflect it.
// A jump instruction to the header is placed at the end of the pre-header.
fn create_pre_header(
header: Ebb,
func: &mut Function,
cfg: &mut ControlFlowGraph,
domtree: &DominatorTree,
) -> Ebb {
let pool = &mut ListPool::<Value>::new();
let header_args_values: Vec<Value> = func.dfg.ebb_params(header).into_iter().cloned().collect();
let header_args_types: Vec<Type> = header_args_values
.clone()
.into_iter()
.map(|val| func.dfg.value_type(val))
.collect();
let pre_header = func.dfg.make_ebb();
let mut pre_header_args_value: EntityList<Value> = EntityList::new();
for typ in header_args_types {
pre_header_args_value.push(func.dfg.append_ebb_param(pre_header, typ), pool);
}
for BasicBlock {
inst: last_inst, ..
} in cfg.pred_iter(header)
{
// We only follow normal edges (not the back edges)
if !domtree.dominates(header, last_inst, &func.layout) {
change_branch_jump_destination(last_inst, pre_header, func);
}
}
{
let mut pos = FuncCursor::new(func).at_top(header);
// Inserts the pre-header at the right place in the layout.
pos.insert_ebb(pre_header);
pos.next_inst();
pos.ins().jump(header, pre_header_args_value.as_slice(pool));
}
pre_header
}
// Detects if a loop header has a natural pre-header.
//
// A loop header has a pre-header if there is only one predecessor that the header doesn't
// dominate.
// Returns the pre-header Ebb and the instruction jumping to the header.
fn has_pre_header(
layout: &Layout,
cfg: &ControlFlowGraph,
domtree: &DominatorTree,
header: Ebb,
) -> Option<(Ebb, Inst)> {
let mut result = None;
let mut found = false;
for BasicBlock {
ebb: pred_ebb,
inst: last_inst,
} in cfg.pred_iter(header)
{
// We only count normal edges (not the back edges)
if !domtree.dominates(header, last_inst, layout) {
if found {
// We have already found one, there are more than one
return None;
} else {
result = Some((pred_ebb, last_inst));
found = true;
}
}
}
result
}
// Change the destination of a jump or branch instruction. Does nothing if called with a non-jump
// or non-branch instruction.
fn change_branch_jump_destination(inst: Inst, new_ebb: Ebb, func: &mut Function) {
match func.dfg[inst].branch_destination_mut() {
None => (),
Some(instruction_dest) => *instruction_dest = new_ebb,
}
}
/// Test whether the given opcode is unsafe to even consider for LICM.
fn trivially_unsafe_for_licm(opcode: Opcode) -> bool {
opcode.can_load()
|| opcode.can_store()
|| opcode.is_call()
|| opcode.is_branch()
|| opcode.is_terminator()
|| opcode.is_return()
|| opcode.can_trap()
|| opcode.other_side_effects()
|| opcode.writes_cpu_flags()
}
/// Test whether the given instruction is loop-invariant.
fn is_loop_invariant(inst: Inst, dfg: &DataFlowGraph, loop_values: &FxHashSet<Value>) -> bool {
if trivially_unsafe_for_licm(dfg[inst].opcode()) {
return false;
}
let inst_args = dfg.inst_args(inst);
for arg in inst_args {
let arg = dfg.resolve_aliases(*arg);
if loop_values.contains(&arg) {
return false;
}
}
true
}
// Traverses a loop in reverse post-order from a header EBB and identify loop-invariant
// instructions. These loop-invariant instructions are then removed from the code and returned
// (in reverse post-order) for later use.
fn remove_loop_invariant_instructions(
lp: Loop,
func: &mut Function,
cfg: &ControlFlowGraph,
loop_analysis: &LoopAnalysis,
) -> Vec<Inst> {
let mut loop_values: FxHashSet<Value> = FxHashSet();
let mut invariant_insts: Vec<Inst> = Vec::new();
let mut pos = FuncCursor::new(func);
// We traverse the loop EBB in reverse post-order.
for ebb in postorder_ebbs_loop(loop_analysis, cfg, lp).iter().rev() {
// Arguments of the EBB are loop values
for val in pos.func.dfg.ebb_params(*ebb) {
loop_values.insert(*val);
}
pos.goto_top(*ebb);
#[cfg_attr(feature = "cargo-clippy", allow(block_in_if_condition_stmt))]
while let Some(inst) = pos.next_inst() {
if is_loop_invariant(inst, &pos.func.dfg, &loop_values) {
// If all the instruction's argument are defined outside the loop
// then this instruction is loop-invariant
invariant_insts.push(inst);
// We remove it from the loop
pos.remove_inst_and_step_back();
} else {
// If the instruction is not loop-invariant we push its results in the set of
// loop values
for out in pos.func.dfg.inst_results(inst) {
loop_values.insert(*out);
}
}
}
}
invariant_insts
}
/// Return ebbs from a loop in post-order, starting from an entry point in the block.
fn postorder_ebbs_loop(loop_analysis: &LoopAnalysis, cfg: &ControlFlowGraph, lp: Loop) -> Vec<Ebb> {
let mut grey = FxHashSet();
let mut black = FxHashSet();
let mut stack = vec![loop_analysis.loop_header(lp)];
let mut postorder = Vec::new();
while !stack.is_empty() {
let node = stack.pop().unwrap();
if !grey.contains(&node) {
// This is a white node. Mark it as gray.
grey.insert(node);
stack.push(node);
// Get any children we've never seen before.
for child in cfg.succ_iter(node) {
if loop_analysis.is_in_loop(child, lp) && !grey.contains(&child) {
stack.push(child);
}
}
} else if !black.contains(&node) {
postorder.push(node);
black.insert(node);
}
}
postorder
}
| 37.055556 | 100 | 0.619421 |
28f5a65374d98752c8e05c14c91bcc14832c6ed8
| 37,700 |
//! This module contains implements of the `Lift` and `TypeFoldable`
//! traits for various types in the Rust compiler. Most are written by
//! hand, though we've recently added some macros (e.g.,
//! `BraceStructLiftImpl!`) to help with the tedium.
use mir::ProjectionKind;
use mir::interpret::ConstValue;
use ty::{self, Lift, Ty, TyCtxt};
use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
use smallvec::SmallVec;
use mir::interpret;
use std::rc::Rc;
///////////////////////////////////////////////////////////////////////////
// Atomic structs
//
// For things that don't carry any arena-allocated data (and are
// copy...), just add them to this list.
CloneTypeFoldableAndLiftImpls! {
(),
bool,
usize,
::ty::layout::VariantIdx,
u64,
String,
::middle::region::Scope,
::syntax::ast::FloatTy,
::syntax::ast::NodeId,
::syntax_pos::symbol::Symbol,
::hir::def::Def,
::hir::def_id::DefId,
::hir::InlineAsm,
::hir::MatchSource,
::hir::Mutability,
::hir::Unsafety,
::rustc_target::spec::abi::Abi,
::mir::Local,
::mir::Promoted,
::traits::Reveal,
::ty::adjustment::AutoBorrowMutability,
::ty::AdtKind,
// Including `BoundRegion` is a *bit* dubious, but direct
// references to bound region appear in `ty::Error`, and aren't
// really meant to be folded. In general, we can only fold a fully
// general `Region`.
::ty::BoundRegion,
::ty::ClosureKind,
::ty::IntVarValue,
::ty::ParamTy,
::ty::UniverseIndex,
::ty::Variance,
::syntax_pos::Span,
}
///////////////////////////////////////////////////////////////////////////
// Lift implementations
impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
type Lifted = (A::Lifted, B::Lifted);
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.0).and_then(|a| tcx.lift(&self.1).map(|b| (a, b)))
}
}
impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>, C: Lift<'tcx>> Lift<'tcx> for (A, B, C) {
type Lifted = (A::Lifted, B::Lifted, C::Lifted);
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.0).and_then(|a| {
tcx.lift(&self.1).and_then(|b| tcx.lift(&self.2).map(|c| (a, b, c)))
})
}
}
impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Option<T> {
type Lifted = Option<T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
Some(ref x) => tcx.lift(x).map(Some),
None => Some(None)
}
}
}
impl<'tcx, T: Lift<'tcx>, E: Lift<'tcx>> Lift<'tcx> for Result<T, E> {
type Lifted = Result<T::Lifted, E::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
Ok(ref x) => tcx.lift(x).map(Ok),
Err(ref e) => tcx.lift(e).map(Err)
}
}
}
impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Box<T> {
type Lifted = Box<T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&**self).map(Box::new)
}
}
impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] {
type Lifted = Vec<T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
// type annotation needed to inform `projection_must_outlive`
let mut result : Vec<<T as Lift<'tcx>>::Lifted>
= Vec::with_capacity(self.len());
for x in self {
if let Some(value) = tcx.lift(x) {
result.push(value);
} else {
return None;
}
}
Some(result)
}
}
impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Vec<T> {
type Lifted = Vec<T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self[..])
}
}
impl<'tcx, I: Idx, T: Lift<'tcx>> Lift<'tcx> for IndexVec<I, T> {
type Lifted = IndexVec<I, T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
self.iter()
.map(|e| tcx.lift(e))
.collect()
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::TraitRef<'a> {
type Lifted = ty::TraitRef<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.substs).map(|substs| ty::TraitRef {
def_id: self.def_id,
substs,
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialTraitRef<'a> {
type Lifted = ty::ExistentialTraitRef<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.substs).map(|substs| ty::ExistentialTraitRef {
def_id: self.def_id,
substs,
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::TraitPredicate<'a> {
type Lifted = ty::TraitPredicate<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
-> Option<ty::TraitPredicate<'tcx>> {
tcx.lift(&self.trait_ref).map(|trait_ref| ty::TraitPredicate {
trait_ref,
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::SubtypePredicate<'a> {
type Lifted = ty::SubtypePredicate<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
-> Option<ty::SubtypePredicate<'tcx>> {
tcx.lift(&(self.a, self.b)).map(|(a, b)| ty::SubtypePredicate {
a_is_expected: self.a_is_expected,
a,
b,
})
}
}
impl<'tcx, A: Copy+Lift<'tcx>, B: Copy+Lift<'tcx>> Lift<'tcx> for ty::OutlivesPredicate<A, B> {
type Lifted = ty::OutlivesPredicate<A::Lifted, B::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&(self.0, self.1)).map(|(a, b)| ty::OutlivesPredicate(a, b))
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::ProjectionTy<'a> {
type Lifted = ty::ProjectionTy<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
-> Option<ty::ProjectionTy<'tcx>> {
tcx.lift(&self.substs).map(|substs| {
ty::ProjectionTy {
item_def_id: self.item_def_id,
substs,
}
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::ProjectionPredicate<'a> {
type Lifted = ty::ProjectionPredicate<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>)
-> Option<ty::ProjectionPredicate<'tcx>> {
tcx.lift(&(self.projection_ty, self.ty)).map(|(projection_ty, ty)| {
ty::ProjectionPredicate {
projection_ty,
ty,
}
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialProjection<'a> {
type Lifted = ty::ExistentialProjection<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.substs).map(|substs| {
ty::ExistentialProjection {
substs,
ty: tcx.lift(&self.ty).expect("type must lift when substs do"),
item_def_id: self.item_def_id,
}
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::Predicate<'a> {
type Lifted = ty::Predicate<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
ty::Predicate::Trait(ref binder) => {
tcx.lift(binder).map(ty::Predicate::Trait)
}
ty::Predicate::Subtype(ref binder) => {
tcx.lift(binder).map(ty::Predicate::Subtype)
}
ty::Predicate::RegionOutlives(ref binder) => {
tcx.lift(binder).map(ty::Predicate::RegionOutlives)
}
ty::Predicate::TypeOutlives(ref binder) => {
tcx.lift(binder).map(ty::Predicate::TypeOutlives)
}
ty::Predicate::Projection(ref binder) => {
tcx.lift(binder).map(ty::Predicate::Projection)
}
ty::Predicate::WellFormed(ty) => {
tcx.lift(&ty).map(ty::Predicate::WellFormed)
}
ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
tcx.lift(&closure_substs)
.map(|closure_substs| ty::Predicate::ClosureKind(closure_def_id,
closure_substs,
kind))
}
ty::Predicate::ObjectSafe(trait_def_id) => {
Some(ty::Predicate::ObjectSafe(trait_def_id))
}
ty::Predicate::ConstEvaluatable(def_id, substs) => {
tcx.lift(&substs).map(|substs| {
ty::Predicate::ConstEvaluatable(def_id, substs)
})
}
}
}
}
impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for ty::Binder<T> {
type Lifted = ty::Binder<T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(self.skip_binder()).map(ty::Binder::bind)
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
type Lifted = ty::ParamEnv<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.caller_bounds).map(|caller_bounds| {
ty::ParamEnv {
reveal: self.reveal,
caller_bounds,
def_id: self.def_id,
}
})
}
}
impl<'a, 'tcx, T: Lift<'tcx>> Lift<'tcx> for ty::ParamEnvAnd<'a, T> {
type Lifted = ty::ParamEnvAnd<'tcx, T::Lifted>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.param_env).and_then(|param_env| {
tcx.lift(&self.value).map(|value| {
ty::ParamEnvAnd {
param_env,
value,
}
})
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::ClosureSubsts<'a> {
type Lifted = ty::ClosureSubsts<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.substs).map(|substs| {
ty::ClosureSubsts { substs }
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::GeneratorSubsts<'a> {
type Lifted = ty::GeneratorSubsts<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.substs).map(|substs| {
ty::GeneratorSubsts { substs }
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::Adjustment<'a> {
type Lifted = ty::adjustment::Adjustment<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.kind).and_then(|kind| {
tcx.lift(&self.target).map(|target| {
ty::adjustment::Adjustment { kind, target }
})
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::Adjust<'a> {
type Lifted = ty::adjustment::Adjust<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
ty::adjustment::Adjust::NeverToAny =>
Some(ty::adjustment::Adjust::NeverToAny),
ty::adjustment::Adjust::ReifyFnPointer =>
Some(ty::adjustment::Adjust::ReifyFnPointer),
ty::adjustment::Adjust::UnsafeFnPointer =>
Some(ty::adjustment::Adjust::UnsafeFnPointer),
ty::adjustment::Adjust::ClosureFnPointer =>
Some(ty::adjustment::Adjust::ClosureFnPointer),
ty::adjustment::Adjust::MutToConstPointer =>
Some(ty::adjustment::Adjust::MutToConstPointer),
ty::adjustment::Adjust::Unsize =>
Some(ty::adjustment::Adjust::Unsize),
ty::adjustment::Adjust::Deref(ref overloaded) => {
tcx.lift(overloaded).map(ty::adjustment::Adjust::Deref)
}
ty::adjustment::Adjust::Borrow(ref autoref) => {
tcx.lift(autoref).map(ty::adjustment::Adjust::Borrow)
}
}
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::OverloadedDeref<'a> {
type Lifted = ty::adjustment::OverloadedDeref<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.region).map(|region| {
ty::adjustment::OverloadedDeref {
region,
mutbl: self.mutbl,
}
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::AutoBorrow<'a> {
type Lifted = ty::adjustment::AutoBorrow<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
ty::adjustment::AutoBorrow::Ref(r, m) => {
tcx.lift(&r).map(|r| ty::adjustment::AutoBorrow::Ref(r, m))
}
ty::adjustment::AutoBorrow::RawPtr(m) => {
Some(ty::adjustment::AutoBorrow::RawPtr(m))
}
}
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::GenSig<'a> {
type Lifted = ty::GenSig<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&(self.yield_ty, self.return_ty))
.map(|(yield_ty, return_ty)| {
ty::GenSig {
yield_ty,
return_ty,
}
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::FnSig<'a> {
type Lifted = ty::FnSig<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.inputs_and_output).map(|x| {
ty::FnSig {
inputs_and_output: x,
variadic: self.variadic,
unsafety: self.unsafety,
abi: self.abi,
}
})
}
}
impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for ty::error::ExpectedFound<T> {
type Lifted = ty::error::ExpectedFound<T::Lifted>;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.expected).and_then(|expected| {
tcx.lift(&self.found).map(|found| {
ty::error::ExpectedFound {
expected,
found,
}
})
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::error::TypeError<'a> {
type Lifted = ty::error::TypeError<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
use ty::error::TypeError::*;
Some(match *self {
Mismatch => Mismatch,
UnsafetyMismatch(x) => UnsafetyMismatch(x),
AbiMismatch(x) => AbiMismatch(x),
Mutability => Mutability,
TupleSize(x) => TupleSize(x),
FixedArraySize(x) => FixedArraySize(x),
ArgCount => ArgCount,
RegionsDoesNotOutlive(a, b) => {
return tcx.lift(&(a, b)).map(|(a, b)| RegionsDoesNotOutlive(a, b))
}
RegionsPlaceholderMismatch => RegionsPlaceholderMismatch,
IntMismatch(x) => IntMismatch(x),
FloatMismatch(x) => FloatMismatch(x),
Traits(x) => Traits(x),
VariadicMismatch(x) => VariadicMismatch(x),
CyclicTy(t) => return tcx.lift(&t).map(|t| CyclicTy(t)),
ProjectionMismatched(x) => ProjectionMismatched(x),
ProjectionBoundsLength(x) => ProjectionBoundsLength(x),
Sorts(ref x) => return tcx.lift(x).map(Sorts),
ExistentialMismatch(ref x) => return tcx.lift(x).map(ExistentialMismatch)
})
}
}
impl<'a, 'tcx> Lift<'tcx> for ty::InstanceDef<'a> {
type Lifted = ty::InstanceDef<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
ty::InstanceDef::Item(def_id) =>
Some(ty::InstanceDef::Item(def_id)),
ty::InstanceDef::VtableShim(def_id) =>
Some(ty::InstanceDef::VtableShim(def_id)),
ty::InstanceDef::Intrinsic(def_id) =>
Some(ty::InstanceDef::Intrinsic(def_id)),
ty::InstanceDef::FnPtrShim(def_id, ref ty) =>
Some(ty::InstanceDef::FnPtrShim(def_id, tcx.lift(ty)?)),
ty::InstanceDef::Virtual(def_id, n) =>
Some(ty::InstanceDef::Virtual(def_id, n)),
ty::InstanceDef::ClosureOnceShim { call_once } =>
Some(ty::InstanceDef::ClosureOnceShim { call_once }),
ty::InstanceDef::DropGlue(def_id, ref ty) =>
Some(ty::InstanceDef::DropGlue(def_id, tcx.lift(ty)?)),
ty::InstanceDef::CloneShim(def_id, ref ty) =>
Some(ty::InstanceDef::CloneShim(def_id, tcx.lift(ty)?)),
}
}
}
BraceStructLiftImpl! {
impl<'a, 'tcx> Lift<'tcx> for ty::Instance<'a> {
type Lifted = ty::Instance<'tcx>;
def, substs
}
}
BraceStructLiftImpl! {
impl<'a, 'tcx> Lift<'tcx> for interpret::GlobalId<'a> {
type Lifted = interpret::GlobalId<'tcx>;
instance, promoted
}
}
BraceStructLiftImpl! {
impl<'a, 'tcx> Lift<'tcx> for ty::Const<'a> {
type Lifted = ty::Const<'tcx>;
val, ty
}
}
impl<'a, 'tcx> Lift<'tcx> for ConstValue<'a> {
type Lifted = ConstValue<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
match *self {
ConstValue::Scalar(x) => Some(ConstValue::Scalar(x)),
ConstValue::Slice(x, y) => Some(ConstValue::Slice(x, y)),
ConstValue::ByRef(x, alloc, z) => Some(ConstValue::ByRef(
x, alloc.lift_to_tcx(tcx)?, z,
)),
}
}
}
///////////////////////////////////////////////////////////////////////////
// TypeFoldable implementations.
//
// Ideally, each type should invoke `folder.fold_foo(self)` and
// nothing else. In some cases, though, we haven't gotten around to
// adding methods on the `folder` yet, and thus the folding is
// hard-coded here. This is less-flexible, because folders cannot
// override the behavior, but there are a lot of random types and one
// can easily refactor the folding into the TypeFolder trait as
// needed.
/// AdtDefs are basically the same as a DefId.
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::AdtDef {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
*self
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
false
}
}
impl<'tcx, T:TypeFoldable<'tcx>, U:TypeFoldable<'tcx>> TypeFoldable<'tcx> for (T, U) {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> (T, U) {
(self.0.fold_with(folder), self.1.fold_with(folder))
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.0.visit_with(visitor) || self.1.visit_with(visitor)
}
}
EnumTypeFoldableImpl! {
impl<'tcx, T> TypeFoldable<'tcx> for Option<T> {
(Some)(a),
(None),
} where T: TypeFoldable<'tcx>
}
impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Rc<T> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
Rc::new((**self).fold_with(folder))
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
(**self).visit_with(visitor)
}
}
impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<T> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let content: T = (**self).fold_with(folder);
box content
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
(**self).visit_with(visitor)
}
}
impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec<T> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
self.iter().map(|t| t.fold_with(folder)).collect()
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<[T]> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>().into_boxed_slice()
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx, T:TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder<T> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
self.map_bound_ref(|ty| ty.fold_with(folder))
}
fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
folder.fold_binder(self)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.skip_binder().visit_with(visitor)
}
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
visitor.visit_binder(self)
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ParamEnv<'tcx> { reveal, caller_bounds, def_id }
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::ExistentialPredicate<'tcx>> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_existential_predicates(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|p| p.visit_with(visitor))
}
}
EnumTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ExistentialPredicate<'tcx> {
(ty::ExistentialPredicate::Trait)(a),
(ty::ExistentialPredicate::Projection)(a),
(ty::ExistentialPredicate::AutoTrait)(a),
}
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<Ty<'tcx>> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|t| t.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_type_list(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ProjectionKind<'tcx>> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|t| t.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_projs(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx> TypeFoldable<'tcx> for ty::instance::Instance<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
use ty::InstanceDef::*;
Self {
substs: self.substs.fold_with(folder),
def: match self.def {
Item(did) => Item(did.fold_with(folder)),
VtableShim(did) => VtableShim(did.fold_with(folder)),
Intrinsic(did) => Intrinsic(did.fold_with(folder)),
FnPtrShim(did, ty) => FnPtrShim(
did.fold_with(folder),
ty.fold_with(folder),
),
Virtual(did, i) => Virtual(
did.fold_with(folder),
i,
),
ClosureOnceShim { call_once } => ClosureOnceShim {
call_once: call_once.fold_with(folder),
},
DropGlue(did, ty) => DropGlue(
did.fold_with(folder),
ty.fold_with(folder),
),
CloneShim(did, ty) => CloneShim(
did.fold_with(folder),
ty.fold_with(folder),
),
},
}
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
use ty::InstanceDef::*;
self.substs.visit_with(visitor) ||
match self.def {
Item(did) | VtableShim(did) | Intrinsic(did) | Virtual(did, _) => {
did.visit_with(visitor)
},
FnPtrShim(did, ty) | CloneShim(did, ty) => {
did.visit_with(visitor) || ty.visit_with(visitor)
},
DropGlue(did, ty) => {
did.visit_with(visitor) || ty.visit_with(visitor)
},
ClosureOnceShim { call_once } => call_once.visit_with(visitor),
}
}
}
impl<'tcx> TypeFoldable<'tcx> for interpret::GlobalId<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
Self {
instance: self.instance.fold_with(folder),
promoted: self.promoted
}
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.instance.visit_with(visitor)
}
}
impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let sty = match self.sty {
ty::RawPtr(tm) => ty::RawPtr(tm.fold_with(folder)),
ty::Array(typ, sz) => ty::Array(typ.fold_with(folder), sz.fold_with(folder)),
ty::Slice(typ) => ty::Slice(typ.fold_with(folder)),
ty::Adt(tid, substs) => ty::Adt(tid, substs.fold_with(folder)),
ty::Dynamic(ref trait_ty, ref region) =>
ty::Dynamic(trait_ty.fold_with(folder), region.fold_with(folder)),
ty::Tuple(ts) => ty::Tuple(ts.fold_with(folder)),
ty::FnDef(def_id, substs) => {
ty::FnDef(def_id, substs.fold_with(folder))
}
ty::FnPtr(f) => ty::FnPtr(f.fold_with(folder)),
ty::Ref(ref r, ty, mutbl) => {
ty::Ref(r.fold_with(folder), ty.fold_with(folder), mutbl)
}
ty::Generator(did, substs, movability) => {
ty::Generator(
did,
substs.fold_with(folder),
movability)
}
ty::GeneratorWitness(types) => ty::GeneratorWitness(types.fold_with(folder)),
ty::Closure(did, substs) => ty::Closure(did, substs.fold_with(folder)),
ty::Projection(ref data) => ty::Projection(data.fold_with(folder)),
ty::UnnormalizedProjection(ref data) => {
ty::UnnormalizedProjection(data.fold_with(folder))
}
ty::Opaque(did, substs) => ty::Opaque(did, substs.fold_with(folder)),
ty::Bool |
ty::Char |
ty::Str |
ty::Int(_) |
ty::Uint(_) |
ty::Float(_) |
ty::Error |
ty::Infer(_) |
ty::Param(..) |
ty::Bound(..) |
ty::Placeholder(..) |
ty::Never |
ty::Foreign(..) => return self
};
if self.sty == sty {
self
} else {
folder.tcx().mk_ty(sty)
}
}
fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
folder.fold_ty(*self)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
match self.sty {
ty::RawPtr(ref tm) => tm.visit_with(visitor),
ty::Array(typ, sz) => typ.visit_with(visitor) || sz.visit_with(visitor),
ty::Slice(typ) => typ.visit_with(visitor),
ty::Adt(_, substs) => substs.visit_with(visitor),
ty::Dynamic(ref trait_ty, ref reg) =>
trait_ty.visit_with(visitor) || reg.visit_with(visitor),
ty::Tuple(ts) => ts.visit_with(visitor),
ty::FnDef(_, substs) => substs.visit_with(visitor),
ty::FnPtr(ref f) => f.visit_with(visitor),
ty::Ref(r, ty, _) => r.visit_with(visitor) || ty.visit_with(visitor),
ty::Generator(_did, ref substs, _) => {
substs.visit_with(visitor)
}
ty::GeneratorWitness(ref types) => types.visit_with(visitor),
ty::Closure(_did, ref substs) => substs.visit_with(visitor),
ty::Projection(ref data) | ty::UnnormalizedProjection(ref data) => {
data.visit_with(visitor)
}
ty::Opaque(_, ref substs) => substs.visit_with(visitor),
ty::Bool |
ty::Char |
ty::Str |
ty::Int(_) |
ty::Uint(_) |
ty::Float(_) |
ty::Error |
ty::Infer(_) |
ty::Bound(..) |
ty::Placeholder(..) |
ty::Param(..) |
ty::Never |
ty::Foreign(..) => false,
}
}
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
visitor.visit_ty(self)
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::TypeAndMut<'tcx> {
ty, mutbl
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::GenSig<'tcx> {
yield_ty, return_ty
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::FnSig<'tcx> {
inputs_and_output, variadic, unsafety, abi
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::TraitRef<'tcx> { def_id, substs }
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ExistentialTraitRef<'tcx> { def_id, substs }
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ImplHeader<'tcx> {
impl_def_id,
self_ty,
trait_ref,
predicates,
}
}
impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
*self
}
fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
folder.fold_region(*self)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
false
}
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
visitor.visit_region(*self)
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ClosureSubsts<'tcx> {
substs,
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::GeneratorSubsts<'tcx> {
substs,
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::adjustment::Adjustment<'tcx> {
kind,
target,
}
}
EnumTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::adjustment::Adjust<'tcx> {
(ty::adjustment::Adjust::NeverToAny),
(ty::adjustment::Adjust::ReifyFnPointer),
(ty::adjustment::Adjust::UnsafeFnPointer),
(ty::adjustment::Adjust::ClosureFnPointer),
(ty::adjustment::Adjust::MutToConstPointer),
(ty::adjustment::Adjust::Unsize),
(ty::adjustment::Adjust::Deref)(a),
(ty::adjustment::Adjust::Borrow)(a),
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::adjustment::OverloadedDeref<'tcx> {
region, mutbl,
}
}
EnumTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::adjustment::AutoBorrow<'tcx> {
(ty::adjustment::AutoBorrow::Ref)(a, b),
(ty::adjustment::AutoBorrow::RawPtr)(m),
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::GenericPredicates<'tcx> {
parent, predicates
}
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::Predicate<'tcx>> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_predicates(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|p| p.visit_with(visitor))
}
}
EnumTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> {
(ty::Predicate::Trait)(a),
(ty::Predicate::Subtype)(a),
(ty::Predicate::RegionOutlives)(a),
(ty::Predicate::TypeOutlives)(a),
(ty::Predicate::Projection)(a),
(ty::Predicate::WellFormed)(a),
(ty::Predicate::ClosureKind)(a, b, c),
(ty::Predicate::ObjectSafe)(a),
(ty::Predicate::ConstEvaluatable)(a, b),
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ProjectionPredicate<'tcx> {
projection_ty, ty
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ExistentialProjection<'tcx> {
ty, substs, item_def_id
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ProjectionTy<'tcx> {
substs, item_def_id
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::InstantiatedPredicates<'tcx> {
predicates
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx, T> TypeFoldable<'tcx> for ty::ParamEnvAnd<'tcx, T> {
param_env, value
} where T: TypeFoldable<'tcx>
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::SubtypePredicate<'tcx> {
a_is_expected, a, b
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::TraitPredicate<'tcx> {
trait_ref
}
}
TupleStructTypeFoldableImpl! {
impl<'tcx,T,U> TypeFoldable<'tcx> for ty::OutlivesPredicate<T,U> {
a, b
} where T : TypeFoldable<'tcx>, U : TypeFoldable<'tcx>,
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::ClosureUpvar<'tcx> {
def, span, ty
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx, T> TypeFoldable<'tcx> for ty::error::ExpectedFound<T> {
expected, found
} where T: TypeFoldable<'tcx>
}
impl<'tcx, T: TypeFoldable<'tcx>, I: Idx> TypeFoldable<'tcx> for IndexVec<I, T> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
self.iter().map(|x| x.fold_with(folder)).collect()
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
EnumTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ty::error::TypeError<'tcx> {
(ty::error::TypeError::Mismatch),
(ty::error::TypeError::UnsafetyMismatch)(x),
(ty::error::TypeError::AbiMismatch)(x),
(ty::error::TypeError::Mutability),
(ty::error::TypeError::TupleSize)(x),
(ty::error::TypeError::FixedArraySize)(x),
(ty::error::TypeError::ArgCount),
(ty::error::TypeError::RegionsDoesNotOutlive)(a, b),
(ty::error::TypeError::RegionsPlaceholderMismatch),
(ty::error::TypeError::IntMismatch)(x),
(ty::error::TypeError::FloatMismatch)(x),
(ty::error::TypeError::Traits)(x),
(ty::error::TypeError::VariadicMismatch)(x),
(ty::error::TypeError::CyclicTy)(t),
(ty::error::TypeError::ProjectionMismatched)(x),
(ty::error::TypeError::ProjectionBoundsLength)(x),
(ty::error::TypeError::Sorts)(x),
(ty::error::TypeError::ExistentialMismatch)(x),
}
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::LazyConst<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let new = match self {
ty::LazyConst::Evaluated(v) => ty::LazyConst::Evaluated(v.fold_with(folder)),
ty::LazyConst::Unevaluated(def_id, substs) => {
ty::LazyConst::Unevaluated(*def_id, substs.fold_with(folder))
}
};
folder.tcx().intern_lazy_const(new)
}
fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
folder.fold_const(*self)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
match *self {
ty::LazyConst::Evaluated(c) => c.visit_with(visitor),
ty::LazyConst::Unevaluated(_, substs) => substs.visit_with(visitor),
}
}
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
visitor.visit_const(self)
}
}
impl<'tcx> TypeFoldable<'tcx> for ty::Const<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
let ty = self.ty.fold_with(folder);
let val = self.val.fold_with(folder);
ty::Const {
ty,
val
}
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.ty.visit_with(visitor) || self.val.visit_with(visitor)
}
}
impl<'tcx> TypeFoldable<'tcx> for ConstValue<'tcx> {
fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
*self
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
false
}
}
| 34.650735 | 96 | 0.550928 |
ac77f5df6d8298f83ca7f704c54110e5a1f3a941
| 143 |
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure().compile(&["engula/v1/engula.proto"], &["."])?;
Ok(())
}
| 28.6 | 75 | 0.552448 |
9cf52be2b220b9b4495f480c9aad5622c5049344
| 5,114 |
use reqwest::Client;
use roxmltree::Document;
use sha2::{Digest, Sha256};
use sqlx::PgPool;
use tracing::instrument;
use warp::{http::StatusCode, Rejection};
use crate::error::Error;
use crate::requests::{upload_file, youtube_streams, youtube_thumbnail, Stream};
use crate::vtubers::VTuber;
pub async fn publish_content(
body: String,
pool: PgPool,
client: Client,
) -> Result<StatusCode, Rejection> {
tracing::info!(name = "POST /api/pubsub/:pubsub", text = &body.as_str(),);
let doc = match Document::parse(&body) {
Ok(doc) => doc,
Err(_) => {
tracing::error!(err.msg = "failed to parse xml");
return Ok(StatusCode::BAD_REQUEST);
}
};
if let Some((vtuber_id, video_id)) = parse_modification(&doc) {
tracing::info!(action = "Update video", vtuber_id, video_id);
let streams = youtube_streams(&client, &[video_id.to_string()]).await?;
if streams.is_empty() {
tracing::error!(err.msg = "stream not found");
return Ok(StatusCode::BAD_REQUEST);
}
let thumbnail_url = upload_thumbnail(&streams[0].id, &client)
.await
.map(|filename| format!("https://taiwanv.linnil1.me/thumbnail/{}", filename));
update_youtube_stream(&streams[0], vtuber_id, thumbnail_url, &pool).await?;
return Ok(StatusCode::OK);
}
if let Some((video_id, vtuber_id)) = parse_deletion(&doc) {
tracing::info!(action = "Delete video", vtuber_id, video_id);
delete_schedule_stream(video_id, vtuber_id, &pool).await?;
return Ok(StatusCode::OK);
}
tracing::error!(err.msg = "unkown xml schema");
Ok(StatusCode::BAD_REQUEST)
}
pub fn parse_modification<'a>(doc: &'a Document) -> Option<(&'a str, &'a str)> {
let video_id = doc
.descendants()
.find(|n| n.tag_name().name() == "videoId")
.and_then(|n| n.text())?;
let channel_id = doc
.descendants()
.find(|n| n.tag_name().name() == "channelId")
.and_then(|n| n.text())?;
let vtuber_id = VTuber::find_by_youtube_channel_id(channel_id).map(|v| v.id)?;
Some((vtuber_id, video_id))
}
pub fn parse_deletion<'a>(doc: &'a Document) -> Option<(&'a str, &'a str)> {
let stream_id = doc
.descendants()
.find(|n| n.tag_name().name() == "deleted-entry")
.and_then(|n| n.attribute("ref"))
.and_then(|r| r.get("yt:video:".len()..))?;
let channel_id = doc
.descendants()
.find(|n| n.tag_name().name() == "uri")
.and_then(|n| n.text())
.and_then(|n| n.get("https://www.youtube.com/channel/".len()..))?;
let vtuber_id = VTuber::find_by_youtube_channel_id(channel_id).map(|v| v.id)?;
Some((stream_id, vtuber_id))
}
async fn upload_thumbnail(stream_id: &str, client: &Client) -> Option<String> {
let data = match youtube_thumbnail(stream_id, &client).await {
Ok(x) => x,
Err(e) => {
tracing::warn!(err = ?e, err.msg = "failed to upload thumbnail");
return None;
}
};
let content_sha256 = Sha256::digest(data.as_ref());
let filename = format!("{}.{}.jpg", stream_id, hex::encode(content_sha256));
match upload_file(&filename, data, "image/jpg", &client).await {
Ok(_) => Some(filename),
Err(e) => {
tracing::warn!(err = ?e, err.msg = "failed to upload thumbnail");
None
}
}
}
#[instrument(
name = "Update youtube stream",
skip(stream, vtuber_id, thumbnail_url, pool),
fields(db.table = "youtube_streams")
)]
async fn update_youtube_stream(
stream: &Stream,
vtuber_id: &str,
thumbnail_url: Option<String>,
pool: &PgPool,
) -> Result<(), Error> {
let _ = sqlx::query!(
r#"
insert into youtube_streams (stream_id, vtuber_id, title, status, thumbnail_url, schedule_time, start_time, end_time)
values ($1, $2, $3, $4, $5, $6, $7, $8)
on conflict (stream_id) do update
set (title, status, thumbnail_url, schedule_time, start_time, end_time)
= ($3, $4, coalesce($5, youtube_streams.thumbnail_url), $6, $7, $8)
"#,
stream.id,
vtuber_id,
stream.title,
stream.status: _,
thumbnail_url,
stream.schedule_time,
stream.start_time,
stream.end_time,
)
.execute(pool)
.await
.map_err(Error::Database)?;
Ok(())
}
#[instrument(
name = "Delete schedule stream",
skip(stream_id, vtuber_id, pool),
fields(db.table = "youtube_streams")
)]
async fn delete_schedule_stream(
stream_id: &str,
vtuber_id: &str,
pool: &PgPool,
) -> Result<(), Error> {
let _ = sqlx::query!(
r#"
delete from youtube_streams
where stream_id = $1
and vtuber_id = $2
and status = 'scheduled'::stream_status
"#,
stream_id,
vtuber_id,
)
.execute(pool)
.await
.map_err(Error::Database)?;
Ok(())
}
| 29.056818 | 129 | 0.577826 |
7522462ac8fbe1d4d7558bd6c07d7dd46236a6d7
| 189 |
fn main() {
use std::f32;
let e = f32::consts::E;
let f = e.tanh().atanh();
let abs_difference = f.abs_sub(e);
assert!(abs_difference <= f32::EPSILON);
}
| 17.181818 | 44 | 0.52381 |
671ed27a9aa47fdf3d6986948e13f6853e55b056
| 2,531 |
use dotenv::var;
use generic_get;
use generic_post;
use serde_json::{Error, Value};
use std::collections::HashMap;
pub fn details() -> Result<Value, &'static str> {
generic_get(format!(
"https://api.plivo.com/v1/Account/{}/",
&var("PLIVO_AUTH_ID").unwrap()
))
}
pub fn modify_name(name: String) -> Result<Value, &'static str> {
let chars_to_trim: &[char] = &['"'];
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("name", name.trim_matches(chars_to_trim));
generic_post(
format!(
"https://api.plivo.com/v1/Account/{}/",
&var("PLIVO_AUTH_ID").unwrap()
),
&map,
)
}
pub fn modify_address(address: String) -> Result<Value, &'static str> {
let chars_to_trim: &[char] = &['"'];
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("address", address.trim_matches(chars_to_trim));
generic_post(
format!(
"https://api.plivo.com/v1/Account/{}/",
&var("PLIVO_AUTH_ID").unwrap()
),
&map,
)
}
pub fn modify_city(city: String) -> Result<Value, &'static str> {
let chars_to_trim: &[char] = &['"'];
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("city", city.trim_matches(chars_to_trim));
generic_post(
format!(
"https://api.plivo.com/v1/Account/{}/",
&var("PLIVO_AUTH_ID").unwrap()
),
&map,
)
}
pub fn create_subaccount(name: String, enabled: String) -> Result<Value, &'static str> {
let chars_to_trim: &[char] = &['"'];
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("name", name.trim_matches(chars_to_trim));
map.insert("enabled", enabled.trim_matches(chars_to_trim));
generic_post(
format!(
"https://api.plivo.com/v1/Account/{}/Subaccount/",
&var("PLIVO_AUTH_ID").unwrap()
),
&map,
)
}
pub fn modify_subaccount(
name: String,
enabled: String,
subauth_id: String,
) -> Result<Value, &'static str> {
let chars_to_trim: &[char] = &['"'];
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("name", name.trim_matches(chars_to_trim));
map.insert("enabled", enabled.trim_matches(chars_to_trim));
generic_post(
format!(
"https://api.plivo.com/v1/Account/{AUTH}/Subaccount/{SUBAUTH}",
AUTH = &var("PLIVO_AUTH_ID").unwrap(),
SUBAUTH = subauth_id.trim_matches(chars_to_trim)
),
&map,
)
}
| 30.130952 | 88 | 0.578032 |
ef766629ab06bf764f02c4f254da77a72805e1ca
| 5,254 |
// Copyright (c) 2018-2020 MobileCoin Inc.
//! Serves client-to-node gRPC requests.
use crate::{
consensus_service::ProposeTxCallback,
counters,
grpc_error::ConsensusGrpcError,
tx_manager::{TxManager, TxManagerError},
};
use grpcio::{RpcContext, UnarySink};
use mc_attest_api::attest::Message;
use mc_common::logger::{log, Logger};
use mc_consensus_api::{
consensus_client_grpc::ConsensusClientApi, consensus_common::ProposeTxResponse,
};
use mc_consensus_enclave::ConsensusEnclaveProxy;
use mc_ledger_db::Ledger;
use mc_transaction_core::validation::TransactionValidationError;
use mc_util_grpc::{rpc_logger, send_result};
use mc_util_metrics::{self, SVC_COUNTERS};
use std::sync::Arc;
/// Maximum number of pending values for consensus service before rejecting add_transaction requests.
const PENDING_LIMIT: i64 = 500;
#[derive(Clone)]
pub struct ClientApiService<E: ConsensusEnclaveProxy, L: Ledger + Clone> {
enclave: E,
scp_client_value_sender: ProposeTxCallback,
ledger: L,
tx_manager: TxManager<E, L>,
is_serving_fn: Arc<(dyn Fn() -> bool + Sync + Send)>,
logger: Logger,
}
impl<E: ConsensusEnclaveProxy, L: Ledger + Clone> ClientApiService<E, L> {
pub fn new(
enclave: E,
scp_client_value_sender: ProposeTxCallback,
ledger: L,
tx_manager: TxManager<E, L>,
is_serving_fn: Arc<(dyn Fn() -> bool + Sync + Send)>,
logger: Logger,
) -> Self {
Self {
enclave,
scp_client_value_sender,
tx_manager,
ledger,
is_serving_fn,
logger,
}
}
fn real_client_tx_propose(
&mut self,
request: Message,
logger: &Logger,
) -> Result<ProposeTxResponse, ConsensusGrpcError> {
counters::ADD_TX_INITIATED.inc();
if counters::CUR_NUM_PENDING_VALUES.get() > PENDING_LIMIT {
self.enclave.client_discard_message(request.into())?;
log::trace!(
logger,
"Ignoring add transaction call, node is over capacity."
);
return Err(ConsensusGrpcError::OverCapacity);
}
// Check if node is accepting requests.
if !(self.is_serving_fn)() {
self.enclave.client_discard_message(request.into())?;
log::info!(
logger,
"Ignoring add transaction call, not currently serving requests."
);
return Err(ConsensusGrpcError::NotServing);
}
let tx_context = self.enclave.client_tx_propose(request.into())?;
let tx_hash = tx_context.tx_hash;
match self.tx_manager.insert_proposed_tx(tx_context) {
Ok(tx_context) => {
// Submit for consideration in next SCP slot.
(*self.scp_client_value_sender)(*tx_context.tx_hash(), None, None);
counters::ADD_TX.inc();
// Return success.
Ok(ProposeTxResponse::new())
}
Err(TxManagerError::TransactionValidation(err)) => {
// These errors are common, so only trace them
if err == TransactionValidationError::TombstoneBlockExceeded
|| err == TransactionValidationError::ContainsSpentKeyImage
{
log::trace!(
logger,
"Error validating transaction {tx_hash}: {err}",
tx_hash = tx_hash.to_string(),
err = format!("{:?}", err)
);
} else {
log::debug!(
logger,
"Error validating transaction {tx_hash}: {err}",
tx_hash = tx_hash.to_string(),
err = format!("{:?}", err)
);
}
counters::TX_VALIDATION_ERROR_COUNTER.inc(&format!("{:?}", err));
Err(err.into())
}
Err(err) => {
log::info!(
logger,
"tx_propose failed for {tx_hash}: {err}",
tx_hash = tx_hash.to_string(),
err = format!("{:?}", err)
);
Err(err.into())
}
}
}
}
impl<E: ConsensusEnclaveProxy, L: Ledger + Clone> ConsensusClientApi for ClientApiService<E, L> {
fn client_tx_propose(
&mut self,
ctx: RpcContext,
request: Message,
sink: UnarySink<ProposeTxResponse>,
) {
let _timer = SVC_COUNTERS.req(&ctx);
mc_common::logger::scoped_global_logger(&rpc_logger(&ctx, &self.logger), |logger| {
send_result(
ctx,
sink,
self.real_client_tx_propose(request, &logger)
.or_else(ConsensusGrpcError::into)
.and_then(|mut resp| {
resp.set_num_blocks(
self.ledger.num_blocks().map_err(ConsensusGrpcError::from)?,
);
Ok(resp)
}),
&logger,
)
});
}
}
| 33.044025 | 101 | 0.539018 |
565e34381501c0a73860bdecb59c1316e53b5a85
| 2,238 |
use std::collections::HashSet;
use http::{header::HeaderName, HeaderMap};
use crate::{Endpoint, IntoResponse, Middleware, Request, Response, Result};
/// Middleware for propagate a header from the request to the response.
#[derive(Default)]
pub struct PropagateHeader {
headers: HashSet<HeaderName>,
}
impl PropagateHeader {
/// Create new `PropagateHeader` middleware.
#[must_use]
pub fn new() -> Self {
Default::default()
}
/// Append a header.
#[must_use]
pub fn header<K>(mut self, key: K) -> Self
where
K: TryInto<HeaderName>,
{
if let Ok(key) = key.try_into() {
self.headers.insert(key);
}
self
}
}
impl<E: Endpoint> Middleware<E> for PropagateHeader {
type Output = PropagateHeaderEndpoint<E>;
fn transform(&self, ep: E) -> Self::Output {
PropagateHeaderEndpoint {
inner: ep,
headers: self.headers.clone(),
}
}
}
/// Endpoint for PropagateHeader middleware.
pub struct PropagateHeaderEndpoint<E> {
inner: E,
headers: HashSet<HeaderName>,
}
#[async_trait::async_trait]
impl<E: Endpoint> Endpoint for PropagateHeaderEndpoint<E> {
type Output = Response;
async fn call(&self, req: Request) -> Result<Self::Output> {
let mut headers = HeaderMap::new();
for header in &self.headers {
for value in req.headers().get_all(header) {
headers.append(header, value.clone());
}
}
let mut resp = self.inner.call(req).await?.into_response();
resp.headers_mut().extend(headers);
Ok(resp)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{handler, EndpointExt};
#[tokio::test]
async fn test_propagate_header() {
#[handler(internal)]
fn index() {}
let resp = index
.with(PropagateHeader::new().header("x-request-id"))
.call(Request::builder().header("x-request-id", "100").finish())
.await
.unwrap();
assert_eq!(
resp.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok()),
Some("100")
);
}
}
| 24.064516 | 76 | 0.574173 |
8a36aab924914e70fe6071e9997337b1d6498a0b
| 4,597 |
//! Allow your users to perform actions by pressing a button.
//!
//! A [`Button`] has some local [`State`].
use crate::{css, Background, Bus, Css, Element, Length, Padding, Widget};
pub use iced_style::button::{Style, StyleSheet};
use dodrio::bumpalo;
/// A generic widget that produces a message when pressed.
///
/// ```
/// # use iced_web::{button, Button, Text};
/// #
/// enum Message {
/// ButtonPressed,
/// }
///
/// let mut state = button::State::new();
/// let button = Button::new(&mut state, Text::new("Press me!"))
/// .on_press(Message::ButtonPressed);
/// ```
#[allow(missing_debug_implementations)]
pub struct Button<'a, Message> {
content: Element<'a, Message>,
on_press: Option<Message>,
width: Length,
#[allow(dead_code)]
height: Length,
min_width: u32,
#[allow(dead_code)]
min_height: u32,
padding: Padding,
style: Box<dyn StyleSheet>,
}
impl<'a, Message> Button<'a, Message> {
/// Creates a new [`Button`] with some local [`State`] and the given
/// content.
pub fn new<E>(_state: &'a mut State, content: E) -> Self
where
E: Into<Element<'a, Message>>,
{
Button {
content: content.into(),
on_press: None,
width: Length::Shrink,
height: Length::Shrink,
min_width: 0,
min_height: 0,
padding: Padding::new(5),
style: Default::default(),
}
}
/// Sets the width of the [`Button`].
pub fn width(mut self, width: Length) -> Self {
self.width = width;
self
}
/// Sets the height of the [`Button`].
pub fn height(mut self, height: Length) -> Self {
self.height = height;
self
}
/// Sets the minimum width of the [`Button`].
pub fn min_width(mut self, min_width: u32) -> Self {
self.min_width = min_width;
self
}
/// Sets the minimum height of the [`Button`].
pub fn min_height(mut self, min_height: u32) -> Self {
self.min_height = min_height;
self
}
/// Sets the [`Padding`] of the [`Button`].
pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
self.padding = padding.into();
self
}
/// Sets the style of the [`Button`].
pub fn style(mut self, style: impl Into<Box<dyn StyleSheet>>) -> Self {
self.style = style.into();
self
}
/// Sets the message that will be produced when the [`Button`] is pressed.
pub fn on_press(mut self, msg: Message) -> Self {
self.on_press = Some(msg);
self
}
}
/// The local state of a [`Button`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct State;
impl State {
/// Creates a new [`State`].
pub fn new() -> State {
State::default()
}
}
impl<'a, Message> Widget<Message> for Button<'a, Message>
where
Message: 'static + Clone,
{
fn node<'b>(
&self,
bump: &'b bumpalo::Bump,
bus: &Bus<Message>,
style_sheet: &mut Css<'b>,
) -> dodrio::Node<'b> {
use dodrio::builder::*;
// TODO: State-based styling
let style = self.style.active();
let background = match style.background {
None => String::from("none"),
Some(background) => match background {
Background::Color(color) => css::color(color),
},
};
let mut node = button(bump)
.attr(
"style",
bumpalo::format!(
in bump,
"background: {}; border-radius: {}px; width:{}; \
min-width: {}; color: {}; padding: {}",
background,
style.border_radius,
css::length(self.width),
css::min_length(self.min_width),
css::color(style.text_color),
css::padding(self.padding)
)
.into_bump_str(),
)
.children(vec![self.content.node(bump, bus, style_sheet)]);
if let Some(on_press) = self.on_press.clone() {
let event_bus = bus.clone();
node = node.on("click", move |_root, _vdom, _event| {
event_bus.publish(on_press.clone());
});
}
node.finish()
}
}
impl<'a, Message> From<Button<'a, Message>> for Element<'a, Message>
where
Message: 'static + Clone,
{
fn from(button: Button<'a, Message>) -> Element<'a, Message> {
Element::new(button)
}
}
| 27.041176 | 78 | 0.531869 |
e25c3ccfcd980d36b67d63a0e7cb885ef5332792
| 1,649 |
// 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.
// Tests the behavior of various Kleene operators in macros with respect to `?` terminals. In
// particular, `?` in the position of a separator and of a Kleene operator is tested.
#![feature(macro_at_most_once_rep)]
// should match `` and `a`
macro_rules! foo {
($(a)?) => {}
}
macro_rules! baz {
($(a),?) => {} //~ ERROR `?` macro repetition does not allow a separator
}
// should match `+` and `a+`
macro_rules! barplus {
($(a)?+) => {}
}
// should match `*` and `a*`
macro_rules! barstar {
($(a)?*) => {}
}
pub fn main() {
foo!(a?a?a); //~ ERROR no rules expected the token `?`
foo!(a?a); //~ ERROR no rules expected the token `?`
foo!(a?); //~ ERROR no rules expected the token `?`
barplus!(); //~ ERROR unexpected end of macro invocation
barstar!(); //~ ERROR unexpected end of macro invocation
barplus!(a?); //~ ERROR no rules expected the token `?`
barplus!(a); //~ ERROR unexpected end of macro invocation
barstar!(a?); //~ ERROR no rules expected the token `?`
barstar!(a); //~ ERROR unexpected end of macro invocation
barplus!(+); // ok
barstar!(*); // ok
barplus!(a+); // ok
barstar!(a*); // ok
}
| 32.98 | 93 | 0.639782 |
ed337b0e07fea235f0045579248d956bb3f06962
| 2,048 |
pub mod conn;
pub mod machine;
pub mod utils;
#[macro_use]
extern crate log;
extern crate bincode;
extern crate chrono;
extern crate common;
extern crate log4rs;
extern crate log_panics;
extern crate rand;
extern crate signal_hook;
extern crate simple_error;
extern crate sysfs_gpio;
use std::sync;
use std::thread;
use std::time;
fn main() {
println!("Starting...");
let signals = signal_hook::iterator::Signals::new(&[signal_hook::SIGINT, signal_hook::SIGTERM])
.expect("Unable to register signal handler.");
match utils::init_logger() {
Err(e) => {
println!("Unable to initialize logger: {}", e);
println!("Exiting...");
std::process::exit(1);
}
_ => {}
}
info!("Initializing configuration...");
let config = match utils::Config::from_env() {
Ok(res) => res,
Err(e) => {
error!("{}", e);
error!("Exiting...");
std::process::exit(2);
}
};
info!("Initializing GPIO...");
let mut machine = machine::Machine::new();
machine.export();
let machine_mutex = sync::Arc::new(sync::Mutex::new(machine));
info!("Initializing session pool on {} port...", config.port);
let mut session_pool = conn::SessionPool::new(config, machine_mutex.clone());
thread::spawn(move || {
match session_pool.listen() {
Ok(_) => {
info!("Exiting...");
std::process::exit(1);
}
Err(e) => {
error!("{}", e);
error!("Exiting...");
std::process::exit(3);
}
};
});
info!("Starting event loop...");
loop {
for sig in signals.pending() {
info!("Received signal {:?}, exiting...", sig);
let mut machine = machine_mutex.try_lock().expect("Failed to lock GPIO");
machine.unexport();
std::process::exit(sig);
}
thread::sleep(time::Duration::from_millis(200));
}
}
| 26.597403 | 99 | 0.536621 |
1eef1ed75294164770ec01697c2cc0008f6e376b
| 2,914 |
use std::cmp::max;
use crate::{
app::{
color::ColorTheme,
command::{Command, CommandHandler, NO_COMMANDS},
},
clock::ticker::TickHandler,
game::game_item::GameItem,
view::{
coordinates::Coordinates, render::Renderable, renderer::Renderer, util::chars_width,
viewport::Viewport,
},
};
use tui::{
style::{Color, Style},
text::Span,
};
const MARGIN_LENGTH: u8 = 1;
const HEIGHT: u8 = 2;
static TEXT_HEADER: &str = "Score";
pub struct Score {
coordinates: Coordinates,
score: u32,
}
impl CommandHandler for Score {
fn handle_command(&mut self, command: Command) -> Vec<Command> {
match command {
Command::IncreaseScore(number) => {
self.score += number;
}
Command::UiViewportInitializedOrChanged(viewport) => {
self.align(viewport);
}
_ => (),
}
NO_COMMANDS
}
}
impl Default for Score {
fn default() -> Self {
Self::new(Coordinates::default()) // Will be re-aligned during `render()`
}
}
impl GameItem for Score {}
impl Renderable for Score {
fn render(&self, renderer: &mut Renderer) {
let (x, y) = self.coordinates.as_tuple();
let width = self.width();
let header_offset = width - chars_width(TEXT_HEADER);
let header_spans = vec![Span::styled(
TEXT_HEADER,
Style::default().fg(Color::from(ColorTheme::ScoreHeader)),
)];
let header_coordinates = Coordinates::new(x + header_offset, y + 1);
let points_offset = width - chars_width(self.text().as_str());
let points_spans = vec![Span::styled(
self.text(),
Style::default().fg(Color::from(ColorTheme::ScorePoints)),
)];
let points_coordinates = Coordinates::new(x + points_offset, y);
let viewport = self.viewport();
renderer.render_spans(viewport.with_coordinates(points_coordinates), points_spans);
renderer.render_spans(viewport.with_coordinates(header_coordinates), header_spans);
}
fn viewport(&self) -> Viewport {
Viewport::new_with_coordinates(self.width(), HEIGHT, self.coordinates)
}
}
impl TickHandler for Score {}
impl Score {
fn new(coordinates: Coordinates) -> Self {
Self {
coordinates,
score: 0,
}
}
fn align(&mut self, viewport: Viewport) {
let (x, _) = viewport.top_right().as_tuple();
let (_, y) = viewport.bottom_left().as_tuple();
let x = x - self.width() + 1 - MARGIN_LENGTH;
let y = y + i8::try_from(MARGIN_LENGTH).unwrap();
self.coordinates = Coordinates::new(x, y);
}
fn text(&self) -> String {
self.score.to_string()
}
fn width(&self) -> u8 {
max(chars_width(TEXT_HEADER), chars_width(self.text().as_str()))
}
}
| 27.233645 | 92 | 0.588195 |
0e4436fe1632f7742458f8afdbcfa9b15fb3593b
| 5,697 |
// Copyright 2018 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.
// run-rustfix
#![allow(unused)]
#![deny(explicit_outlives_requirements)]
use std::fmt::{Debug, Display};
// Programmatically generated examples!
//
// Exercise outlives bounds for each of the following parameter/position
// combinations—
//
// • one generic parameter (T) bound inline
// • one parameter (T) with a where clause
// • two parameters (T and U), both bound inline
// • two paramters (T and U), one bound inline, one with a where clause
// • two parameters (T and U), both with where clauses
//
// —and for every permutation of 0, 1, or 2 lifetimes to outlive and 0 or 1
// trait bounds distributed among said parameters (subject to no where clause
// being empty and the struct having at least one lifetime).
struct TeeOutlivesAy<'a, T: 'a> {
//~^ ERROR outlives requirements can be inferred
tee: &'a T
}
struct TeeOutlivesAyIsDebug<'a, T: 'a + Debug> {
//~^ ERROR outlives requirements can be inferred
tee: &'a T
}
struct TeeIsDebugOutlivesAy<'a, T: Debug + 'a> {
//~^ ERROR outlives requirements can be inferred
tee: &'a T
}
struct TeeOutlivesAyBee<'a, 'b, T: 'a + 'b> {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T
}
struct TeeOutlivesAyBeeIsDebug<'a, 'b, T: 'a + 'b + Debug> {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T
}
struct TeeIsDebugOutlivesAyBee<'a, 'b, T: Debug + 'a + 'b> {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T
}
struct TeeWhereOutlivesAy<'a, T> where T: 'a {
//~^ ERROR outlives requirements can be inferred
tee: &'a T
}
struct TeeWhereOutlivesAyIsDebug<'a, T> where T: 'a + Debug {
//~^ ERROR outlives requirements can be inferred
tee: &'a T
}
struct TeeWhereIsDebugOutlivesAy<'a, T> where T: Debug + 'a {
//~^ ERROR outlives requirements can be inferred
tee: &'a T
}
struct TeeWhereOutlivesAyBee<'a, 'b, T> where T: 'a + 'b {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T
}
struct TeeWhereOutlivesAyBeeIsDebug<'a, 'b, T> where T: 'a + 'b + Debug {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T
}
struct TeeWhereIsDebugOutlivesAyBee<'a, 'b, T> where T: Debug + 'a + 'b {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T
}
struct TeeYooOutlivesAy<'a, T, U: 'a> {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a U
}
struct TeeYooOutlivesAyIsDebug<'a, T, U: 'a + Debug> {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a U
}
struct TeeYooIsDebugOutlivesAy<'a, T, U: Debug + 'a> {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a U
}
struct TeeOutlivesAyYooIsDebug<'a, T: 'a, U: Debug> {
//~^ ERROR outlives requirements can be inferred
tee: &'a T,
yoo: U
}
struct TeeYooOutlivesAyBee<'a, 'b, T, U: 'a + 'b> {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a &'b U
}
struct TeeYooOutlivesAyBeeIsDebug<'a, 'b, T, U: 'a + 'b + Debug> {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a &'b U
}
struct TeeYooIsDebugOutlivesAyBee<'a, 'b, T, U: Debug + 'a + 'b> {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a &'b U
}
struct TeeOutlivesAyBeeYooIsDebug<'a, 'b, T: 'a + 'b, U: Debug> {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T,
yoo: U
}
struct TeeYooWhereOutlivesAy<'a, T, U> where U: 'a {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a U
}
struct TeeYooWhereOutlivesAyIsDebug<'a, T, U> where U: 'a + Debug {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a U
}
struct TeeYooWhereIsDebugOutlivesAy<'a, T, U> where U: Debug + 'a {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a U
}
struct TeeOutlivesAyYooWhereIsDebug<'a, T: 'a, U> where U: Debug {
//~^ ERROR outlives requirements can be inferred
tee: &'a T,
yoo: U
}
struct TeeYooWhereOutlivesAyBee<'a, 'b, T, U> where U: 'a + 'b {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a &'b U
}
struct TeeYooWhereOutlivesAyBeeIsDebug<'a, 'b, T, U> where U: 'a + 'b + Debug {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a &'b U
}
struct TeeYooWhereIsDebugOutlivesAyBee<'a, 'b, T, U> where U: Debug + 'a + 'b {
//~^ ERROR outlives requirements can be inferred
tee: T,
yoo: &'a &'b U
}
struct TeeOutlivesAyBeeYooWhereIsDebug<'a, 'b, T: 'a + 'b, U> where U: Debug {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T,
yoo: U
}
struct TeeWhereOutlivesAyYooWhereIsDebug<'a, T, U> where T: 'a, U: Debug {
//~^ ERROR outlives requirements can be inferred
tee: &'a T,
yoo: U
}
struct TeeWhereOutlivesAyBeeYooWhereIsDebug<'a, 'b, T, U> where T: 'a + 'b, U: Debug {
//~^ ERROR outlives requirements can be inferred
tee: &'a &'b T,
yoo: U
}
// But outlives inference for 'static lifetimes is under a separate
// feature-gate for now
// (https://github.com/rust-lang/rust/issues/44493#issuecomment-407846046).
struct StaticRef<T: 'static> {
field: &'static T
}
fn main() {}
| 26.746479 | 86 | 0.645603 |
ed6deed44b3603e3db68486881c7e653344ca6e6
| 14,937 |
// 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)]
extern crate tokio;
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
use google_driveactivity2::{api, Error};
mod client;
use client::{InvalidOptionsError, CLIError, 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 serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::DriveActivityHub,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
async fn _activity_query(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"ancestor-name" => Some(("ancestorName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"item-name" => Some(("itemName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"page-size" => Some(("pageSize", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"page-token" => Some(("pageToken", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["ancestor-name", "filter", "item-name", "page-size", "page-token"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::QueryDriveActivityRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.activity().query(request);
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 {
_ => {
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 } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
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().await,
_ => 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(())
}
}
}
}
async 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() {
("activity", Some(opt)) => {
match opt.subcommand() {
("query", Some(opt)) => {
call_result = self._activity_query(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("activity".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
async fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match client::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 client::application_secret_from_directory(&config_dir, "driveactivity2-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 = yup_oauth2::InstalledFlowAuthenticator::builder(
secret,
yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
).persist_tokens_to_disk(format!("{}/driveactivity2", config_dir)).build().await.unwrap();
let client = hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots());
let engine = Engine {
opt: opt,
hub: api::DriveActivityHub::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).await {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
async fn doit(&self) -> Result<(), DoitError> {
match self._doit(false).await {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
#[tokio::main]
async fn main() {
let mut exit_status = 0i32;
let arg_data = [
("activity", "methods: 'query'", vec![
("query",
Some(r##"Query past activity in Google Drive."##),
"Details at http://byron.github.io/google-apis-rs/google_driveactivity2_cli/activity_query",
vec![
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(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("driveactivity2")
.author("Sebastian Thiel <[email protected]>")
.version("2.0.4+20210326")
.about("Provides a historical view of activity in Google Drive.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_driveactivity2_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.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("Debug print all errors")
.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).await {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit().await {
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);
}
| 44.192308 | 526 | 0.476669 |
72241604bc2148308d0f0c44d616f145a100223c
| 13,313 |
/// Macros for use within the Artichoke VM.
///
/// This module contains macros for working with interpreters and Ruby values.
/// This module should be included first in `lib.rs` with the `#[macro_use]`
/// attribute, which makes all macros available for all modules in this crate.
///
/// Macros that relate to manipulating the underlying mruby VM are exported.
/// Log a fatal error to stderr and suppress all errors.
///
/// This macro accepts a format string and arguments similar to [`write!`].
macro_rules! emit_fatal_warning {
($($arg:tt)+) => {{
use ::std::io::Write;
// Something bad, terrible, and unexpected has happened.
//
// Suppress errors from logging to stderr because this function may being
// called when there are foreign C frames in the stack and panics are
// either undefined behavior or will result in an abort.
//
// Ensure the returned error is dropped so we don't leave anything on
// the stack in the event of a foreign unwind.
let maybe_err = ::std::write!(::std::io::stderr(), "fatal[artichoke-backend]: ");
drop(maybe_err);
let maybe_err = ::std::writeln!(::std::io::stderr(), $($arg)+);
drop(maybe_err);
}};
}
/// Extract an [`Artichoke`] instance from the userdata on a [`sys::mrb_state`].
///
/// If there is an error when extracting the Rust wrapper around the
/// interpreter, return `nil` or a user-provided default.
///
/// This macro calls `unsafe` functions.
///
/// [`Artichoke`]: crate::Artichoke
/// [`sys::mrb_state`]: crate::sys::mrb_state
#[macro_export]
macro_rules! unwrap_interpreter {
($mrb:expr, to => $to:ident, or_else = ()) => {
let mut interp = if let Ok(interp) = $crate::ffi::from_user_data($mrb) {
interp
} else {
return;
};
let mut arena = if let Ok(arena) =
$crate::gc::MrbGarbageCollection::create_arena_savepoint(&mut interp)
{
arena
} else {
return;
};
#[allow(unused_mut)]
let mut $to = $crate::Guard::new(arena.interp());
};
($mrb:expr, to => $to:ident, or_else = $default:expr) => {
let mut interp = if let Ok(interp) = $crate::ffi::from_user_data($mrb) {
interp
} else {
return $default;
};
let mut arena = if let Ok(arena) =
$crate::gc::MrbGarbageCollection::create_arena_savepoint(&mut interp)
{
arena
} else {
return $default;
};
#[allow(unused_mut)]
let mut $to = $crate::Guard::new(arena.interp());
};
($mrb:expr, to => $to:ident) => {
unwrap_interpreter!($mrb, to => $to, or_else = $crate::sys::mrb_sys_nil_value())
};
}
#[doc(hidden)]
pub mod argspec {
use std::ffi::CStr;
pub const NONE: &CStr = qed::const_cstr_from_str!("\0");
pub const REQ1: &CStr = qed::const_cstr_from_str!("o\0");
pub const OPT1: &CStr = qed::const_cstr_from_str!("|o\0");
pub const REQ1_OPT1: &CStr = qed::const_cstr_from_str!("o|o\0");
pub const REQ1_OPT2: &CStr = qed::const_cstr_from_str!("o|oo\0");
pub const REQ1_REQBLOCK: &CStr = qed::const_cstr_from_str!("o&\0");
pub const REQ1_REQBLOCK_OPT1: &CStr = qed::const_cstr_from_str!("o&|o?\0");
pub const REQ2: &CStr = qed::const_cstr_from_str!("oo\0");
pub const OPT2: &CStr = qed::const_cstr_from_str!("|oo\0");
pub const OPT2_OPTBLOCK: &CStr = qed::const_cstr_from_str!("&|o?o?\0");
pub const REQ2_OPT1: &CStr = qed::const_cstr_from_str!("oo|o\0");
pub const REST: &CStr = qed::const_cstr_from_str!("*\0");
}
/// Extract [`sys::mrb_value`]s from a [`sys::mrb_state`] to adapt a C
/// entry point to a Rust implementation of a Ruby function.
///
/// This macro exists because the mruby VM [does not validate argspecs] attached
/// to native functions.
///
/// This macro calls `unsafe` functions.
///
/// [`sys::mrb_value`]: crate::sys::mrb_value
/// [`sys::mrb_state`]: crate::sys::mrb_state
/// [does not validate argspecs]: https://github.com/mruby/mruby/issues/4688
#[macro_export]
macro_rules! mrb_get_args {
($mrb:expr, none) => {{
$crate::sys::mrb_get_args($mrb, $crate::macros::argspec::NONE.as_ptr());
}};
($mrb:expr, required = 1) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args($mrb, $crate::macros::argspec::REQ1.as_ptr(), req1.as_mut_ptr());
match argc {
1 => req1.assume_init(),
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, optional = 1) => {{
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args($mrb, $crate::macros::argspec::OPT1.as_ptr(), opt1.as_mut_ptr());
match argc {
1 => {
let opt1 = opt1.assume_init();
Some(opt1)
}
0 => None,
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, required = 1, optional = 1) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REQ1_OPT1.as_ptr(),
req1.as_mut_ptr(),
opt1.as_mut_ptr(),
);
match argc {
2 => {
let req1 = req1.assume_init();
let opt1 = opt1.assume_init();
(req1, Some(opt1))
}
1 => {
let req1 = req1.assume_init();
(req1, None)
}
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, required = 1, optional = 2) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REQ1_OPT2.as_ptr(),
req1.as_mut_ptr(),
opt1.as_mut_ptr(),
opt2.as_mut_ptr(),
);
match argc {
3 => {
let req1 = req1.assume_init();
let opt1 = opt1.assume_init();
let opt2 = opt2.assume_init();
(req1, Some(opt1), Some(opt2))
}
2 => {
let req1 = req1.assume_init();
let opt1 = opt1.assume_init();
(req1, Some(opt1), None)
}
1 => {
let req1 = req1.assume_init();
(req1, None, None)
}
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, required = 1, &block) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut block = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REQ1_REQBLOCK.as_ptr(),
req1.as_mut_ptr(),
block.as_mut_ptr(),
);
match argc {
2 | 1 => {
let req1 = req1.assume_init();
let block = block.assume_init();
(req1, $crate::block::Block::new(block))
}
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, required = 1, optional = 1, &block) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut has_opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_bool>::uninit();
let mut block = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REQ1_REQBLOCK_OPT1.as_ptr(),
req1.as_mut_ptr(),
block.as_mut_ptr(),
opt1.as_mut_ptr(),
has_opt1.as_mut_ptr(),
);
let has_opt1 = has_opt1.assume_init() != 0;
match argc {
3 => {
let req1 = req1.assume_init();
let opt1 = opt1.assume_init();
let block = block.assume_init();
(req1, Some(opt1), $crate::block::Block::new(block))
}
2 => {
let req1 = req1.assume_init();
let opt1 = if has_opt1 { Some(opt1.assume_init()) } else { None };
let block = block.assume_init();
(req1, opt1, $crate::block::Block::new(block))
}
1 => {
let req1 = req1.assume_init();
let block = block.assume_init();
(req1, None, $crate::block::Block::new(block))
}
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, required = 2) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut req2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REQ2.as_ptr(),
req1.as_mut_ptr(),
req2.as_mut_ptr(),
);
match argc {
2 => {
let req1 = req1.assume_init();
let req2 = req2.assume_init();
(req1, req2)
}
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, optional = 2) => {{
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::OPT2.as_ptr(),
opt1.as_mut_ptr(),
opt2.as_mut_ptr(),
);
match argc {
2 => {
let opt1 = opt1.assume_init();
let opt2 = opt2.assume_init();
(Some(opt1), Some(opt2))
}
1 => {
let opt1 = opt1.assume_init();
(Some(opt1), None)
}
0 => (None, None),
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, optional = 2, &block) => {{
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut has_opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_bool>::uninit();
let mut opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut has_opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_bool>::uninit();
let mut block = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
$crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::OPT2_OPTBLOCK.as_ptr(),
block.as_mut_ptr(),
opt1.as_mut_ptr(),
has_opt1.as_mut_ptr(),
opt2.as_mut_ptr(),
has_opt2.as_mut_ptr(),
);
let has_opt1 = has_opt1.assume_init() != 0;
let has_opt2 = has_opt2.assume_init() != 0;
let opt1 = if has_opt1 { Some(opt1.assume_init()) } else { None };
let opt2 = if has_opt2 { Some(opt2.assume_init()) } else { None };
let block = block.assume_init();
(opt1, opt2, $crate::block::Block::new(block))
}};
($mrb:expr, required = 2, optional = 1) => {{
let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut req2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
let argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REQ2_OPT1.as_ptr(),
req1.as_mut_ptr(),
req2.as_mut_ptr(),
opt1.as_mut_ptr(),
);
match argc {
3 => {
let req1 = req1.assume_init();
let req2 = req2.assume_init();
let opt1 = opt1.assume_init();
(req1, req2, Some(opt1))
}
2 => {
let req1 = req1.assume_init();
let req2 = req2.assume_init();
(req1, req2, None)
}
_ => unreachable!("mrb_get_args should have raised"),
}
}};
($mrb:expr, *args) => {{
let mut args = std::mem::MaybeUninit::<*const $crate::sys::mrb_value>::uninit();
let mut count = std::mem::MaybeUninit::<usize>::uninit();
let _argc = $crate::sys::mrb_get_args(
$mrb,
$crate::macros::argspec::REST.as_ptr(),
args.as_mut_ptr(),
count.as_mut_ptr(),
);
std::slice::from_raw_parts(args.assume_init(), count.assume_init())
}};
}
| 39.271386 | 110 | 0.527079 |
f4af3d386d09f5a883df8b161109a2f19f013542
| 3,868 |
//! Modules for events in the *m.key.verification* namespace.
//!
//! This module also contains types shared by events in its child namespaces.
use serde::{Deserialize, Serialize};
use strum::{Display, EnumString};
pub mod accept;
pub mod cancel;
pub mod key;
pub mod mac;
pub mod request;
pub mod start;
/// A hash algorithm.
#[derive(Clone, Copy, Debug, PartialEq, Display, EnumString, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum HashAlgorithm {
/// The SHA256 hash algorithm.
Sha256,
}
/// A key agreement protocol.
#[derive(Clone, Copy, Debug, PartialEq, Display, EnumString, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum KeyAgreementProtocol {
/// The [Curve25519](https://cr.yp.to/ecdh.html) key agreement protocol.
Curve25519,
/// The Curve25519 key agreement protocol with check for public keys.
Curve25519HkdfSha256,
}
/// A message authentication code algorithm.
#[derive(Clone, Copy, Debug, PartialEq, Display, EnumString, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum MessageAuthenticationCode {
/// The HKDF-HMAC-SHA256 MAC.
HkdfHmacSha256,
/// The HMAC-SHA256 MAC.
HmacSha256,
}
/// A Short Authentication String method.
#[derive(Clone, Copy, Debug, PartialEq, Display, EnumString, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ShortAuthenticationString {
/// The decimal method.
Decimal,
/// The emoji method.
Emoji,
}
/// A Short Authentication String (SAS) verification method.
#[derive(Clone, Copy, Debug, PartialEq, Display, EnumString, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub enum VerificationMethod {
/// The *m.sas.v1* verification method.
#[serde(rename = "m.sas.v1")]
#[strum(serialize = "m.sas.v1")]
MSasV1,
}
#[cfg(test)]
mod test {
use super::{KeyAgreementProtocol, MessageAuthenticationCode};
use serde_json::{from_value as from_json_value, json};
#[test]
fn serialize_key_agreement() {
let serialized =
serde_json::to_string(&KeyAgreementProtocol::Curve25519HkdfSha256).unwrap();
assert_eq!(serialized, "\"curve25519-hkdf-sha256\"");
let deserialized: KeyAgreementProtocol = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, KeyAgreementProtocol::Curve25519HkdfSha256);
}
#[test]
fn deserialize_mac_method() {
let json = json!(["hkdf-hmac-sha256", "hmac-sha256"]);
let deserialized: Vec<MessageAuthenticationCode> = from_json_value(json).unwrap();
assert!(deserialized.contains(&MessageAuthenticationCode::HkdfHmacSha256));
}
#[test]
fn serialize_mac_method() {
let serialized = serde_json::to_string(&MessageAuthenticationCode::HkdfHmacSha256).unwrap();
let deserialized: MessageAuthenticationCode = serde_json::from_str(&serialized).unwrap();
assert_eq!(serialized, "\"hkdf-hmac-sha256\"");
assert_eq!(deserialized, MessageAuthenticationCode::HkdfHmacSha256);
let serialized = serde_json::to_string(&MessageAuthenticationCode::HmacSha256).unwrap();
let deserialized: MessageAuthenticationCode = serde_json::from_str(&serialized).unwrap();
assert_eq!(serialized, "\"hmac-sha256\"");
assert_eq!(deserialized, MessageAuthenticationCode::HmacSha256);
}
}
| 35.486239 | 100 | 0.709928 |
eff52f97f4d179aff72ad0e53c0b072f1cb38a70
| 426 |
#[derive(Debug, Clone)]
pub enum Stage {
Unready,
Ready,
Drawing(usize),
Marking(usize),
Over,
_Recover
}
pub struct State {
pub topic: String,
pub stage: Stage,
pub player_count: u8,
}
impl State {
pub fn new() -> Self {
Self {
stage: Stage::Unready,
player_count: 0,
topic: "当你看到这个,意味着设置关键词的逻辑上出现了bug".to_string(),
}
}
}
| 15.777778 | 59 | 0.532864 |
b9a479fd04abc7b5edb907f335d9125e6b34c79e
| 8,347 |
//! Example 01. Simple scene.
//!
//! Difficulty: Easy.
//!
//! This example shows how to create simple scene with animated model.
extern crate rg3d;
pub mod shared;
use crate::shared::create_camera;
use rg3d::{
animation::Animation,
core::{
algebra::{Matrix4, UnitQuaternion, Vector3},
color::Color,
pool::Handle,
},
engine::{framework::prelude::*, resource_manager::ResourceManager},
event::{ElementState, VirtualKeyCode, WindowEvent},
gui::{
message::{MessageDirection, TextMessage},
text::TextBuilder,
widget::WidgetBuilder,
},
scene::{
base::BaseBuilder,
light::{BaseLightBuilder, PointLightBuilder},
mesh::{
surface::{SurfaceBuilder, SurfaceData},
MeshBuilder,
},
node::Node,
transform::TransformBuilder,
Scene,
},
};
use std::sync::{Arc, RwLock};
struct GameSceneLoader {
scene: Scene,
model_handle: Handle<Node>,
walk_animation: Handle<Animation>,
}
impl GameSceneLoader {
async fn load_with(resource_manager: ResourceManager) -> Self {
let mut scene = Scene::new();
// Set ambient light.
scene.ambient_lighting_color = Color::opaque(200, 200, 200);
// Camera is our eyes in the world - you won't see anything without it.
create_camera(
resource_manager.clone(),
Vector3::new(0.0, 6.0, -12.0),
&mut scene.graph,
)
.await;
// Add some light.
PointLightBuilder::new(BaseLightBuilder::new(
BaseBuilder::new().with_local_transform(
TransformBuilder::new()
.with_local_position(Vector3::new(0.0, 12.0, 0.0))
.build(),
),
))
.with_radius(20.0)
.build(&mut scene.graph);
// Load model and animation resource in parallel. Is does *not* adds anything to
// our scene - it just loads a resource then can be used later on to instantiate
// models from it on scene. Why loading of resource is separated from instantiation?
// Because it is too inefficient to load a resource every time you trying to
// create instance of it - much more efficient is to load it once and then make copies
// of it. In case of models it is very efficient because single vertex and index buffer
// can be used for all models instances, so memory footprint on GPU will be lower.
let (model_resource, walk_animation_resource) = rg3d::core::futures::join!(
resource_manager.request_model("examples/data/mutant.FBX"),
resource_manager.request_model("examples/data/walk.fbx")
);
// Instantiate model on scene - but only geometry, without any animations.
// Instantiation is a process of embedding model resource data in desired scene.
let model_handle = model_resource.unwrap().instantiate_geometry(&mut scene);
// Now we have whole sub-graph instantiated, we can start modifying model instance.
scene.graph[model_handle]
.local_transform_mut()
// Our model is too big, fix it by scale.
.set_scale(Vector3::new(0.05, 0.05, 0.05));
// Add simple animation for our model. Animations are loaded from model resources -
// this is because animation is a set of skeleton bones with their own transforms.
// Once animation resource is loaded it must be re-targeted to our model instance.
// Why? Because animation in *resource* uses information about *resource* bones,
// not model instance bones, retarget_animations maps animations of each bone on
// model instance so animation will know about nodes it should operate on.
let walk_animation = *walk_animation_resource
.unwrap()
.retarget_animations(model_handle, &mut scene)
.get(0)
.unwrap();
// Add floor.
MeshBuilder::new(
BaseBuilder::new().with_local_transform(
TransformBuilder::new()
.with_local_position(Vector3::new(0.0, -0.25, 0.0))
.build(),
),
)
.with_surfaces(vec![SurfaceBuilder::new(Arc::new(RwLock::new(
SurfaceData::make_cube(Matrix4::new_nonuniform_scaling(&Vector3::new(
25.0, 0.25, 25.0,
))),
)))
.with_diffuse_texture(resource_manager.request_texture("examples/data/concrete2.dds"))
.build()])
.build(&mut scene.graph);
Self {
scene,
model_handle,
walk_animation,
}
}
}
struct InputController {
rotate_left: bool,
rotate_right: bool,
}
struct Game {
scene: Handle<Scene>,
model_handle: Handle<Node>,
walk_animation: Handle<Animation>,
input_controller: InputController,
debug_text: Handle<UiNode>,
model_angle: f32,
}
impl GameState for Game {
fn init(engine: &mut GameEngine) -> Self
where
Self: Sized,
{
// Prepare resource manager - it must be notified where to search textures. When engine
// loads model resource it automatically tries to load textures it uses. But since most
// model formats store absolute paths, we can't use them as direct path to load texture
// instead we telling engine to search textures in given folder.
engine
.resource_manager
.state()
.set_textures_path("examples/data");
let scene = rg3d::core::futures::executor::block_on(GameSceneLoader::load_with(
engine.resource_manager.clone(),
));
Self {
debug_text: TextBuilder::new(WidgetBuilder::new())
.build(&mut engine.user_interface.build_ctx()),
scene: engine.scenes.add(scene.scene),
model_handle: scene.model_handle,
walk_animation: scene.walk_animation,
// Create input controller - it will hold information about needed actions.
input_controller: InputController {
rotate_left: false,
rotate_right: false,
},
// We will rotate model using keyboard input.
model_angle: 180.0f32.to_radians(),
}
}
fn on_tick(&mut self, engine: &mut GameEngine, _dt: f32) {
let scene = &mut engine.scenes[self.scene];
// Our animation must be applied to scene explicitly, otherwise
// it will have no effect.
scene
.animations
.get_mut(self.walk_animation)
.get_pose()
.apply(&mut scene.graph);
// Rotate model according to input controller state
if self.input_controller.rotate_left {
self.model_angle -= 5.0f32.to_radians();
} else if self.input_controller.rotate_right {
self.model_angle += 5.0f32.to_radians();
}
scene.graph[self.model_handle]
.local_transform_mut()
.set_rotation(UnitQuaternion::from_axis_angle(
&Vector3::y_axis(),
self.model_angle,
));
engine.user_interface.send_message(TextMessage::text(
self.debug_text,
MessageDirection::ToWidget,
format!(
"Example 01 - Simple Scene\nUse [A][D] keys to rotate model.\nFPS: {}",
engine.renderer.get_statistics().frames_per_second
),
));
}
fn on_window_event(&mut self, _engine: &mut GameEngine, event: WindowEvent) {
if let WindowEvent::KeyboardInput { input, .. } = event {
if let Some(key_code) = input.virtual_keycode {
match key_code {
VirtualKeyCode::A => {
self.input_controller.rotate_left = input.state == ElementState::Pressed
}
VirtualKeyCode::D => {
self.input_controller.rotate_right = input.state == ElementState::Pressed
}
_ => (),
}
}
}
}
}
fn main() {
Framework::<Game>::new()
.unwrap()
.title("Example 01 - Simple")
.run();
}
| 35.219409 | 97 | 0.59123 |
62d3c142eeb52962c65147814abbe82811085008
| 83,036 |
//! 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.
crate mod cache;
#[cfg(test)]
mod tests;
mod context;
mod print_item;
mod write_shared;
crate use context::*;
use std::collections::VecDeque;
use std::default::Default;
use std::fmt;
use std::path::PathBuf;
use std::str;
use std::string::ToString;
use rustc_ast_pretty::pprust;
use rustc_attr::{Deprecation, StabilityLevel};
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_hir::Mutability;
use rustc_middle::middle::stability;
use rustc_span::symbol::{kw, sym, Symbol};
use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer};
use crate::clean::{self, FakeDefId, GetDefId, RenderedLink, SelfTy};
use crate::docfs::PathError;
use crate::error::Error;
use crate::formats::cache::Cache;
use crate::formats::item_type::ItemType;
use crate::formats::{AssocItemRender, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::{
href, print_abi_with_space, print_default_space, print_generic_bounds, print_where_clause,
Buffer, PrintWithSpace,
};
use crate::html::markdown::{Markdown, MarkdownHtml, MarkdownSummaryLine};
/// A pair of name and its optional document.
crate type NameDoc = (String, Option<String>);
crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
crate::html::format::display_fn(move |f| {
if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
})
}
// Helper structs for rendering items/sidebars and carrying along contextual
// information
/// 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)]
crate struct IndexItem {
crate ty: ItemType,
crate name: String,
crate path: String,
crate desc: String,
crate parent: Option<DefId>,
crate parent_idx: Option<usize>,
crate search_type: Option<IndexItemFunctionType>,
crate aliases: Box<[String]>,
}
/// A type used for the search index.
#[derive(Debug)]
crate struct RenderType {
ty: Option<DefId>,
idx: Option<usize>,
name: Option<String>,
generics: Option<Vec<Generic>>,
}
impl Serialize for RenderType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(name) = &self.name {
let mut seq = serializer.serialize_seq(None)?;
if let Some(id) = self.idx {
seq.serialize_element(&id)?;
} else {
seq.serialize_element(&name)?;
}
if let Some(generics) = &self.generics {
seq.serialize_element(&generics)?;
}
seq.end()
} else {
serializer.serialize_none()
}
}
}
/// A type used for the search index.
#[derive(Debug)]
crate struct Generic {
name: String,
defid: Option<DefId>,
idx: Option<usize>,
}
impl Serialize for Generic {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(id) = self.idx {
serializer.serialize_some(&id)
} else {
serializer.serialize_some(&self.name)
}
}
}
/// Full type of functions/methods in the search index.
#[derive(Debug)]
crate struct IndexItemFunctionType {
inputs: Vec<TypeWithKind>,
output: Option<Vec<TypeWithKind>>,
}
impl Serialize for IndexItemFunctionType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// If we couldn't figure out a type, just write `null`.
let mut iter = self.inputs.iter();
if match self.output {
Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
None => iter.any(|ref i| i.ty.name.is_none()),
} {
serializer.serialize_none()
} else {
let mut seq = serializer.serialize_seq(None)?;
seq.serialize_element(&self.inputs)?;
if let Some(output) = &self.output {
if output.len() > 1 {
seq.serialize_element(&output)?;
} else {
seq.serialize_element(&output[0])?;
}
}
seq.end()
}
}
}
#[derive(Debug)]
crate struct TypeWithKind {
ty: RenderType,
kind: ItemType,
}
impl From<(RenderType, ItemType)> for TypeWithKind {
fn from(x: (RenderType, ItemType)) -> TypeWithKind {
TypeWithKind { ty: x.0, kind: x.1 }
}
}
impl Serialize for TypeWithKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(&self.ty.name, self.kind).serialize(serializer)
}
}
#[derive(Debug, Clone)]
crate struct StylePath {
/// The path to the theme
crate path: PathBuf,
/// What the `disabled` attribute should be set to in the HTML tag
crate disabled: bool,
}
fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
if let Some(l) = cx.src_href(item) {
write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
}
}
#[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 ItemEntry {
crate fn print(&self) -> impl fmt::Display + '_ {
crate::html::format::display_fn(move |f| {
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: FxHashSet<ItemEntry>,
enums: FxHashSet<ItemEntry>,
unions: FxHashSet<ItemEntry>,
primitives: FxHashSet<ItemEntry>,
traits: FxHashSet<ItemEntry>,
macros: FxHashSet<ItemEntry>,
functions: FxHashSet<ItemEntry>,
typedefs: FxHashSet<ItemEntry>,
opaque_tys: FxHashSet<ItemEntry>,
statics: FxHashSet<ItemEntry>,
constants: FxHashSet<ItemEntry>,
keywords: FxHashSet<ItemEntry>,
attributes: FxHashSet<ItemEntry>,
derives: FxHashSet<ItemEntry>,
trait_aliases: FxHashSet<ItemEntry>,
}
impl AllTypes {
fn new() -> AllTypes {
let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
AllTypes {
structs: new_set(100),
enums: new_set(100),
unions: new_set(100),
primitives: new_set(26),
traits: new_set(100),
macros: new_set(100),
functions: new_set(100),
typedefs: new_set(100),
opaque_tys: new_set(100),
statics: new_set(100),
constants: new_set(100),
keywords: new_set(100),
attributes: new_set(100),
derives: new_set(100),
trait_aliases: new_set(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::OpaqueTy => self.opaque_tys.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)),
ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
_ => true,
};
}
}
}
impl AllTypes {
fn print(self, f: &mut Buffer) {
fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
if !e.is_empty() {
let mut e: Vec<&ItemEntry> = e.iter().collect();
e.sort();
write!(
f,
"<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
title.replace(' ', "-"), // IDs cannot contain whitespaces.
title,
class
);
for s in e.iter() {
write!(f, "<li>{}</li>", s.print());
}
f.write_str("</ul>");
}
}
f.write_str(
"<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>",
);
// Note: print_entries does not escape the title, because we know the current set of titles
// doesn't require escaping.
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.attributes, "Attribute Macros", "attributes");
print_entries(f, &self.derives, "Derive Macros", "derives");
print_entries(f, &self.functions, "Functions", "functions");
print_entries(f, &self.typedefs, "Typedefs", "typedefs");
print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
print_entries(f, &self.statics, "Statics", "statics");
print_entries(f, &self.constants, "Constants", "constants")
}
}
#[derive(Debug)]
enum Setting {
Section {
description: &'static str,
sub_settings: Vec<Setting>,
},
Toggle {
js_data_name: &'static str,
description: &'static str,
default_value: bool,
},
Select {
js_data_name: &'static str,
description: &'static str,
default_value: &'static str,
options: Vec<(String, String)>,
},
}
impl Setting {
fn display(&self, root_path: &str, suffix: &str) -> String {
match *self {
Setting::Section { description, ref sub_settings } => format!(
"<div class=\"setting-line\">\
<div class=\"title\">{}</div>\
<div class=\"sub-settings\">{}</div>
</div>",
description,
sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
),
Setting::Toggle { js_data_name, description, default_value } => format!(
"<div class=\"setting-line\">\
<label class=\"toggle\">\
<input type=\"checkbox\" id=\"{}\" {}>\
<span class=\"slider\"></span>\
</label>\
<div>{}</div>\
</div>",
js_data_name,
if default_value { " checked" } else { "" },
description,
),
Setting::Select { js_data_name, description, default_value, ref options } => format!(
"<div class=\"setting-line\">\
<div>{}</div>\
<label class=\"select-wrapper\">\
<select id=\"{}\" autocomplete=\"off\">{}</select>\
<img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
</label>\
</div>",
description,
js_data_name,
options
.iter()
.map(|opt| format!(
"<option value=\"{}\" {}>{}</option>",
opt.0,
if opt.0 == default_value { "selected" } else { "" },
opt.1,
))
.collect::<String>(),
root_path,
suffix,
),
}
}
}
impl From<(&'static str, &'static str, bool)> for Setting {
fn from(values: (&'static str, &'static str, bool)) -> Setting {
Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
}
}
impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
fn from(values: (&'static str, Vec<T>)) -> Setting {
Setting::Section {
description: values.0,
sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
}
}
}
fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
let theme_names: Vec<(String, String)> = themes
.iter()
.map(|entry| {
let theme =
try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
.to_string();
Ok((theme.clone(), theme))
})
.collect::<Result<_, Error>>()?;
// (id, explanation, default value)
let settings: &[Setting] = &[
(
"Theme preferences",
vec![
Setting::from(("use-system-theme", "Use system theme", true)),
Setting::Select {
js_data_name: "preferred-dark-theme",
description: "Preferred dark theme",
default_value: "dark",
options: theme_names.clone(),
},
Setting::Select {
js_data_name: "preferred-light-theme",
description: "Preferred light theme",
default_value: "light",
options: theme_names,
},
],
)
.into(),
("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
.into(),
("go-to-only-result", "Directly go to item in search if there is only one result", false)
.into(),
("line-numbers", "Show line numbers on code examples", false).into(),
("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
];
Ok(format!(
"<h1 class=\"fqn\">\
<span class=\"in-band\">Rustdoc settings</span>\
</h1>\
<div class=\"settings\">{}</div>\
<script src=\"{}settings{}.js\"></script>",
settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
root_path,
suffix
))
}
fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
if let Some(ref name) = item.name {
info!("Documenting {}", name);
}
document_item_info(w, cx, item, parent);
if parent.is_none() {
document_full_collapsible(w, item, cx);
} else {
document_full(w, item, cx);
}
}
/// Render md_text as markdown.
fn render_markdown(w: &mut Buffer, cx: &Context<'_>, md_text: &str, links: Vec<RenderedLink>) {
let mut ids = cx.id_map.borrow_mut();
write!(
w,
"<div class=\"docblock\">{}</div>",
Markdown(
md_text,
&links,
&mut ids,
cx.shared.codes,
cx.shared.edition(),
&cx.shared.playground
)
.into_string()
)
}
/// Writes a documentation block containing only the first paragraph of the documentation. If the
/// docs are longer, a "Read more" link is appended to the end.
fn document_short(
w: &mut Buffer,
item: &clean::Item,
cx: &Context<'_>,
link: AssocItemLink<'_>,
parent: &clean::Item,
show_def_docs: bool,
) {
document_item_info(w, cx, item, Some(parent));
if !show_def_docs {
return;
}
if let Some(s) = item.doc_value() {
let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
if s.contains('\n') {
let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
if let Some(idx) = summary_html.rfind("</p>") {
summary_html.insert_str(idx, &link);
} else {
summary_html.push_str(&link);
}
}
write!(w, "<div class='docblock'>{}</div>", summary_html,);
}
}
fn document_full_collapsible(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
document_full_inner(w, item, cx, true);
}
fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
document_full_inner(w, item, cx, false);
}
fn document_full_inner(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, is_collapsible: bool) {
if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
debug!("Doc block: =====\n{}\n=====", s);
if is_collapsible {
w.write_str(
"<details class=\"rustdoc-toggle top-doc\" open>\
<summary class=\"hideme\">\
<span>Expand description</span>\
</summary>",
);
render_markdown(w, cx, &s, item.links(cx));
w.write_str("</details>");
} else {
render_markdown(w, cx, &s, item.links(cx));
}
}
}
/// Add extra information about an item such as:
///
/// * Stability
/// * Deprecated
/// * Required features (through the `doc_cfg` feature)
fn document_item_info(
w: &mut Buffer,
cx: &Context<'_>,
item: &clean::Item,
parent: Option<&clean::Item>,
) {
let item_infos = short_item_info(item, cx, parent);
if !item_infos.is_empty() {
w.write_str("<div class=\"item-info\">");
for info in item_infos {
w.write_str(&info);
}
w.write_str("</div>");
}
}
fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
(Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
(cfg, _) => cfg.as_deref().cloned(),
};
debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
}
/// Render the stability, deprecation and portability information that is displayed at the top of
/// the item's documentation.
fn short_item_info(
item: &clean::Item,
cx: &Context<'_>,
parent: Option<&clean::Item>,
) -> Vec<String> {
let mut extra_info = vec![];
let error_codes = cx.shared.codes;
if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
item.deprecation(cx.tcx())
{
// We display deprecation messages for #[deprecated] and #[rustc_deprecated]
// but only display the future-deprecation messages for #[rustc_deprecated].
let mut message = if let Some(since) = since {
let since = &since.as_str();
if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
if *since == "TBD" {
String::from("Deprecating in a future Rust version")
} else {
format!("Deprecating in {}", Escape(since))
}
} else {
format!("Deprecated since {}", Escape(since))
}
} else {
String::from("Deprecated")
};
if let Some(note) = note {
let note = note.as_str();
let mut ids = cx.id_map.borrow_mut();
let html = MarkdownHtml(
¬e,
&mut ids,
error_codes,
cx.shared.edition(),
&cx.shared.playground,
);
message.push_str(&format!(": {}", html.into_string()));
}
extra_info.push(format!(
"<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
message,
));
}
// Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
// Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
.stability(cx.tcx())
.as_ref()
.filter(|stab| stab.feature != sym::rustc_private)
.map(|stab| (stab.level, stab.feature))
{
let mut message =
"<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
feature.push_str(&format!(
" <a href=\"{url}{issue}\">#{issue}</a>",
url = url,
issue = issue
));
}
message.push_str(&format!(" ({})", feature));
if let Some(unstable_reason) = reason {
let mut ids = cx.id_map.borrow_mut();
message = format!(
"<details><summary>{}</summary>{}</details>",
message,
MarkdownHtml(
&unstable_reason.as_str(),
&mut ids,
error_codes,
cx.shared.edition(),
&cx.shared.playground,
)
.into_string()
);
}
extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
}
if let Some(portability) = portability(item, parent) {
extra_info.push(portability);
}
extra_info
}
// Render the list of items inside one of the sections "Trait Implementations",
// "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
fn render_impls(
cx: &Context<'_>,
w: &mut Buffer,
traits: &[&&Impl],
containing_item: &clean::Item,
) {
let cache = cx.cache();
let tcx = cx.tcx();
let mut impls = traits
.iter()
.map(|i| {
let did = i.trait_did_full(cache).unwrap();
let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
render_impl(
&mut buffer,
cx,
i,
containing_item,
assoc_link,
RenderMode::Normal,
true,
None,
false,
true,
&[],
);
buffer.into_inner()
})
.collect::<Vec<_>>();
impls.sort();
w.write_str(&impls.join(""));
}
fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
use crate::formats::item_type::ItemType::*;
let name = it.name.as_ref().unwrap();
let ty = match it.type_() {
Typedef | AssocType => AssocType,
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.expect_real(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
}
}
}
fn assoc_const(
w: &mut Buffer,
it: &clean::Item,
ty: &clean::Type,
_default: Option<&String>,
link: AssocItemLink<'_>,
extra: &str,
cx: &Context<'_>,
) {
write!(
w,
"{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
extra,
it.visibility.print_with_space(it.def_id, cx),
naive_assoc_href(it, link, cx),
it.name.as_ref().unwrap(),
ty.print(cx)
);
}
fn assoc_type(
w: &mut Buffer,
it: &clean::Item,
bounds: &[clean::GenericBound],
default: Option<&clean::Type>,
link: AssocItemLink<'_>,
extra: &str,
cx: &Context<'_>,
) {
write!(
w,
"{}type <a href=\"{}\" class=\"type\">{}</a>",
extra,
naive_assoc_href(it, link, cx),
it.name.as_ref().unwrap()
);
if !bounds.is_empty() {
write!(w, ": {}", print_generic_bounds(bounds, cx))
}
if let Some(default) = default {
write!(w, " = {}", default.print(cx))
}
}
fn render_stability_since_raw(
w: &mut Buffer,
ver: Option<&str>,
const_ver: Option<&str>,
containing_ver: Option<&str>,
containing_const_ver: Option<&str>,
) {
let ver = ver.filter(|inner| !inner.is_empty());
let const_ver = const_ver.filter(|inner| !inner.is_empty());
match (ver, const_ver) {
(Some(v), Some(cv)) if const_ver != containing_const_ver => {
write!(
w,
"<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
v, cv
);
}
(Some(v), _) if ver != containing_ver => {
write!(
w,
"<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
v
);
}
_ => {}
}
}
fn render_assoc_item(
w: &mut Buffer,
item: &clean::Item,
link: AssocItemLink<'_>,
parent: ItemType,
cx: &Context<'_>,
) {
fn method(
w: &mut Buffer,
meth: &clean::Item,
header: hir::FnHeader,
g: &clean::Generics,
d: &clean::FnDecl,
link: AssocItemLink<'_>,
parent: ItemType,
cx: &Context<'_>,
) {
let name = meth.name.as_ref().unwrap();
let href = match link {
AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
AssocItemLink::Anchor(None) => format!("#{}.{}", meth.type_(), name),
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.expect_real(), cx)
.map(|p| format!("{}#{}.{}", p.0, ty, name))
.unwrap_or_else(|| format!("#{}.{}", ty, name))
}
};
let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
let constness = header.constness.print_with_space();
let asyncness = header.asyncness.print_with_space();
let unsafety = header.unsafety.print_with_space();
let defaultness = print_default_space(meth.is_default());
let abi = print_abi_with_space(header.abi).to_string();
// NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
let generics_len = format!("{:#}", g.print(cx)).len();
let mut header_len = "fn ".len()
+ vis.len()
+ constness.len()
+ asyncness.len()
+ unsafety.len()
+ defaultness.len()
+ abi.len()
+ name.as_str().len()
+ generics_len;
let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
header_len += 4;
let indent_str = " ";
render_attributes_in_pre(w, meth, indent_str);
(4, indent_str, false)
} else {
render_attributes_in_code(w, meth);
(0, "", true)
};
w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
write!(
w,
"{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
{generics}{decl}{notable_traits}{where_clause}",
indent_str,
vis,
constness,
asyncness,
unsafety,
defaultness,
abi,
href = href,
name = name,
generics = g.print(cx),
decl = d.full_print(header_len, indent, header.asyncness, cx),
notable_traits = notable_traits_decl(&d, cx),
where_clause = print_where_clause(g, cx, indent, end_newline),
)
}
match *item.kind {
clean::StrippedItem(..) => {}
clean::TyMethodItem(ref m) => {
method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
}
clean::MethodItem(ref m, _) => {
method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
}
clean::AssocConstItem(ref ty, ref default) => assoc_const(
w,
item,
ty,
default.as_ref(),
link,
if parent == ItemType::Trait { " " } else { "" },
cx,
),
clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
w,
item,
bounds,
default.as_ref(),
link,
if parent == ItemType::Trait { " " } else { "" },
cx,
),
_ => panic!("render_assoc_item called on non-associated-item"),
}
}
const ALLOWED_ATTRIBUTES: &[Symbol] =
&[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
fn attributes(it: &clean::Item) -> Vec<String> {
it.attrs
.other_attrs
.iter()
.filter_map(|attr| {
if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
} else {
None
}
})
.collect()
}
// When an attribute is rendered inside a `<pre>` tag, it is formatted using
// a whitespace prefix and newline.
fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
for a in attributes(it) {
writeln!(w, "{}{}", prefix, a);
}
}
// When an attribute is rendered inside a <code> tag, it is formatted using
// a div to produce a newline after it.
fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
for a in attributes(it) {
write!(w, "<div class=\"code-attribute\">{}</div>", a);
}
}
#[derive(Copy, Clone)]
enum AssocItemLink<'a> {
Anchor(Option<&'a str>),
GotoSource(FakeDefId, &'a FxHashSet<Symbol>),
}
impl<'a> AssocItemLink<'a> {
fn anchor(&self, id: &'a str) -> Self {
match *self {
AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
ref other => *other,
}
}
}
fn render_assoc_items(
w: &mut Buffer,
cx: &Context<'_>,
containing_item: &clean::Item,
it: DefId,
what: AssocItemRender<'_>,
) {
info!("Documenting associated items of {:?}", containing_item.name);
let v = match cx.cache.impls.get(&it) {
Some(v) => v,
None => return,
};
let cache = cx.cache();
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 => {
w.write_str(
"<h2 id=\"implementations\" class=\"small-section-header\">\
Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
</h2>",
);
RenderMode::Normal
}
AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
write!(
w,
"<h2 id=\"deref-methods\" class=\"small-section-header\">\
Methods from {trait_}<Target = {type_}>\
<a href=\"#deref-methods\" class=\"anchor\"></a>\
</h2>",
trait_ = trait_.print(cx),
type_ = type_.print(cx),
);
RenderMode::ForDeref { mut_: deref_mut_ }
}
};
for i in &non_trait {
render_impl(
w,
cx,
i,
containing_item,
AssocItemLink::Anchor(None),
render_mode,
true,
None,
false,
true,
&[],
);
}
}
if let AssocItemRender::DerefFor { .. } = what {
return;
}
if !traits.is_empty() {
let deref_impl = traits
.iter()
.find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
if let Some(impl_) = deref_impl {
let has_deref_mut = traits
.iter()
.any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
}
let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
traits.iter().partition(|t| t.inner_impl().synthetic);
let (blanket_impl, concrete): (Vec<&&Impl>, _) =
concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
let mut impls = Buffer::empty_from(&w);
render_impls(cx, &mut impls, &concrete, containing_item);
let impls = impls.into_inner();
if !impls.is_empty() {
write!(
w,
"<h2 id=\"trait-implementations\" class=\"small-section-header\">\
Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
</h2>\
<div id=\"trait-implementations-list\">{}</div>",
impls
);
}
if !synthetic.is_empty() {
w.write_str(
"<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);
w.write_str("</div>");
}
if !blanket_impl.is_empty() {
w.write_str(
"<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
Blanket Implementations\
<a href=\"#blanket-implementations\" class=\"anchor\"></a>\
</h2>\
<div id=\"blanket-implementations-list\">",
);
render_impls(cx, w, &blanket_impl, containing_item);
w.write_str("</div>");
}
}
}
fn render_deref_methods(
w: &mut Buffer,
cx: &Context<'_>,
impl_: &Impl,
container_item: &clean::Item,
deref_mut: bool,
) {
let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
let (target, real_target) = impl_
.inner_impl()
.items
.iter()
.find_map(|item| match *item.kind {
clean::TypedefItem(ref t, true) => Some(match *t {
clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
_ => (&t.type_, &t.type_),
}),
_ => None,
})
.expect("Expected associated type binding");
debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
let what =
AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
if let Some(did) = target.def_id_full(cx.cache()) {
if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
// `impl Deref<Target = S> for S`
if did == type_did {
// Avoid infinite cycles
return;
}
}
render_assoc_items(w, cx, container_item, did, what);
} else {
if let Some(prim) = target.primitive_type() {
if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
render_assoc_items(w, cx, container_item, did, what);
}
}
}
}
fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
let self_type_opt = match *item.kind {
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::Mut, 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 notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
let mut out = Buffer::html();
let mut trait_ = String::new();
if let Some(did) = decl.output.def_id_full(cx.cache()) {
if let Some(impls) = cx.cache().impls.get(&did) {
for i in impls {
let impl_ = i.inner_impl();
if impl_.trait_.def_id().map_or(false, |d| {
cx.cache().traits.get(&d).map(|t| t.is_notable).unwrap_or(false)
}) {
if out.is_empty() {
write!(
&mut out,
"<h3 class=\"notable\">Notable traits for {}</h3>\
<code class=\"content\">",
impl_.for_.print(cx)
);
trait_.push_str(&impl_.for_.print(cx).to_string());
}
//use the "where" class here to make it small
write!(
&mut out,
"<span class=\"where fmt-newline\">{}</span>",
impl_.print(false, cx)
);
let t_did = impl_.trait_.def_id_full(cx.cache()).unwrap();
for it in &impl_.items {
if let clean::TypedefItem(ref tydef, _) = *it.kind {
out.push_str("<span class=\"where fmt-newline\"> ");
assoc_type(
&mut out,
it,
&[],
Some(&tydef.type_),
AssocItemLink::GotoSource(t_did.into(), &FxHashSet::default()),
"",
cx,
);
out.push_str(";</span>");
}
}
}
}
}
}
if !out.is_empty() {
out.insert_str(
0,
"<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
<div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
);
out.push_str("</code></span></div></span></span>");
}
out.into_inner()
}
fn render_impl(
w: &mut Buffer,
cx: &Context<'_>,
i: &Impl,
parent: &clean::Item,
link: AssocItemLink<'_>,
render_mode: RenderMode,
show_def_docs: bool,
use_absolute: Option<bool>,
is_on_foreign_type: bool,
show_default_items: bool,
// This argument is used to reference same type with different paths to avoid duplication
// in documentation pages for trait with automatic implementations like "Send" and "Sync".
aliases: &[String],
) {
let cache = cx.cache();
let traits = &cache.traits;
let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
let mut close_tags = String::new();
// For trait implementations, the `interesting` output contains all methods that have doc
// comments, and the `boring` output contains all methods that do not. The distinction is
// used to allow hiding the boring methods.
// `containing_item` is used for rendering stability info. If the parent is a trait impl,
// `containing_item` will the grandparent, since trait impls can't have stability attached.
fn doc_impl_item(
boring: &mut Buffer,
interesting: &mut Buffer,
cx: &Context<'_>,
item: &clean::Item,
parent: &clean::Item,
containing_item: &clean::Item,
link: AssocItemLink<'_>,
render_mode: RenderMode,
is_default_item: bool,
trait_: Option<&clean::Trait>,
show_def_docs: bool,
) {
let item_type = item.type_();
let name = item.name.as_ref().unwrap();
let render_method_item = match render_mode {
RenderMode::Normal => true,
RenderMode::ForDeref { mut_: deref_mut_ } => {
should_render_item(&item, deref_mut_, &cx.cache)
}
};
let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
let mut doc_buffer = Buffer::empty_from(boring);
let mut info_buffer = Buffer::empty_from(boring);
let mut short_documented = true;
if render_method_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.
if item.doc_value().is_some() {
document_item_info(&mut info_buffer, cx, it, Some(parent));
document_full(&mut doc_buffer, item, cx);
short_documented = false;
} else {
// In case the item isn't documented,
// provide short documentation from the trait.
document_short(&mut doc_buffer, it, cx, link, parent, show_def_docs);
}
}
} else {
document_item_info(&mut info_buffer, cx, item, Some(parent));
if show_def_docs {
document_full(&mut doc_buffer, item, cx);
short_documented = false;
}
}
} else {
document_short(&mut doc_buffer, item, cx, link, parent, show_def_docs);
}
}
let w = if short_documented && trait_.is_some() { interesting } else { boring };
let toggled = !doc_buffer.is_empty();
if toggled {
let method_toggle_class =
if item_type == ItemType::Method { " method-toggle" } else { "" };
write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
}
match *item.kind {
clean::MethodItem(..) | clean::TyMethodItem(_) => {
// Only render when the method is not static or we allow static methods
if render_method_item {
let id = cx.derive_id(format!("{}.{}", item_type, name));
let source_id = trait_
.and_then(|trait_| {
trait_.items.iter().find(|item| {
item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
})
})
.map(|item| format!("{}.{}", item.type_(), name));
write!(
w,
"<div id=\"{}\" class=\"{}{} has-srclink\">",
id, item_type, in_trait_class,
);
render_rightside(w, cx, item, containing_item);
write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
w.write_str("<code>");
render_assoc_item(
w,
item,
link.anchor(source_id.as_ref().unwrap_or(&id)),
ItemType::Impl,
cx,
);
w.write_str("</code>");
w.write_str("</div>");
}
}
clean::TypedefItem(ref tydef, _) => {
let source_id = format!("{}.{}", ItemType::AssocType, name);
let id = cx.derive_id(source_id.clone());
write!(
w,
"<div id=\"{}\" class=\"{}{} has-srclink\">",
id, item_type, in_trait_class
);
write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
w.write_str("<code>");
assoc_type(
w,
item,
&Vec::new(),
Some(&tydef.type_),
link.anchor(if trait_.is_some() { &source_id } else { &id }),
"",
cx,
);
w.write_str("</code>");
w.write_str("</div>");
}
clean::AssocConstItem(ref ty, ref default) => {
let source_id = format!("{}.{}", item_type, name);
let id = cx.derive_id(source_id.clone());
write!(
w,
"<div id=\"{}\" class=\"{}{} has-srclink\">",
id, item_type, in_trait_class
);
render_rightside(w, cx, item, containing_item);
write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
w.write_str("<code>");
assoc_const(
w,
item,
ty,
default.as_ref(),
link.anchor(if trait_.is_some() { &source_id } else { &id }),
"",
cx,
);
w.write_str("</code>");
w.write_str("</div>");
}
clean::AssocTypeItem(ref bounds, ref default) => {
let source_id = format!("{}.{}", item_type, name);
let id = cx.derive_id(source_id.clone());
write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
w.write_str("<code>");
assoc_type(
w,
item,
bounds,
default.as_ref(),
link.anchor(if trait_.is_some() { &source_id } else { &id }),
"",
cx,
);
w.write_str("</code>");
w.write_str("</div>");
}
clean::StrippedItem(..) => return,
_ => panic!("can't make docs for trait item with name {:?}", item.name),
}
w.push_buffer(info_buffer);
if toggled {
w.write_str("</summary>");
w.push_buffer(doc_buffer);
w.push_str("</details>");
}
}
let mut impl_items = Buffer::empty_from(w);
let mut default_impl_items = Buffer::empty_from(w);
for trait_item in &i.inner_impl().items {
doc_impl_item(
&mut default_impl_items,
&mut impl_items,
cx,
trait_item,
if trait_.is_some() { &i.impl_item } else { parent },
parent,
link,
render_mode,
false,
trait_.map(|t| &t.trait_),
show_def_docs,
);
}
fn render_default_items(
boring: &mut Buffer,
interesting: &mut Buffer,
cx: &Context<'_>,
t: &clean::Trait,
i: &clean::Impl,
parent: &clean::Item,
containing_item: &clean::Item,
render_mode: RenderMode,
show_def_docs: bool,
) {
for trait_item in &t.items {
let n = trait_item.name;
if i.items.iter().any(|m| m.name == n) {
continue;
}
let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
let provided_methods = i.provided_trait_methods(cx.tcx());
let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
doc_impl_item(
boring,
interesting,
cx,
trait_item,
parent,
containing_item,
assoc_link,
render_mode,
true,
Some(t),
show_def_docs,
);
}
}
// If we've implemented a trait, then also emit documentation for all
// default items which weren't overridden in the implementation block.
// We don't emit documentation for default items if they appear in the
// Implementations on Foreign Types or Implementors sections.
if show_default_items {
if let Some(t) = trait_ {
render_default_items(
&mut default_impl_items,
&mut impl_items,
cx,
&t.trait_,
&i.inner_impl(),
&i.impl_item,
parent,
render_mode,
show_def_docs,
);
}
}
if render_mode == RenderMode::Normal {
let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
if toggled {
close_tags.insert_str(0, "</details>");
write!(w, "<details class=\"rustdoc-toggle implementors-toggle\" open>");
write!(w, "<summary>")
}
render_impl_summary(
w,
cx,
i,
parent,
parent,
show_def_docs,
use_absolute,
is_on_foreign_type,
aliases,
);
if toggled {
write!(w, "</summary>")
}
if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
let mut ids = cx.id_map.borrow_mut();
write!(
w,
"<div class=\"docblock\">{}</div>",
Markdown(
&*dox,
&i.impl_item.links(cx),
&mut ids,
cx.shared.codes,
cx.shared.edition(),
&cx.shared.playground
)
.into_string()
);
}
}
if !default_impl_items.is_empty() || !impl_items.is_empty() {
w.write_str("<div class=\"impl-items\">");
w.push_buffer(default_impl_items);
w.push_buffer(impl_items);
close_tags.insert_str(0, "</div>");
}
w.write_str(&close_tags);
}
// Render the items that appear on the right side of methods, impls, and
// associated types. For example "1.0.0 (const: 1.39.0) [src]".
fn render_rightside(
w: &mut Buffer,
cx: &Context<'_>,
item: &clean::Item,
containing_item: &clean::Item,
) {
let tcx = cx.tcx();
write!(w, "<div class=\"rightside\">");
render_stability_since_raw(
w,
item.stable_since(tcx).as_deref(),
item.const_stable_since(tcx).as_deref(),
containing_item.stable_since(tcx).as_deref(),
containing_item.const_stable_since(tcx).as_deref(),
);
write_srclink(cx, item, w);
w.write_str("</div>");
}
pub(crate) fn render_impl_summary(
w: &mut Buffer,
cx: &Context<'_>,
i: &Impl,
parent: &clean::Item,
containing_item: &clean::Item,
show_def_docs: bool,
use_absolute: Option<bool>,
is_on_foreign_type: bool,
// This argument is used to reference same type with different paths to avoid duplication
// in documentation pages for trait with automatic implementations like "Send" and "Sync".
aliases: &[String],
) {
let id = cx.derive_id(match i.inner_impl().trait_ {
Some(ref t) => {
if is_on_foreign_type {
get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
} else {
format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
}
}
None => "impl".to_string(),
});
let aliases = if aliases.is_empty() {
String::new()
} else {
format!(" data-aliases=\"{}\"", aliases.join(","))
};
write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
render_rightside(w, cx, &i.impl_item, containing_item);
write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
write!(w, "<code class=\"in-band\">");
if let Some(use_absolute) = use_absolute {
write!(w, "{}", i.inner_impl().print(use_absolute, cx));
if show_def_docs {
for it in &i.inner_impl().items {
if let clean::TypedefItem(ref tydef, _) = *it.kind {
w.write_str("<span class=\"where fmt-newline\"> ");
assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
w.write_str(";</span>");
}
}
}
} else {
write!(w, "{}", i.inner_impl().print(false, cx));
}
write!(w, "</code>");
let is_trait = i.inner_impl().trait_.is_some();
if is_trait {
if let Some(portability) = portability(&i.impl_item, Some(parent)) {
write!(w, "<div class=\"item-info\">{}</div>", portability);
}
}
w.write_str("</div>");
}
fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
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!(
buffer,
"<p class=\"location\">{}{}</p>",
match *it.kind {
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) = cx.cache.crate_version {
write!(
buffer,
"<div class=\"block version\">\
<p>Version {}</p>\
</div>",
Escape(version),
);
}
}
buffer.write_str("<div class=\"sidebar-elems\">");
if it.is_crate() {
write!(
buffer,
"<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
it.name.as_ref().expect("crates always have a name"),
);
}
match *it.kind {
clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, 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).
if !it.is_mod() {
buffer.write_str("<p class=\"location\">Other items in<br>");
for (i, name) in cx.current.iter().take(parentlen).enumerate() {
if i > 0 {
buffer.write_str("::<wbr>");
}
write!(
buffer,
"<a href=\"{}index.html\">{}</a>",
&cx.root_path()[..(cx.current.len() - i - 1) * 3],
*name
);
}
buffer.write_str("</p>");
}
// Sidebar refers to the enclosing module, not this module.
let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
write!(
buffer,
"<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
</div>",
name = it.name.unwrap_or(kw::Empty),
ty = it.type_(),
path = relpath
);
write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
// Closes sidebar-elems div.
buffer.write_str("</div>");
}
fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
if used_links.insert(url.clone()) {
return url;
}
let mut add = 1;
while !used_links.insert(format!("{}-{}", url, add)) {
add += 1;
}
format!("{}-{}", url, add)
}
fn get_methods(
i: &clean::Impl,
for_deref: bool,
used_links: &mut FxHashSet<String>,
deref_mut: bool,
cache: &Cache,
) -> Vec<String> {
i.items
.iter()
.filter_map(|item| match item.name {
Some(ref name) if !name.is_empty() && item.is_method() => {
if !for_deref || should_render_item(item, deref_mut, cache) {
Some(format!(
"<a href=\"#{}\">{}</a>",
get_next_url(used_links, format!("method.{}", 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: String) -> String {
let mut st = String::new();
let mut last_match = 0;
for (idx, c) in s.char_indices() {
let escaped = match c {
'<' => "%3C",
'>' => "%3E",
' ' => "%20",
'?' => "%3F",
'\'' => "%27",
'&' => "%26",
',' => "%2C",
':' => "%3A",
';' => "%3B",
'[' => "%5B",
']' => "%5D",
'"' => "%22",
_ => continue,
};
st += &s[last_match..idx];
st += escaped;
// NOTE: we only expect single byte characters here - which is fine as long as we
// only match single byte characters
last_match = idx + 1;
}
if last_match != 0 {
st += &s[last_match..];
st
} else {
s
}
}
fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
let did = it.def_id.expect_real();
if let Some(v) = cx.cache.impls.get(&did) {
let mut used_links = FxHashSet::default();
let cache = cx.cache();
{
let used_links_bor = &mut used_links;
let mut ret = v
.iter()
.filter(|i| i.inner_impl().trait_.is_none())
.flat_map(move |i| {
get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
})
.collect::<Vec<_>>();
if !ret.is_empty() {
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
out.push_str(
"<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
<div class=\"sidebar-links\">",
);
for line in ret {
out.push_str(&line);
}
out.push_str("</div>");
}
}
if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
let format_impls = |impls: Vec<&Impl>| {
let mut links = FxHashSet::default();
let mut ret = impls
.iter()
.filter_map(|it| {
if let Some(ref i) = it.inner_impl().trait_ {
let i_display = format!("{:#}", i.print(cx));
let out = Escape(&i_display);
let encoded = small_url_encode(format!("{:#}", i.print(cx)));
let generated = format!(
"<a href=\"#impl-{}\">{}{}</a>",
encoded,
if it.inner_impl().negative_polarity { "!" } else { "" },
out
);
if links.insert(generated.clone()) { Some(generated) } else { None }
} else {
None
}
})
.collect::<Vec<String>>();
ret.sort();
ret
};
let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
out.push_str("<div class=\"sidebar-links\">");
for link in links {
out.push_str(&link);
}
out.push_str("</div>");
};
let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
.into_iter()
.partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
let concrete_format = format_impls(concrete);
let synthetic_format = format_impls(synthetic);
let blanket_format = format_impls(blanket_impl);
if !concrete_format.is_empty() {
out.push_str(
"<a class=\"sidebar-title\" href=\"#trait-implementations\">\
Trait Implementations</a>",
);
write_sidebar_links(out, concrete_format);
}
if !synthetic_format.is_empty() {
out.push_str(
"<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
Auto Trait Implementations</a>",
);
write_sidebar_links(out, synthetic_format);
}
if !blanket_format.is_empty() {
out.push_str(
"<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
Blanket Implementations</a>",
);
write_sidebar_links(out, blanket_format);
}
if let Some(impl_) = v
.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
{
sidebar_deref_methods(cx, out, impl_, v);
}
}
}
}
fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
let c = cx.cache();
debug!("found Deref: {:?}", impl_);
if let Some((target, real_target)) =
impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
clean::TypedefItem(ref t, true) => Some(match *t {
clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
_ => (&t.type_, &t.type_),
}),
_ => None,
})
{
debug!("found target, real_target: {:?} {:?}", target, real_target);
if let Some(did) = target.def_id_full(c) {
if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
// `impl Deref<Target = S> for S`
if did == type_did {
// Avoid infinite cycles
return;
}
}
}
let deref_mut = v
.iter()
.filter(|i| i.inner_impl().trait_.is_some())
.any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
let inner_impl = target
.def_id_full(c)
.or_else(|| {
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 {
debug!("found inner_impl: {:?}", impls);
let mut used_links = FxHashSet::default();
let mut ret = impls
.iter()
.filter(|i| i.inner_impl().trait_.is_none())
.flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
.collect::<Vec<_>>();
if !ret.is_empty() {
write!(
out,
"<a class=\"sidebar-title\" href=\"#deref-methods\">Methods from {}<Target={}></a>",
Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
Escape(&format!("{:#}", real_target.print(cx))),
);
// We want links' order to be reproducible so we don't use unstable sort.
ret.sort();
out.push_str("<div class=\"sidebar-links\">");
for link in ret {
out.push_str(&link);
}
out.push_str("</div>");
}
}
}
}
fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
let mut sidebar = Buffer::new();
let fields = get_struct_fields_name(&s.fields);
if !fields.is_empty() {
if let CtorKind::Fictive = s.struct_type {
sidebar.push_str(
"<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
<div class=\"sidebar-links\">",
);
for field in fields {
sidebar.push_str(&field);
}
sidebar.push_str("</div>");
}
}
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
}
}
fn get_id_for_impl_on_foreign_type(
for_: &clean::Type,
trait_: &clean::Type,
cx: &Context<'_>,
) -> String {
small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx),))
}
fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
match *item.kind {
clean::ItemKind::ImplItem(ref i) => {
if let Some(ref trait_) = i.trait_ {
// Alternative format produces no URLs,
// so this parameter does nothing.
Some((
format!("{:#}", i.for_.print(cx)),
get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
))
} else {
None
}
}
_ => None,
}
}
fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
buf.write_str("<div class=\"block items\">");
fn print_sidebar_section(
out: &mut Buffer,
items: &[clean::Item],
before: &str,
filter: impl Fn(&clean::Item) -> bool,
write: impl Fn(&mut Buffer, &str),
after: &str,
) {
let mut items = items
.iter()
.filter_map(|m| match m.name {
Some(ref name) if filter(m) => Some(name.as_str()),
_ => None,
})
.collect::<Vec<_>>();
if !items.is_empty() {
items.sort_unstable();
out.push_str(before);
for item in items.into_iter() {
write(out, &item);
}
out.push_str(after);
}
}
print_sidebar_section(
buf,
&t.items,
"<a class=\"sidebar-title\" href=\"#associated-types\">\
Associated Types</a><div class=\"sidebar-links\">",
|m| m.is_associated_type(),
|out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
"</div>",
);
print_sidebar_section(
buf,
&t.items,
"<a class=\"sidebar-title\" href=\"#associated-const\">\
Associated Constants</a><div class=\"sidebar-links\">",
|m| m.is_associated_const(),
|out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
"</div>",
);
print_sidebar_section(
buf,
&t.items,
"<a class=\"sidebar-title\" href=\"#required-methods\">\
Required Methods</a><div class=\"sidebar-links\">",
|m| m.is_ty_method(),
|out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
"</div>",
);
print_sidebar_section(
buf,
&t.items,
"<a class=\"sidebar-title\" href=\"#provided-methods\">\
Provided Methods</a><div class=\"sidebar-links\">",
|m| m.is_method(),
|out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
"</div>",
);
if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
let cache = cx.cache();
let mut res = implementors
.iter()
.filter(|i| {
i.inner_impl()
.for_
.def_id_full(cache)
.map_or(false, |d| !cx.cache.paths.contains_key(&d))
})
.filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
.collect::<Vec<_>>();
if !res.is_empty() {
res.sort();
buf.push_str(
"<a class=\"sidebar-title\" href=\"#foreign-impls\">\
Implementations on Foreign Types</a>\
<div class=\"sidebar-links\">",
);
for (name, id) in res.into_iter() {
write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
}
buf.push_str("</div>");
}
}
sidebar_assoc_items(cx, buf, it);
buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
if t.is_auto {
buf.push_str(
"<a class=\"sidebar-title\" \
href=\"#synthetic-implementors\">Auto Implementors</a>",
);
}
buf.push_str("</div>")
}
fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
let mut sidebar = Buffer::new();
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
}
}
fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
let mut sidebar = Buffer::new();
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
}
}
fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
let mut fields = fields
.iter()
.filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
.filter_map(|f| {
f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
})
.collect::<Vec<_>>();
fields.sort();
fields
}
fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
let mut sidebar = Buffer::new();
let fields = get_struct_fields_name(&u.fields);
if !fields.is_empty() {
sidebar.push_str(
"<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
<div class=\"sidebar-links\">",
);
for field in fields {
sidebar.push_str(&field);
}
sidebar.push_str("</div>");
}
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
}
}
fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
let mut sidebar = Buffer::new();
let mut 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::<Vec<_>>();
if !variants.is_empty() {
variants.sort_unstable();
sidebar.push_str(&format!(
"<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
<div class=\"sidebar-links\">{}</div>",
variants.join(""),
));
}
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
}
}
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::AssocType => ("associated-types", "Associated Types"),
ItemType::AssocConst => ("associated-consts", "Associated Constants"),
ItemType::ForeignType => ("foreign-types", "Foreign Types"),
ItemType::Keyword => ("keywords", "Keywords"),
ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
ItemType::ProcDerive => ("derives", "Derive Macros"),
ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
}
}
fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
let mut sidebar = String::new();
// Re-exports are handled a bit differently because they can be extern crates or imports.
if items.iter().any(|it| {
it.name.is_some()
&& (it.type_() == ItemType::ExternCrate
|| (it.type_() == ItemType::Import && !it.is_stripped()))
}) {
let (id, name) = item_ty_to_strs(ItemType::Import);
sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
}
// 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::AssocType,
ItemType::AssocConst,
ItemType::ForeignType,
ItemType::Keyword,
] {
if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
let (id, name) = item_ty_to_strs(myty);
sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
}
}
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
}
}
fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
let mut sidebar = Buffer::new();
sidebar_assoc_items(cx, &mut sidebar, it);
if !sidebar.is_empty() {
write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
}
}
crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
/// 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, cache: &Cache) -> Vec<String> {
let mut out = Vec::new();
let mut visited = FxHashSet::default();
let mut work = VecDeque::new();
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);
if let Some(path) = fqp {
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::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
}
| 34.815933 | 140 | 0.505046 |
08fce3f2c490805db5d41a619d21f54b0151d518
| 14,562 |
use serde::{Deserialize, Serialize};
use std::fmt;
/// SDPSemantics determines which style of SDP offers and answers
/// can be used
#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
pub enum SDPSemantics {
Unspecified = 0,
/// UnifiedPlan uses unified-plan offers and answers
/// (the default in Chrome since M72)
/// https://tools.ietf.org/html/draft-roach-mmusic-unified-plan-00
#[serde(rename = "unified-plan")]
UnifiedPlan = 1,
/// PlanB uses plan-b offers and answers
/// NB: This format should be considered deprecated
/// https://tools.ietf.org/html/draft-uberti-rtcweb-plan-00
#[serde(rename = "plan-b")]
PlanB = 2,
/// UnifiedPlanWithFallback prefers unified-plan
/// offers and answers, but will respond to a plan-b offer
/// with a plan-b answer
#[serde(rename = "unified-plan-with-fallback")]
UnifiedPlanWithFallback = 3,
}
impl Default for SDPSemantics {
fn default() -> Self {
SDPSemantics::UnifiedPlan
}
}
const SDP_SEMANTICS_UNIFIED_PLAN_WITH_FALLBACK: &str = "unified-plan-with-fallback";
const SDP_SEMANTICS_UNIFIED_PLAN: &str = "unified-plan";
const SDP_SEMANTICS_PLAN_B: &str = "plan-b";
impl From<&str> for SDPSemantics {
fn from(raw: &str) -> Self {
match raw {
SDP_SEMANTICS_UNIFIED_PLAN_WITH_FALLBACK => SDPSemantics::UnifiedPlanWithFallback,
SDP_SEMANTICS_UNIFIED_PLAN => SDPSemantics::UnifiedPlan,
SDP_SEMANTICS_PLAN_B => SDPSemantics::PlanB,
_ => SDPSemantics::Unspecified,
}
}
}
impl fmt::Display for SDPSemantics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match *self {
SDPSemantics::UnifiedPlanWithFallback => SDP_SEMANTICS_UNIFIED_PLAN_WITH_FALLBACK,
SDPSemantics::UnifiedPlan => SDP_SEMANTICS_UNIFIED_PLAN,
SDPSemantics::PlanB => SDP_SEMANTICS_PLAN_B,
SDPSemantics::Unspecified => crate::UNSPECIFIED_STR,
};
write!(f, "{}", s)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::api::media_engine::MediaEngine;
use crate::api::APIBuilder;
use crate::media::rtp::rtp_codec::{RTPCodecCapability, RTPCodecType};
use crate::media::rtp::rtp_transceiver_direction::RTPTransceiverDirection;
use crate::media::rtp::RTPTransceiverInit;
use crate::media::track::track_local::track_local_static_sample::TrackLocalStaticSample;
use crate::media::track::track_local::TrackLocal;
use crate::peer::configuration::Configuration;
use crate::peer::peer_connection::peer_connection_test::close_pair_now;
use crate::SSRC_STR;
use anyhow::Result;
use sdp::media_description::MediaDescription;
use sdp::session_description::SessionDescription;
use std::collections::HashSet;
use std::sync::Arc;
#[test]
fn test_sdp_semantics_string() {
let tests = vec![
(SDPSemantics::Unspecified, "Unspecified"),
(
SDPSemantics::UnifiedPlanWithFallback,
"unified-plan-with-fallback",
),
(SDPSemantics::PlanB, "plan-b"),
(SDPSemantics::UnifiedPlan, "unified-plan"),
];
for (value, expected_string) in tests {
assert_eq!(expected_string, value.to_string());
}
}
// The following tests are for non-standard SDP semantics
// (i.e. not unified-unified)
fn get_md_names(sdp: &SessionDescription) -> Vec<String> {
sdp.media_descriptions
.iter()
.map(|md| md.media_name.media.clone())
.collect()
}
fn extract_ssrc_list(md: &MediaDescription) -> Vec<String> {
let mut ssrcs = HashSet::new();
for attr in &md.attributes {
if attr.key == SSRC_STR {
if let Some(value) = &attr.value {
let fields: Vec<&str> = value.split_whitespace().collect();
if let Some(ssrc) = fields.first() {
ssrcs.insert(*ssrc);
}
}
}
}
ssrcs
.into_iter()
.map(|ssrc| ssrc.to_owned())
.collect::<Vec<String>>()
}
#[tokio::test]
async fn test_sdp_semantics_plan_b_offer_transceivers() -> Result<()> {
let mut m = MediaEngine::default();
m.register_default_codecs()?;
let api = APIBuilder::new().with_media_engine(m).build();
let opc = api
.new_peer_connection(Configuration {
sdp_semantics: SDPSemantics::PlanB,
..Default::default()
})
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Video,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Sendrecv,
send_encodings: vec![],
}],
)
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Video,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Sendrecv,
send_encodings: vec![],
}],
)
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Audio,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Sendrecv,
send_encodings: vec![],
}],
)
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Audio,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Sendrecv,
send_encodings: vec![],
}],
)
.await?;
let offer = opc.create_offer(None).await?;
if let Some(parsed) = &offer.parsed {
let md_names = get_md_names(parsed);
assert_eq!(md_names, &["video".to_owned(), "audio".to_owned()]);
// Verify that each section has 2 SSRCs (one for each transceiver)
for section in &["video".to_owned(), "audio".to_owned()] {
for media in &parsed.media_descriptions {
if &media.media_name.media == section {
assert_eq!(extract_ssrc_list(media).len(), 2);
}
}
}
}
let apc = api
.new_peer_connection(Configuration {
sdp_semantics: SDPSemantics::PlanB,
..Default::default()
})
.await?;
apc.set_remote_description(offer).await?;
let answer = apc.create_answer(None).await?;
if let Some(parsed) = &answer.parsed {
let md_names = get_md_names(parsed);
assert_eq!(md_names, &["video".to_owned(), "audio".to_owned()]);
}
close_pair_now(&apc, &opc).await;
Ok(())
}
#[tokio::test]
async fn test_sdp_semantics_plan_b_answer_senders() -> Result<()> {
let mut m = MediaEngine::default();
m.register_default_codecs()?;
let api = APIBuilder::new().with_media_engine(m).build();
let opc = api
.new_peer_connection(Configuration {
sdp_semantics: SDPSemantics::PlanB,
..Default::default()
})
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Video,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Recvonly,
send_encodings: vec![],
}],
)
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Audio,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Recvonly,
send_encodings: vec![],
}],
)
.await?;
let offer = opc.create_offer(None).await?;
if let Some(parsed) = &offer.parsed {
let md_names = get_md_names(parsed);
assert_eq!(md_names, &["video".to_owned(), "audio".to_owned()]);
}
let apc = api
.new_peer_connection(Configuration {
sdp_semantics: SDPSemantics::PlanB,
..Default::default()
})
.await?;
let video1: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "video/h264".to_owned(),
sdp_fmtp_line:
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"
.to_owned(),
..Default::default()
},
"1".to_owned(),
"1".to_owned(),
));
let _ = apc.add_track(video1).await?;
let video2: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "video/h264".to_owned(),
sdp_fmtp_line:
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"
.to_owned(),
..Default::default()
},
"2".to_owned(),
"2".to_owned(),
));
let _ = apc.add_track(video2).await?;
let audio1: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "audio/opus".to_owned(),
..Default::default()
},
"3".to_owned(),
"3".to_owned(),
));
let _ = apc.add_track(audio1).await?;
let audio2: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "audio/opus".to_owned(),
..Default::default()
},
"4".to_owned(),
"4".to_owned(),
));
let _ = apc.add_track(audio2).await?;
apc.set_remote_description(offer).await?;
let answer = apc.create_answer(None).await?;
if let Some(parsed) = &answer.parsed {
let md_names = get_md_names(parsed);
assert_eq!(md_names, &["video".to_owned(), "audio".to_owned()]);
// Verify that each section has 2 SSRCs (one for each transceiver)
for section in &["video".to_owned(), "audio".to_owned()] {
for media in &parsed.media_descriptions {
if &media.media_name.media == section {
assert_eq!(extract_ssrc_list(media).len(), 2);
}
}
}
}
close_pair_now(&apc, &opc).await;
Ok(())
}
#[tokio::test]
async fn test_sdp_semantics_unified_plan_with_fallback() -> Result<()> {
let mut m = MediaEngine::default();
m.register_default_codecs()?;
let api = APIBuilder::new().with_media_engine(m).build();
let opc = api
.new_peer_connection(Configuration {
sdp_semantics: SDPSemantics::PlanB,
..Default::default()
})
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Video,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Recvonly,
send_encodings: vec![],
}],
)
.await?;
opc.add_transceiver_from_kind(
RTPCodecType::Audio,
&[RTPTransceiverInit {
direction: RTPTransceiverDirection::Recvonly,
send_encodings: vec![],
}],
)
.await?;
let offer = opc.create_offer(None).await?;
if let Some(parsed) = &offer.parsed {
let md_names = get_md_names(parsed);
assert_eq!(md_names, &["video".to_owned(), "audio".to_owned()]);
}
let apc = api
.new_peer_connection(Configuration {
sdp_semantics: SDPSemantics::UnifiedPlanWithFallback,
..Default::default()
})
.await?;
let video1: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "video/h264".to_owned(),
sdp_fmtp_line:
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"
.to_owned(),
..Default::default()
},
"1".to_owned(),
"1".to_owned(),
));
let _ = apc.add_track(video1).await?;
let video2: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "video/h264".to_owned(),
sdp_fmtp_line:
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"
.to_owned(),
..Default::default()
},
"2".to_owned(),
"2".to_owned(),
));
let _ = apc.add_track(video2).await?;
let audio1: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "audio/opus".to_owned(),
..Default::default()
},
"3".to_owned(),
"3".to_owned(),
));
let _ = apc.add_track(audio1).await?;
let audio2: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
RTPCodecCapability {
mime_type: "audio/opus".to_owned(),
..Default::default()
},
"4".to_owned(),
"4".to_owned(),
));
let _ = apc.add_track(audio2).await?;
apc.set_remote_description(offer).await?;
let answer = apc.create_answer(None).await?;
if let Some(parsed) = &answer.parsed {
let md_names = get_md_names(parsed);
assert_eq!(md_names, &["video".to_owned(), "audio".to_owned()]);
// Verify that each section has 2 SSRCs (one for each transceiver)
for section in &["video".to_owned(), "audio".to_owned()] {
for media in &parsed.media_descriptions {
if &media.media_name.media == section {
assert_eq!(extract_ssrc_list(media).len(), 2);
}
}
}
}
close_pair_now(&apc, &opc).await;
Ok(())
}
}
| 33.170843 | 94 | 0.539761 |
dd7565b71c298831fd0f1bc0503f9d886bed4e05
| 21,828 |
use crate::meta::{FileType, Name};
use std::collections::HashMap;
pub struct Icons {
display_icons: bool,
icons_by_name: HashMap<&'static str, &'static str>,
icons_by_extension: HashMap<&'static str, &'static str>,
default_folder_icon: &'static str,
default_file_icon: &'static str,
icon_separator: String,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Theme {
NoIcon,
Fancy,
Unicode,
}
// In order to add a new icon, write the unicode value like "\ue5fb" then
// run the command below in vim:
//
// s#\\u[0-9a-f]*#\=eval('"'.submatch(0).'"')#
impl Icons {
pub fn new(theme: Theme, icon_separator: String) -> Self {
let display_icons = theme == Theme::Fancy || theme == Theme::Unicode;
let (icons_by_name, icons_by_extension, default_file_icon, default_folder_icon) =
if theme == Theme::Fancy {
(
Self::get_default_icons_by_name(),
Self::get_default_icons_by_extension(),
"\u{f016}", //
"\u{e5ff}", //
)
} else {
(
HashMap::new(),
HashMap::new(),
"\u{1f5cb}", // 🗋
"\u{1f5c1}", // 🗁
)
};
Self {
display_icons,
icons_by_name,
icons_by_extension,
default_file_icon,
default_folder_icon,
icon_separator,
}
}
pub fn get(&self, name: &Name) -> String {
if !self.display_icons {
return String::new();
}
// Check file types
let file_type: FileType = name.file_type();
let icon = if let FileType::Directory { .. } = file_type {
self.default_folder_icon
} else if let FileType::SymLink { is_dir: true } = file_type {
"\u{f482}" // ""
} else if let FileType::SymLink { is_dir: false } = file_type {
"\u{f481}" // ""
} else if let FileType::Socket = file_type {
"\u{f6a7}" // ""
} else if let FileType::Pipe = file_type {
"\u{f731}" // ""
} else if let FileType::CharDevice = file_type {
"\u{e601}" // ""
} else if let FileType::BlockDevice = file_type {
"\u{fc29}" // "ﰩ"
} else if let FileType::Special = file_type {
"\u{f2dc}" // ""
} else if let Some(icon) = self
.icons_by_name
.get(name.file_name().to_lowercase().as_str())
{
// Use the known names.
icon
} else if let Some(icon) = name.extension().and_then(|extension| {
self.icons_by_extension
.get(extension.to_lowercase().as_str())
}) {
// Use the known extensions.
icon
} else if let FileType::File { exec: true, .. } = file_type {
// If file has no extension and is executable
"\u{f489}" // ""
} else {
// Use the default icons.
self.default_file_icon
};
format!("{}{}", icon, self.icon_separator)
}
fn get_default_icons_by_name() -> HashMap<&'static str, &'static str> {
let mut m = HashMap::new();
// Note: filenames must be lower-case
m.insert(".trash", "\u{f1f8}"); // ""
m.insert(".atom", "\u{e764}"); // ""
m.insert(".bashprofile", "\u{e615}"); // ""
m.insert(".bashrc", "\u{f489}"); // ""
m.insert(".clang-format", "\u{e615}"); // ""
m.insert(".config", "\u{e5fc}"); // ""
m.insert(".git", "\u{f1d3}"); // ""
m.insert(".gitattributes", "\u{f1d3}"); // ""
m.insert(".gitconfig", "\u{f1d3}"); // ""
m.insert(".github", "\u{f408}"); // ""
m.insert(".gitignore", "\u{f1d3}"); // ""
m.insert(".gitlab-ci.yml", "\u{f296}"); // ""
m.insert(".gitmodules", "\u{f1d3}"); // ""
m.insert(".rvm", "\u{e21e}"); // ""
m.insert(".vimrc", "\u{e62b}"); // ""
m.insert(".vscode", "\u{e70c}"); // ""
m.insert(".xinitrc", "\u{e615}"); // ""
m.insert(".xresources", "\u{e615}"); // ""
m.insert(".zshrc", "\u{f489}"); // ""
m.insert("a.out", "\u{f489}"); // ""
m.insert("authorized_keys", "\u{e60a}"); // ""
m.insert("bin", "\u{e5fc}"); // ""
m.insert("bspwmrc", "\u{e615}"); // ""
m.insert("cargo.toml", "\u{e7a8}"); // ""
m.insert("cargo.lock", "\u{e7a8}"); // ""
m.insert("changelog", "\u{e609}"); // ""
m.insert("composer.json", "\u{e608}"); // ""
m.insert("config", "\u{e5fc}"); // ""
m.insert("config.mk", "\u{e615}"); // ""
m.insert("docker-compose.yml", "\u{f308}"); // ""
m.insert("dockerfile", "\u{f308}"); // ""
m.insert("ds_store", "\u{f179}"); // ""
m.insert(".emacs.d", "\u{e615}"); // ""
m.insert("favicon.ico", "\u{f005}"); // ""
m.insert("gitignore_global", "\u{f1d3}"); // ""
m.insert("gradle", "\u{e70e}"); // ""
m.insert("gruntfile.coffee", "\u{e611}"); // ""
m.insert("gruntfile.js", "\u{e611}"); // ""
m.insert("gruntfile.ls", "\u{e611}"); // ""
m.insert("gulpfile.coffee", "\u{e610}"); // ""
m.insert("gulpfile.js", "\u{e610}"); // ""
m.insert("gulpfile.ls", "\u{e610}"); // ""
m.insert("hidden", "\u{f023}"); // ""
m.insert("include", "\u{e5fc}"); // ""
m.insert("known_hosts", "\u{e60a}"); // ""
m.insert("lib", "\u{f121}"); // ""
m.insert("license", "\u{e60a}"); // ""
m.insert("license.md", "\u{e60a}"); // ""
m.insert("license.txt", "\u{e60a}"); // ""
m.insert("localized", "\u{f179}"); // ""
m.insert("makefile", "\u{e615}"); // ""
m.insert("muttrc", "\u{e615}"); // ""
m.insert("node_modules", "\u{e718}"); // ""
m.insert("npmignore", "\u{e71e}"); // ""
m.insert("package.json", "\u{e718}"); // ""
m.insert("package-lock.json", "\u{e718}"); // ""
m.insert("rubydoc", "\u{e73b}"); // ""
m.insert("robots.txt", "\u{fba7}"); // "ﮧ"
m.insert("root", "\u{f023}"); // ""
m.insert("sxhkdrc", "\u{e615}"); // ""
m.insert("vagrantfile", "\u{e615}"); // ""
m.insert("webpack.config.js", "\u{fc29}"); // "ﰩ"
m.insert("xmonad.hs", "\u{e615}"); // ""
m
}
fn get_default_icons_by_extension() -> HashMap<&'static str, &'static str> {
let mut m = HashMap::new();
// Note: extensions must be lower-case
m.insert("1", "\u{f02d}"); // ""
m.insert("7z", "\u{f410}"); // ""
m.insert("a", "\u{e624}"); // ""
m.insert("ai", "\u{e7b4}"); // ""
m.insert("ape", "\u{f001}"); // ""
m.insert("apk", "\u{e70e}"); // ""
m.insert("asm", "\u{e614}"); // ""
m.insert("avi", "\u{f008}"); // ""
m.insert("avro", "\u{e60b}"); // ""
m.insert("awk", "\u{f489}"); // ""
m.insert("bash", "\u{f489}"); // ""
m.insert("bash_history", "\u{f489}"); // ""
m.insert("bash_profile", "\u{f489}"); // ""
m.insert("bashrc", "\u{f489}"); // ""
m.insert("bat", "\u{f17a}"); // ""
m.insert("bin", "\u{f489}"); // ""
m.insert("bio", "\u{f910}"); // "蘿"
m.insert("bmp", "\u{f1c5}"); // ""
m.insert("bz2", "\u{f410}"); // ""
m.insert("c", "\u{e61e}"); // ""
m.insert("c++", "\u{e61d}"); // ""
m.insert("cc", "\u{e61d}"); // ""
m.insert("cfg", "\u{e615}"); // ""
m.insert("cl", "\u{f671}"); // ""
m.insert("class", "\u{e738}"); // ""
m.insert("clj", "\u{e768}"); // ""
m.insert("cljs", "\u{e76a}"); // ""
m.insert("cls", "\u{e600}"); // ""
m.insert("coffee", "\u{f0f4}"); // ""
m.insert("conf", "\u{e615}"); // ""
m.insert("cp", "\u{e61d}"); // ""
m.insert("cpp", "\u{e61d}"); // ""
m.insert("cs", "\u{f81a}"); // ""
m.insert("cshtml", "\u{f1fa}"); // ""
m.insert("csproj", "\u{f81a}"); // ""
m.insert("csx", "\u{f81a}"); // ""
m.insert("csh", "\u{f489}"); // ""
m.insert("css", "\u{e749}"); // ""
m.insert("csv", "\u{f1c3}"); // ""
m.insert("cue", "\u{f001}"); // ""
m.insert("cxx", "\u{e61d}"); // ""
m.insert("d", "\u{e7af}"); // ""
m.insert("dart", "\u{e798}"); // ""
m.insert("db", "\u{f1c0}"); // ""
m.insert("deb", "\u{f187}"); // ""
m.insert("diff", "\u{e728}"); // ""
m.insert("dll", "\u{f17a}"); // ""
m.insert("doc", "\u{f1c2}"); // ""
m.insert("dockerfile", "\u{f308}"); // ""
m.insert("docx", "\u{f1c2}"); // ""
m.insert("ds_store", "\u{f179}"); // ""
m.insert("dump", "\u{f1c0}"); // ""
m.insert("ebook", "\u{e28b}"); // ""
m.insert("editorconfig", "\u{e615}"); // ""
m.insert("ejs", "\u{e618}"); // ""
m.insert("el", "\u{f671}"); // ""
m.insert("elc", "\u{f671}"); // ""
m.insert("elf", "\u{f489}"); // ""
m.insert("elm", "\u{e62c}"); // ""
m.insert("env", "\u{f462}"); // ""
m.insert("eot", "\u{f031}"); // ""
m.insert("epub", "\u{e28a}"); // ""
m.insert("erb", "\u{e73b}"); // ""
m.insert("erl", "\u{e7b1}"); // ""
m.insert("exe", "\u{f17a}"); // ""
m.insert("ex", "\u{e62d}"); // ""
m.insert("exs", "\u{e62d}"); // ""
m.insert("fish", "\u{f489}"); // ""
m.insert("flac", "\u{f001}"); // ""
m.insert("flv", "\u{f008}"); // ""
m.insert("font", "\u{f031}"); // ""
m.insert("fpl", "\u{f910}"); // "蘿"
m.insert("fs", "\u{e7a7}"); // ""
m.insert("fsx", "\u{e7a7}"); // ""
m.insert("fsi", "\u{e7a7}"); // ""
m.insert("gdoc", "\u{f1c2}"); // ""
m.insert("gemfile", "\u{e21e}"); // ""
m.insert("gemspec", "\u{e21e}"); // ""
m.insert("gform", "\u{f298}"); // ""
m.insert("gif", "\u{f1c5}"); // ""
m.insert("git", "\u{f1d3}"); // ""
m.insert("go", "\u{e627}"); // ""
m.insert("gradle", "\u{e70e}"); // ""
m.insert("gsheet", "\u{f1c3}"); // ""
m.insert("gslides", "\u{f1c4}"); // ""
m.insert("guardfile", "\u{e21e}"); // ""
m.insert("gz", "\u{f410}"); // ""
m.insert("h", "\u{f0fd}"); // ""
m.insert("hbs", "\u{e60f}"); // ""
m.insert("heic", "\u{f1c5}"); // ""
m.insert("heif", "\u{f1c5}"); // ""
m.insert("heix", "\u{f1c5}"); // ""
m.insert("hpp", "\u{f0fd}"); // ""
m.insert("hs", "\u{e777}"); // ""
m.insert("htm", "\u{f13b}"); // ""
m.insert("html", "\u{f13b}"); // ""
m.insert("hxx", "\u{f0fd}"); // ""
m.insert("ico", "\u{f1c5}"); // ""
m.insert("image", "\u{f1c5}"); // ""
m.insert("img", "\u{f1c0}"); // ""
m.insert("iml", "\u{e7b5}"); // ""
m.insert("ini", "\u{e615}"); // ""
m.insert("ipynb", "\u{e606}"); // ""
m.insert("iso", "\u{f1c0}"); // ""
m.insert("jar", "\u{e738}"); // ""
m.insert("java", "\u{e738}"); // ""
m.insert("jpeg", "\u{f1c5}"); // ""
m.insert("jpg", "\u{f1c5}"); // ""
m.insert("js", "\u{e74e}"); // ""
m.insert("json", "\u{e60b}"); // ""
m.insert("jsx", "\u{e7ba}"); // ""
m.insert("jl", "\u{e624}"); // ""
m.insert("key", "\u{e60a}"); // ""
m.insert("ksh", "\u{f489}"); // ""
m.insert("ld", "\u{e624}"); // ""
m.insert("less", "\u{e758}"); // ""
m.insert("lhs", "\u{e777}"); // ""
m.insert("license", "\u{e60a}"); // ""
m.insert("lisp", "\u{f671}"); // ""
m.insert("localized", "\u{f179}"); // ""
m.insert("lock", "\u{f023}"); // ""
m.insert("log", "\u{f18d}"); // ""
m.insert("lua", "\u{e620}"); // ""
m.insert("lz", "\u{f410}"); // ""
m.insert("m3u", "\u{f910}"); // "蘿"
m.insert("m3u8", "\u{f910}"); // "蘿"
m.insert("m4a", "\u{f001}"); // ""
m.insert("m4v", "\u{f008}"); // ""
m.insert("magnet", "\u{f076}"); // ""
m.insert("markdown", "\u{e609}"); // ""
m.insert("md", "\u{e609}"); // ""
m.insert("mjs", "\u{e74e}"); // ""
m.insert("mkd", "\u{e609}"); // ""
m.insert("mkv", "\u{f008}"); // ""
m.insert("mobi", "\u{e28b}"); // ""
m.insert("mov", "\u{f008}"); // ""
m.insert("mp3", "\u{f001}"); // ""
m.insert("mp4", "\u{f008}"); // ""
m.insert("msi", "\u{f17a}"); // ""
m.insert("mustache", "\u{e60f}"); // ""
m.insert("nix", "\u{f313}"); // ""
m.insert("npmignore", "\u{e71e}"); // ""
m.insert("o", "\u{e624}"); // ""
m.insert("opus", "\u{f001}"); // ""
m.insert("ogg", "\u{f001}"); // ""
m.insert("ogv", "\u{f008}"); // ""
m.insert("otf", "\u{f031}"); // ""
m.insert("pdf", "\u{f1c1}"); // ""
m.insert("pem", "\u{f805}"); // ""
m.insert("phar", "\u{e608}"); // ""
m.insert("php", "\u{e608}"); // ""
m.insert("pkg", "\u{f187}"); // ""
m.insert("pl", "\u{e769}"); // ""
m.insert("pls", "\u{f910}"); // "蘿"
m.insert("pm", "\u{e769}"); // ""
m.insert("png", "\u{f1c5}"); // ""
m.insert("ppt", "\u{f1c4}"); // ""
m.insert("pptx", "\u{f1c4}"); // ""
m.insert("procfile", "\u{e21e}"); // ""
m.insert("properties", "\u{e60b}"); // ""
m.insert("ps1", "\u{f489}"); // ""
m.insert("psd", "\u{e7b8}"); // ""
m.insert("pub", "\u{e60a}"); // ""
m.insert("pxm", "\u{f1c5}"); // ""
m.insert("py", "\u{e606}"); // ""
m.insert("pyc", "\u{e606}"); // ""
m.insert("r", "\u{fcd2}"); // "ﳒ"
m.insert("rakefile", "\u{e21e}"); // ""
m.insert("rar", "\u{f410}"); // ""
m.insert("razor", "\u{f1fa}"); // ""
m.insert("rb", "\u{e21e}"); // ""
m.insert("rdata", "\u{fcd2}"); // "ﳒ"
m.insert("rdb", "\u{e76d}"); // ""
m.insert("rdoc", "\u{e609}"); // ""
m.insert("rds", "\u{fcd2}"); // "ﳒ"
m.insert("readme", "\u{e609}"); // ""
m.insert("rlib", "\u{e7a8}"); // ""
m.insert("rmd", "\u{e609}"); // ""
m.insert("rpm", "\u{f187}"); // ""
m.insert("rproj", "\u{fac5}"); // "鉶"
m.insert("rs", "\u{e7a8}"); // ""
m.insert("rspec", "\u{e21e}"); // ""
m.insert("rspec_parallel", "\u{e21e}"); // ""
m.insert("rspec_status", "\u{e21e}"); // ""
m.insert("rss", "\u{f09e}"); // ""
m.insert("rtf", "\u{f15c}"); // ""
m.insert("ru", "\u{e21e}"); // ""
m.insert("rubydoc", "\u{e73b}"); // ""
m.insert("s", "\u{e614}"); // ""
m.insert("sass", "\u{e603}"); // ""
m.insert("scala", "\u{e737}"); // ""
m.insert("scpt", "\u{f302}"); // ""
m.insert("scss", "\u{e603}"); // ""
m.insert("sh", "\u{f489}"); // ""
m.insert("shell", "\u{f489}"); // ""
m.insert("sig", "\u{e60a}"); // ""
m.insert("slim", "\u{e73b}"); // ""
m.insert("sln", "\u{e70c}"); // ""
m.insert("so", "\u{e624}"); // ""
m.insert("sql", "\u{f1c0}"); // ""
m.insert("sqlite3", "\u{e7c4}"); // ""
m.insert("srt", "\u{f02d}"); // ""
m.insert("styl", "\u{e600}"); // ""
m.insert("stylus", "\u{e600}"); // ""
m.insert("sub", "\u{f02d}"); // ""
m.insert("svg", "\u{f1c5}"); // ""
m.insert("swift", "\u{e755}"); // ""
m.insert("t", "\u{e769}"); // ""
m.insert("tar", "\u{f410}"); // ""
m.insert("tex", "\u{e600}"); // ""
m.insert("tiff", "\u{f1c5}"); // ""
m.insert("toml", "\u{e60b}"); // ""
m.insert("torrent", "\u{f98c}"); // "歷"
m.insert("ts", "\u{e628}"); // ""
m.insert("tsx", "\u{e7ba}"); // ""
m.insert("ttc", "\u{f031}"); // ""
m.insert("ttf", "\u{f031}"); // ""
m.insert("twig", "\u{e61c}"); // ""
m.insert("txt", "\u{f15c}"); // ""
m.insert("video", "\u{f008}"); // ""
m.insert("vim", "\u{e62b}"); // ""
m.insert("vlc", "\u{f910}"); // "蘿"
m.insert("vue", "\u{fd42}"); // "﵂"
m.insert("wav", "\u{f001}"); // ""
m.insert("webm", "\u{f008}"); // ""
m.insert("webp", "\u{f1c5}"); // ""
m.insert("windows", "\u{f17a}"); // ""
m.insert("wma", "\u{f001}"); // ""
m.insert("wmv", "\u{f008}"); // ""
m.insert("wpl", "\u{f910}"); // "蘿"
m.insert("woff", "\u{f031}"); // ""
m.insert("woff2", "\u{f031}"); // ""
m.insert("xbps", "\u{f187}"); // ""
m.insert("xcf", "\u{f1c5}"); // ""
m.insert("xls", "\u{f1c3}"); // ""
m.insert("xlsx", "\u{f1c3}"); // ""
m.insert("xml", "\u{f121}"); // ""
m.insert("xul", "\u{f269}"); // ""
m.insert("xz", "\u{f410}"); // ""
m.insert("yaml", "\u{e60b}"); // ""
m.insert("yml", "\u{e60b}"); // ""
m.insert("zip", "\u{f410}"); // ""
m.insert("zsh", "\u{f489}"); // ""
m.insert("zsh-theme", "\u{f489}"); // ""
m.insert("zshrc", "\u{f489}"); // ""
m
}
}
#[cfg(test)]
mod test {
use super::{Icons, Theme};
use crate::meta::Meta;
use std::fs::File;
use tempfile::tempdir;
#[test]
fn get_no_icon() {
let tmp_dir = tempdir().expect("failed to create temp dir");
let file_path = tmp_dir.path().join("file.txt");
File::create(&file_path).expect("failed to create file");
let meta = Meta::from_path(&file_path, false).unwrap();
let icon = Icons::new(Theme::NoIcon, " ".to_string());
let icon = icon.get(&meta.name);
assert_eq!(icon, "");
}
#[test]
fn get_default_file_icon() {
let tmp_dir = tempdir().expect("failed to create temp dir");
let file_path = tmp_dir.path().join("file");
File::create(&file_path).expect("failed to create file");
let meta = Meta::from_path(&file_path, false).unwrap();
let icon = Icons::new(Theme::Fancy, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", "\u{f016}", icon.icon_separator)); //
}
#[test]
fn get_default_file_icon_unicode() {
let tmp_dir = tempdir().expect("failed to create temp dir");
let file_path = tmp_dir.path().join("file");
File::create(&file_path).expect("failed to create file");
let meta = Meta::from_path(&file_path, false).unwrap();
let icon = Icons::new(Theme::Unicode, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", "\u{1f5cb}", icon.icon_separator));
}
#[test]
fn get_directory_icon() {
let tmp_dir = tempdir().expect("failed to create temp dir");
let file_path = tmp_dir.path();
let meta = Meta::from_path(&file_path.to_path_buf(), false).unwrap();
let icon = Icons::new(Theme::Fancy, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", "\u{f115}", icon.icon_separator)); //
}
#[test]
fn get_directory_icon_unicode() {
let tmp_dir = tempdir().expect("failed to create temp dir");
let file_path = tmp_dir.path();
let meta = Meta::from_path(&file_path.to_path_buf(), false).unwrap();
let icon = Icons::new(Theme::Unicode, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", "\u{1f5c1}", icon.icon_separator));
}
#[test]
fn get_directory_icon_with_ext() {
let tmp_dir = tempdir().expect("failed to create temp dir");
let file_path = tmp_dir.path();
let meta = Meta::from_path(&file_path.to_path_buf(), false).unwrap();
let icon = Icons::new(Theme::Fancy, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", "\u{f115}", icon.icon_separator)); //
}
#[test]
fn get_icon_by_name() {
let tmp_dir = tempdir().expect("failed to create temp dir");
for (file_name, file_icon) in &Icons::get_default_icons_by_name() {
let file_path = tmp_dir.path().join(file_name);
File::create(&file_path).expect("failed to create file");
let meta = Meta::from_path(&file_path, false).unwrap();
let icon = Icons::new(Theme::Fancy, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", file_icon, icon.icon_separator));
}
}
#[test]
fn get_icon_by_extension() {
let tmp_dir = tempdir().expect("failed to create temp dir");
for (ext, file_icon) in &Icons::get_default_icons_by_extension() {
let file_path = tmp_dir.path().join(format!("file.{}", ext));
File::create(&file_path).expect("failed to create file");
let meta = Meta::from_path(&file_path, false).unwrap();
let icon = Icons::new(Theme::Fancy, " ".to_string());
let icon_str = icon.get(&meta.name);
assert_eq!(icon_str, format!("{}{}", file_icon, icon.icon_separator));
}
}
}
| 40.273063 | 89 | 0.429723 |
7253c808c8569979f2793f56db8d571b33ab5fea
| 1,363 |
#![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "package-2016-03")]
mod package_2016_03;
#[cfg(feature = "package-2016-03")]
pub use package_2016_03::{models, operations, API_VERSION};
#[cfg(feature = "package-2016-01")]
mod package_2016_01;
#[cfg(feature = "package-2016-01")]
pub use package_2016_01::{models, operations, API_VERSION};
#[cfg(feature = "package-2014-08-preview")]
mod package_2014_08_preview;
#[cfg(feature = "package-2014-08-preview")]
pub use package_2014_08_preview::{models, operations, API_VERSION};
pub struct OperationConfig {
pub api_version: String,
pub client: reqwest::Client,
pub base_path: String,
pub token_credential: Option<Box<dyn azure_core::TokenCredential>>,
pub token_credential_resource: String,
}
impl OperationConfig {
pub fn new(token_credential: Box<dyn azure_core::TokenCredential>) -> Self {
Self {
token_credential: Some(token_credential),
..Default::default()
}
}
}
impl Default for OperationConfig {
fn default() -> Self {
Self {
api_version: API_VERSION.to_owned(),
client: reqwest::Client::new(),
base_path: "https://management.azure.com".to_owned(),
token_credential: None,
token_credential_resource: "https://management.azure.com/".to_owned(),
}
}
}
| 34.075 | 82 | 0.668379 |
7137920f116c516527b0978fc5aaf78d38d95731
| 163 |
use vergen::{generate_cargo_keys, ConstantsFlags};
fn main() {
generate_cargo_keys(ConstantsFlags::SHA_SHORT).expect("Unable to generate the cargo keys!");
}
| 27.166667 | 96 | 0.760736 |
4a490b1b9fa57f67d2a8d640674b1d286c4b1875
| 30 |
pub mod data;
pub mod codec;
| 7.5 | 14 | 0.7 |
1c7d0b76a643ea17e8b5a40c4cf02363345155dc
| 17,438 |
// 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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use hir::def_id::CrateNum;
use session;
use session::config;
use ty::TyCtxt;
use middle::cstore::{self, DepKind};
use middle::cstore::LinkagePreference::{self, RequireStatic, RequireDynamic};
use util::nodemap::FxHashMap;
use rustc_back::PanicStrategy;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Linkage>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = FxHashMap<config::CrateType, DependencyList>;
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Linkage {
NotLinked,
IncludedFromDylib,
Static,
Dynamic,
}
pub fn calculate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let sess = &tcx.sess;
let mut fmts = sess.dependency_formats.borrow_mut();
for &ty in sess.crate_types.borrow().iter() {
let linkage = calculate_type(tcx, ty);
verify_ok(tcx, &linkage);
fmts.insert(ty, linkage);
}
sess.abort_if_errors();
}
fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
ty: config::CrateType) -> DependencyList {
let sess = &tcx.sess;
if !sess.opts.output_types.should_trans() {
return Vec::new();
}
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
if let Some(v) = attempt_static(tcx) {
return v;
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs and cdylibs must have all static dependencies. If any fail
// to be found, we generate some nice pretty errors.
config::CrateTypeStaticlib |
config::CrateTypeCdylib => {
if let Some(v) = attempt_static(tcx) {
return v;
}
for &cnum in tcx.crates().iter() {
if tcx.dep_kind(cnum).macros_only() { continue }
let src = tcx.used_crate_source(cnum);
if src.rlib.is_some() { continue }
sess.err(&format!("dependency `{}` not found in rlib format",
tcx.crate_name(cnum)));
}
return Vec::new();
}
// Generating a dylib without `-C prefer-dynamic` means that we're going
// to try to eagerly statically link all dependencies. This is normally
// done for end-product dylibs, not intermediate products.
config::CrateTypeDylib if !sess.opts.cg.prefer_dynamic => {
if let Some(v) = attempt_static(tcx) {
return v;
}
}
// Everything else falls through below. This will happen either with the
// `-C prefer-dynamic` or because we're a proc-macro crate. Note that
// proc-macro crates are required to be dylibs, and they're currently
// required to link to libsyntax as well.
config::CrateTypeExecutable |
config::CrateTypeDylib |
config::CrateTypeProcMacro => {},
}
let mut formats = FxHashMap();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
for &cnum in tcx.crates().iter() {
if tcx.dep_kind(cnum).macros_only() { continue }
let name = tcx.crate_name(cnum);
let src = tcx.used_crate_source(cnum);
if src.dylib.is_some() {
info!("adding dylib: {}", name);
add_library(tcx, cnum, RequireDynamic, &mut formats);
let deps = tcx.dylib_dependency_formats(cnum);
for &(depnum, style) in deps.iter() {
info!("adding {:?}: {}", style, tcx.crate_name(depnum));
add_library(tcx, depnum, style, &mut formats);
}
}
}
// Collect what we've got so far in the return vector.
let last_crate = tcx.crates().len();
let mut ret = (1..last_crate+1).map(|cnum| {
match formats.get(&CrateNum::new(cnum)) {
Some(&RequireDynamic) => Linkage::Dynamic,
Some(&RequireStatic) => Linkage::IncludedFromDylib,
None => Linkage::NotLinked,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
//
// If the crate hasn't been included yet and it's not actually required
// (e.g. it's an allocator) then we skip it here as well.
for &cnum in tcx.crates().iter() {
let src = tcx.used_crate_source(cnum);
if src.dylib.is_none() &&
!formats.contains_key(&cnum) &&
tcx.dep_kind(cnum) == DepKind::Explicit {
assert!(src.rlib.is_some() || src.rmeta.is_some());
info!("adding staticlib: {}", tcx.crate_name(cnum));
add_library(tcx, cnum, RequireStatic, &mut formats);
ret[cnum.as_usize() - 1] = Linkage::Static;
}
}
// We've gotten this far because we're emitting some form of a final
// artifact which means that we may need to inject dependencies of some
// form.
//
// Things like allocators and panic runtimes may not have been activated
// quite yet, so do so here.
activate_injected_dep(sess.injected_panic_runtime.get(), &mut ret,
&|cnum| tcx.is_panic_runtime(cnum));
activate_injected_allocator(sess, &mut ret);
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = CrateNum::new(cnum + 1);
let src = tcx.used_crate_source(cnum);
match *kind {
Linkage::NotLinked |
Linkage::IncludedFromDylib => {}
Linkage::Static if src.rlib.is_some() => continue,
Linkage::Dynamic if src.dylib.is_some() => continue,
kind => {
let kind = match kind {
Linkage::Static => "rlib",
_ => "dylib",
};
let name = tcx.crate_name(cnum);
sess.err(&format!("crate `{}` required to be available in {}, \
but it was not available in this form",
name, kind));
}
}
}
return ret;
}
fn add_library(tcx: TyCtxt,
cnum: CrateNum,
link: LinkagePreference,
m: &mut FxHashMap<CrateNum, LinkagePreference>) {
match m.get(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2 != link || link == RequireStatic {
tcx.sess.struct_err(&format!("cannot satisfy dependencies so `{}` only \
shows up once", tcx.crate_name(cnum)))
.help("having upstream crates all available in one format \
will likely make this go away")
.emit();
}
}
None => { m.insert(cnum, link); }
}
}
fn attempt_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<DependencyList> {
let sess = &tcx.sess;
let crates = cstore::used_crates(tcx, RequireStatic);
if !crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
return None
}
// All crates are available in an rlib format, so we're just going to link
// everything in explicitly so long as it's actually required.
let last_crate = tcx.crates().len();
let mut ret = (1..last_crate+1).map(|cnum| {
if tcx.dep_kind(CrateNum::new(cnum)) == DepKind::Explicit {
Linkage::Static
} else {
Linkage::NotLinked
}
}).collect::<Vec<_>>();
// Our allocator/panic runtime may not have been linked above if it wasn't
// explicitly linked, which is the case for any injected dependency. Handle
// that here and activate them.
activate_injected_dep(sess.injected_panic_runtime.get(), &mut ret,
&|cnum| tcx.is_panic_runtime(cnum));
activate_injected_allocator(sess, &mut ret);
Some(ret)
}
// Given a list of how to link upstream dependencies so far, ensure that an
// injected dependency is activated. This will not do anything if one was
// transitively included already (e.g. via a dylib or explicitly so).
//
// If an injected dependency was not found then we're guaranteed the
// metadata::creader module has injected that dependency (not listed as
// a required dependency) in one of the session's field. If this field is not
// set then this compilation doesn't actually need the dependency and we can
// also skip this step entirely.
fn activate_injected_dep(injected: Option<CrateNum>,
list: &mut DependencyList,
replaces_injected: &Fn(CrateNum) -> bool) {
for (i, slot) in list.iter().enumerate() {
let cnum = CrateNum::new(i + 1);
if !replaces_injected(cnum) {
continue
}
if *slot != Linkage::NotLinked {
return
}
}
if let Some(injected) = injected {
let idx = injected.as_usize() - 1;
assert_eq!(list[idx], Linkage::NotLinked);
list[idx] = Linkage::Static;
}
}
fn activate_injected_allocator(sess: &session::Session,
list: &mut DependencyList) {
let cnum = match sess.injected_allocator.get() {
Some(cnum) => cnum,
None => return,
};
let idx = cnum.as_usize() - 1;
if list[idx] == Linkage::NotLinked {
list[idx] = Linkage::Static;
}
}
// After the linkage for a crate has been determined we need to verify that
// there's only going to be one allocator in the output.
fn verify_ok<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, list: &[Linkage]) {
let sess = &tcx.sess;
if list.len() == 0 {
return
}
let mut panic_runtime = None;
for (i, linkage) in list.iter().enumerate() {
if let Linkage::NotLinked = *linkage {
continue
}
let cnum = CrateNum::new(i + 1);
if tcx.is_panic_runtime(cnum) {
if let Some((prev, _)) = panic_runtime {
let prev_name = tcx.crate_name(prev);
let cur_name = tcx.crate_name(cnum);
sess.err(&format!("cannot link together two \
panic runtimes: {} and {}",
prev_name, cur_name));
}
panic_runtime = Some((cnum, tcx.panic_strategy(cnum)));
}
}
// If we found a panic runtime, then we know by this point that it's the
// only one, but we perform validation here that all the panic strategy
// compilation modes for the whole DAG are valid.
if let Some((cnum, found_strategy)) = panic_runtime {
let desired_strategy = sess.panic_strategy();
// First up, validate that our selected panic runtime is indeed exactly
// our same strategy.
if found_strategy != desired_strategy {
sess.err(&format!("the linked panic runtime `{}` is \
not compiled with this crate's \
panic strategy `{}`",
tcx.crate_name(cnum),
desired_strategy.desc()));
}
// Next up, verify that all other crates are compatible with this panic
// strategy. If the dep isn't linked, we ignore it, and if our strategy
// is abort then it's compatible with everything. Otherwise all crates'
// panic strategy must match our own.
for (i, linkage) in list.iter().enumerate() {
if let Linkage::NotLinked = *linkage {
continue
}
if desired_strategy == PanicStrategy::Abort {
continue
}
let cnum = CrateNum::new(i + 1);
let found_strategy = tcx.panic_strategy(cnum);
let is_compiler_builtins = tcx.is_compiler_builtins(cnum);
if is_compiler_builtins || desired_strategy == found_strategy {
continue
}
sess.err(&format!("the crate `{}` is compiled with the \
panic strategy `{}` which is \
incompatible with this crate's \
strategy of `{}`",
tcx.crate_name(cnum),
found_strategy.desc(),
desired_strategy.desc()));
}
}
}
| 42.22276 | 88 | 0.604198 |
cc85f68c197ec34551df74a1742b7d171ddf5bc5
| 3,868 |
// Copyright 2012-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.
use rustc::mir;
use base;
use common::{self, BlockAndBuilder};
use super::MirContext;
use super::LocalRef;
use super::super::adt;
use super::super::disr::Disr;
impl<'a, 'tcx> MirContext<'a, 'tcx> {
pub fn trans_statement(&mut self,
bcx: BlockAndBuilder<'a, 'tcx>,
statement: &mir::Statement<'tcx>)
-> BlockAndBuilder<'a, 'tcx> {
debug!("trans_statement(statement={:?})", statement);
self.set_debug_loc(&bcx, statement.source_info);
match statement.kind {
mir::StatementKind::Assign(ref lvalue, ref rvalue) => {
if let mir::Lvalue::Local(index) = *lvalue {
match self.locals[index] {
LocalRef::Lvalue(tr_dest) => {
self.trans_rvalue(bcx, tr_dest, rvalue)
}
LocalRef::Operand(None) => {
let (bcx, operand) = self.trans_rvalue_operand(bcx, rvalue);
self.locals[index] = LocalRef::Operand(Some(operand));
bcx
}
LocalRef::Operand(Some(_)) => {
let ty = self.monomorphized_lvalue_ty(lvalue);
if !common::type_is_zero_size(bcx.ccx, ty) {
span_bug!(statement.source_info.span,
"operand {:?} already assigned",
rvalue);
} else {
// If the type is zero-sized, it's already been set here,
// but we still need to make sure we translate the operand
self.trans_rvalue_operand(bcx, rvalue).0
}
}
}
} else {
let tr_dest = self.trans_lvalue(&bcx, lvalue);
self.trans_rvalue(bcx, tr_dest, rvalue)
}
}
mir::StatementKind::SetDiscriminant{ref lvalue, variant_index} => {
let ty = self.monomorphized_lvalue_ty(lvalue);
let lvalue_transed = self.trans_lvalue(&bcx, lvalue);
adt::trans_set_discr(&bcx,
ty,
lvalue_transed.llval,
Disr::from(variant_index));
bcx
}
mir::StatementKind::StorageLive(ref lvalue) => {
self.trans_storage_liveness(bcx, lvalue, base::Lifetime::Start)
}
mir::StatementKind::StorageDead(ref lvalue) => {
self.trans_storage_liveness(bcx, lvalue, base::Lifetime::End)
}
mir::StatementKind::Nop => bcx,
}
}
fn trans_storage_liveness(&self,
bcx: BlockAndBuilder<'a, 'tcx>,
lvalue: &mir::Lvalue<'tcx>,
intrinsic: base::Lifetime)
-> BlockAndBuilder<'a, 'tcx> {
if let mir::Lvalue::Local(index) = *lvalue {
if let LocalRef::Lvalue(tr_lval) = self.locals[index] {
intrinsic.call(&bcx, tr_lval.llval);
}
}
bcx
}
}
| 42.043478 | 90 | 0.486556 |
9b1c0a89cca3bbe0e01c4315b4bec3034d9d48e7
| 8,000 |
use crate::cfg::Cfg;
use crate::err::ProcessingResult;
use crate::gen::codepoints::{TAG_NAME_CHAR, WHITESPACE};
use crate::proc::checkpoint::ReadCheckpoint;
use crate::proc::entity::maybe_normalise_entity;
use crate::proc::MatchAction::*;
use crate::proc::MatchMode::*;
use crate::proc::Processor;
use crate::proc::range::ProcessorRange;
use crate::spec::tag::ns::Namespace;
use crate::spec::tag::omission::{can_omit_as_before, can_omit_as_last_node};
use crate::spec::tag::whitespace::{get_whitespace_minification_for_tag, WhitespaceMinification};
use crate::unit::bang::process_bang;
use crate::unit::comment::process_comment;
use crate::unit::instruction::process_instruction;
use crate::unit::tag::{MaybeClosingTag, process_tag};
#[derive(Copy, Clone, PartialEq, Eq)]
enum ContentType {
Comment,
Bang,
Instruction,
Tag,
Start,
End,
Text,
}
impl ContentType {
fn peek(proc: &mut Processor) -> ContentType {
// Manually write out matching for fast performance as this is hot spot; don't use generated trie.
match proc.peek(0) {
None => ContentType::End,
Some(b'<') => match proc.peek(1) {
Some(b'/') => ContentType::End,
Some(b'?') => ContentType::Instruction,
Some(b'!') => match proc.peek_many(2, 2) {
Some(b"--") => ContentType::Comment,
_ => ContentType::Bang,
},
Some(c) if TAG_NAME_CHAR[c] => ContentType::Tag,
_ => ContentType::Text,
},
Some(_) => ContentType::Text,
}
}
}
pub struct ProcessedContent {
pub closing_tag_omitted: bool,
}
pub fn process_content(proc: &mut Processor, cfg: &Cfg, ns: Namespace, parent: Option<ProcessorRange>, descendant_of_pre: bool) -> ProcessingResult<ProcessedContent> {
let &WhitespaceMinification { collapse, destroy_whole, trim } = get_whitespace_minification_for_tag(parent.map(|r| &proc[r]), descendant_of_pre);
let handle_ws = collapse || destroy_whole || trim;
let mut last_written = ContentType::Start;
// Whether or not currently in whitespace.
let mut ws_skipped = false;
let mut prev_sibling_closing_tag = MaybeClosingTag::none();
loop {
// WARNING: Do not write anything until any previously ignored whitespace has been processed later.
// Process comments, bangs, and instructions, which are completely ignored and do not affect anything (previous
// element node's closing tag, unintentional entities, whitespace, etc.).
let next_content_type = ContentType::peek(proc);
match next_content_type {
ContentType::Comment => {
process_comment(proc)?;
continue;
}
ContentType::Bang => {
process_bang(proc)?;
continue;
}
ContentType::Instruction => {
process_instruction(proc)?;
continue;
}
_ => {}
};
maybe_normalise_entity(proc);
if handle_ws {
if next_content_type == ContentType::Text && proc.m(IsInLookup(WHITESPACE), Discard).nonempty() {
// This is the start or part of one or more whitespace characters.
// Simply ignore and process until first non-whitespace.
ws_skipped = true;
continue;
};
// Next character is not whitespace, so handle any previously ignored whitespace.
if ws_skipped {
if destroy_whole && last_written == ContentType::Tag && next_content_type == ContentType::Tag {
// Whitespace is between two tags, instructions, or bangs.
// `destroy_whole` is on, so don't write it.
} else if trim && (last_written == ContentType::Start || next_content_type == ContentType::End) {
// Whitespace is leading or trailing.
// `trim` is on, so don't write it.
} else if collapse {
// If writing space, then prev_sibling_closing_tag no longer represents immediate previous sibling
// node; space will be new previous sibling node (as a text node).
prev_sibling_closing_tag.write_if_exists(proc);
// Current contiguous whitespace needs to be reduced to a single space character.
proc.write(b' ');
last_written = ContentType::Text;
} else {
unreachable!();
};
// Reset whitespace marker.
ws_skipped = false;
};
};
// Process and consume next character(s).
match next_content_type {
ContentType::Tag => {
let tag_checkpoint = ReadCheckpoint::new(proc);
proc.skip_expect();
let tag_name = proc.m(WhileInLookup(TAG_NAME_CHAR), Discard).require("tag name")?;
proc.make_lowercase(tag_name);
if can_omit_as_before(proc, parent, tag_name) {
// TODO Is this necessary? Can a previous closing tag even exist?
prev_sibling_closing_tag.write_if_exists(proc);
tag_checkpoint.restore(proc);
return Ok(ProcessedContent {
closing_tag_omitted: true,
});
};
let new_closing_tag = process_tag(proc, cfg, ns, parent, descendant_of_pre || ns == Namespace::Html && parent.filter(|p| &proc[*p] == b"pre").is_some(), prev_sibling_closing_tag, tag_name)?;
prev_sibling_closing_tag.replace(new_closing_tag);
}
ContentType::End => {
if prev_sibling_closing_tag.exists_and(|prev_tag| !can_omit_as_last_node(proc, parent, prev_tag)) {
prev_sibling_closing_tag.write(proc);
};
break;
}
ContentType::Text => {
// Immediate next sibling node is not an element, so write any immediate previous sibling element's closing tag.
if prev_sibling_closing_tag.exists() {
prev_sibling_closing_tag.write(proc);
};
let c = proc.peek(0).unwrap();
// From the spec: https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
// After a `<`, a valid character is an ASCII alpha, `/`, `!`, or `?`. Anything
// else, and the `<` is treated as content.
if proc.last_is(b'<') && (
TAG_NAME_CHAR[c] || c == b'?' || c == b'!' || c == b'/'
) {
// We need to encode the `<` that we just wrote as otherwise this char will
// cause it to be interpreted as something else (e.g. opening tag).
// NOTE: This conditional should mean that we never have to worry about a
// semicolon after encoded `<` becoming `<` and part of the entity, as the
// only time `<` appears is when we write it here; every other time we always
// decode any encoded `<`.
// TODO Optimise, maybe using last written flag.
proc.undo_write(1);
// We use `LT` because no other named entity starts with it so it can't be
// misinterpreted as another entity or require a semicolon.
proc.write_slice(b"<");
};
proc.accept_expect();
}
_ => unreachable!(),
};
// This should not be reached if ContentType::{Comment, End}.
last_written = next_content_type;
};
Ok(ProcessedContent {
closing_tag_omitted: false,
})
}
| 43.010753 | 206 | 0.5655 |
e58e1f06954246a69bfa6dd966937e41bf2ae281
| 2,295 |
pub use gl_layer_types::*;
use platform_types::{CharDim};
use shared::Res;
pub struct State<'font> {
open_gl: open_gl::State,
text_rendering: text_rendering::State<'font>,
}
pub use text_rendering::FONT_LICENSE;
pub fn init<F>(
hidpi_factor: f32,
text_sizes: &'static [f32],
clear_colour: [f32; 4], // the clear colour currently flashes up on exit.
load_fn: F,
) -> Res<(State<'static>, Vec<CharDim>)>
where
F: FnMut(&'static str) -> open_gl::LoadFnOutput,
{
let (text_rendering_state, char_dims) = text_rendering::new(
hidpi_factor,
text_sizes
)?;
Ok((
State {
open_gl: open_gl:: State::new(clear_colour, text_rendering_state.texture_dimensions(), load_fn)?,
text_rendering: text_rendering_state,
},
char_dims,
))
}
pub fn set_dimensions(state: &mut State, hidpi_factor: f32, wh: (i32, i32)) {
state.open_gl.set_dimensions(wh);
state.text_rendering.set_dimensions(hidpi_factor);
}
#[perf_viz::record]
pub fn render(
state: &mut State,
text_or_rects: Vec<TextOrRect>,
width: u32,
height: u32,
) -> Res<()> {
state.open_gl.begin_frame();
let resize_texture = |new_width: u32, new_height: u32| {
eprint!("\r \r");
eprintln!("Resizing glyph texture -> {}x{}", new_width, new_height);
open_gl::State::resize_texture(new_width, new_height);
};
let replacement_vertices = state.text_rendering.render_vertices(
text_or_rects,
(width, height),
|rect: text_rendering::TextureRect, tex_data: &_| {
// Update part of gpu texture with new glyph alpha values
open_gl::State::update_texture(
rect.min.x as _,
rect.min.y as _,
rect.width() as _,
rect.height() as _,
tex_data,
);
},
resize_texture,
);
if let Some(vertices) = replacement_vertices {
perf_viz::record_guard!("open_gl.draw_vertices");
state.open_gl.draw_vertices(vertices);
}
state.open_gl.end_frame();
Ok(())
}
pub fn cleanup(
state: &State,
) -> Res<()> {
state.open_gl.cleanup()
}
| 26.37931 | 109 | 0.586057 |
90bfd492e76b7603780c9255b6221853ce0336dc
| 3,517 |
//! # fields
//! All necessery functions for appliying fields to json results.
use serde_json::Value;
use serde_json;
use service::query_api::Queries;
/// let only named fields array according to the query api
pub fn apply(obj: &mut Value, queries: &Queries) {
let ref fields = queries.fields;
if fields.len() == 0 {
return;
}
match obj {
&mut Value::Array(ref mut arr) => {
let mut i = 0usize;
let size = (&arr.len()).clone();
let remove_keys = match arr.get(0) {
Some(item) => {
if let &Value::Object(ref map) = item {
diff_left(map.keys(), fields)
} else {
Vec::<String>::new()
}
}
None => Vec::<String>::new(),
};
while i < size {
let map_val = arr.get_mut(i).unwrap();
if let &mut Value::Object(ref mut obj) = map_val {
for key in &remove_keys {
obj.remove(key);
}
}
i += 1;
}
}
&mut Value::Object(ref mut map) => {
let remove_keys = diff_left(map.keys(), fields);
for key in &remove_keys {
map.remove(key);
}
}
_ => {
//No need to handle other types
}
}
}
fn diff_left(a: serde_json::map::Keys, b: &Vec<String>) -> Vec<String> {
let mut diff = Vec::<String>::new();
'outer: for a_item in a {
for b_item in b {
if a_item == b_item {
continue 'outer;
}
}
diff.push(a_item.clone());
}
diff
}
#[cfg(test)]
mod tests {
use super::*;
fn get_json() -> Value {
let json_string = r#"[
{
"name":"seray",
"age":31,
"active":true,
"password":"123"
},
{
"name":"kamil",
"age":900,
"active":false,
"password":"333"
},
{
"name":"hasan",
"age":25,
"active":true,
"password":"321"
}
]"#;
serde_json::from_str(&json_string).unwrap()
}
#[test]
fn apply_test() {
let mut queries = Queries::new();
{
let fields = &mut queries.fields;
fields.push("name".to_string());
fields.push("active".to_string());
}
let expected: Value = serde_json::from_str(&r#"[
{
"name":"seray",
"active":true
},
{
"name":"kamil",
"active":false
},
{
"name":"hasan",
"active":true
}
]"#)
.unwrap();
let json = &mut get_json();
apply(json, &queries);
assert_eq!(json.clone(), expected);
}
#[test]
fn diff_left_test() {
let mut a = serde_json::Map::<String, Value>::new();
a.insert("a".to_string(), Value::Null);
a.insert("b".to_string(), Value::Null);
a.insert("c".to_string(), Value::Null);
let b = vec!["b".to_string(), "c".to_string()];
let r = diff_left(a.keys(), &b);
assert_eq!(r, vec!["a".to_string()]);
}
}
| 27.263566 | 72 | 0.411999 |
56e452803e8f2a0628f425ff351902c97eb8f5e0
| 77,325 |
/**
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree. An additional
* directory.
*
**
*
* THIS FILE IS @generated; DO NOT EDIT IT
* To regenerate this file, run
*
* buck run //hphp/hack/src:generate_full_fidelity
*
**
*
*/
use super::{
has_arena::HasArena,
syntax::*, syntax_variant_generated::*,
};
use crate::{
lexable_token::LexableToken,
syntax::{SyntaxType, SyntaxValueType},
};
impl<'a, C, T, V> SyntaxType<C> for Syntax<'a, T, V>
where
T: LexableToken + Copy,
V: SyntaxValueType<T>,
C: HasArena<'a>,
{
fn make_end_of_file(ctx: &C, token: Self) -> Self {
let syntax = SyntaxVariant::EndOfFile(ctx.get_arena().alloc(EndOfFileChildren {
token,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_script(ctx: &C, declarations: Self) -> Self {
let syntax = SyntaxVariant::Script(ctx.get_arena().alloc(ScriptChildren {
declarations,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_qualified_name(ctx: &C, parts: Self) -> Self {
let syntax = SyntaxVariant::QualifiedName(ctx.get_arena().alloc(QualifiedNameChildren {
parts,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_simple_type_specifier(ctx: &C, specifier: Self) -> Self {
let syntax = SyntaxVariant::SimpleTypeSpecifier(ctx.get_arena().alloc(SimpleTypeSpecifierChildren {
specifier,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_literal_expression(ctx: &C, expression: Self) -> Self {
let syntax = SyntaxVariant::LiteralExpression(ctx.get_arena().alloc(LiteralExpressionChildren {
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_prefixed_string_expression(ctx: &C, name: Self, str: Self) -> Self {
let syntax = SyntaxVariant::PrefixedStringExpression(ctx.get_arena().alloc(PrefixedStringExpressionChildren {
name,
str,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_prefixed_code_expression(ctx: &C, prefix: Self, left_backtick: Self, expression: Self, right_backtick: Self) -> Self {
let syntax = SyntaxVariant::PrefixedCodeExpression(ctx.get_arena().alloc(PrefixedCodeExpressionChildren {
prefix,
left_backtick,
expression,
right_backtick,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_variable_expression(ctx: &C, expression: Self) -> Self {
let syntax = SyntaxVariant::VariableExpression(ctx.get_arena().alloc(VariableExpressionChildren {
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_pipe_variable_expression(ctx: &C, expression: Self) -> Self {
let syntax = SyntaxVariant::PipeVariableExpression(ctx.get_arena().alloc(PipeVariableExpressionChildren {
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_file_attribute_specification(ctx: &C, left_double_angle: Self, keyword: Self, colon: Self, attributes: Self, right_double_angle: Self) -> Self {
let syntax = SyntaxVariant::FileAttributeSpecification(ctx.get_arena().alloc(FileAttributeSpecificationChildren {
left_double_angle,
keyword,
colon,
attributes,
right_double_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_declaration(ctx: &C, attribute_spec: Self, keyword: Self, name: Self, colon: Self, base: Self, type_: Self, left_brace: Self, use_clauses: Self, enumerators: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::EnumDeclaration(ctx.get_arena().alloc(EnumDeclarationChildren {
attribute_spec,
keyword,
name,
colon,
base,
type_,
left_brace,
use_clauses,
enumerators,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_use(ctx: &C, keyword: Self, names: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::EnumUse(ctx.get_arena().alloc(EnumUseChildren {
keyword,
names,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enumerator(ctx: &C, name: Self, equal: Self, value: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::Enumerator(ctx.get_arena().alloc(EnumeratorChildren {
name,
equal,
value,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_class_declaration(ctx: &C, attribute_spec: Self, enum_keyword: Self, class_keyword: Self, name: Self, colon: Self, base: Self, extends: Self, extends_list: Self, left_brace: Self, elements: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::EnumClassDeclaration(ctx.get_arena().alloc(EnumClassDeclarationChildren {
attribute_spec,
enum_keyword,
class_keyword,
name,
colon,
base,
extends,
extends_list,
left_brace,
elements,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_class_enumerator(ctx: &C, type_: Self, name: Self, equal: Self, initial_value: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::EnumClassEnumerator(ctx.get_arena().alloc(EnumClassEnumeratorChildren {
type_,
name,
equal,
initial_value,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_record_declaration(ctx: &C, attribute_spec: Self, modifier: Self, keyword: Self, name: Self, extends_keyword: Self, extends_opt: Self, left_brace: Self, fields: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::RecordDeclaration(ctx.get_arena().alloc(RecordDeclarationChildren {
attribute_spec,
modifier,
keyword,
name,
extends_keyword,
extends_opt,
left_brace,
fields,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_record_field(ctx: &C, type_: Self, name: Self, init: Self, semi: Self) -> Self {
let syntax = SyntaxVariant::RecordField(ctx.get_arena().alloc(RecordFieldChildren {
type_,
name,
init,
semi,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_alias_declaration(ctx: &C, attribute_spec: Self, keyword: Self, name: Self, generic_parameter: Self, constraint: Self, equal: Self, type_: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::AliasDeclaration(ctx.get_arena().alloc(AliasDeclarationChildren {
attribute_spec,
keyword,
name,
generic_parameter,
constraint,
equal,
type_,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_property_declaration(ctx: &C, attribute_spec: Self, modifiers: Self, type_: Self, declarators: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::PropertyDeclaration(ctx.get_arena().alloc(PropertyDeclarationChildren {
attribute_spec,
modifiers,
type_,
declarators,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_property_declarator(ctx: &C, name: Self, initializer: Self) -> Self {
let syntax = SyntaxVariant::PropertyDeclarator(ctx.get_arena().alloc(PropertyDeclaratorChildren {
name,
initializer,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_declaration(ctx: &C, header: Self, body: Self) -> Self {
let syntax = SyntaxVariant::NamespaceDeclaration(ctx.get_arena().alloc(NamespaceDeclarationChildren {
header,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_declaration_header(ctx: &C, keyword: Self, name: Self) -> Self {
let syntax = SyntaxVariant::NamespaceDeclarationHeader(ctx.get_arena().alloc(NamespaceDeclarationHeaderChildren {
keyword,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_body(ctx: &C, left_brace: Self, declarations: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::NamespaceBody(ctx.get_arena().alloc(NamespaceBodyChildren {
left_brace,
declarations,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_empty_body(ctx: &C, semicolon: Self) -> Self {
let syntax = SyntaxVariant::NamespaceEmptyBody(ctx.get_arena().alloc(NamespaceEmptyBodyChildren {
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_use_declaration(ctx: &C, keyword: Self, kind: Self, clauses: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::NamespaceUseDeclaration(ctx.get_arena().alloc(NamespaceUseDeclarationChildren {
keyword,
kind,
clauses,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_group_use_declaration(ctx: &C, keyword: Self, kind: Self, prefix: Self, left_brace: Self, clauses: Self, right_brace: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::NamespaceGroupUseDeclaration(ctx.get_arena().alloc(NamespaceGroupUseDeclarationChildren {
keyword,
kind,
prefix,
left_brace,
clauses,
right_brace,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_namespace_use_clause(ctx: &C, clause_kind: Self, name: Self, as_: Self, alias: Self) -> Self {
let syntax = SyntaxVariant::NamespaceUseClause(ctx.get_arena().alloc(NamespaceUseClauseChildren {
clause_kind,
name,
as_,
alias,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_declaration(ctx: &C, attribute_spec: Self, declaration_header: Self, body: Self) -> Self {
let syntax = SyntaxVariant::FunctionDeclaration(ctx.get_arena().alloc(FunctionDeclarationChildren {
attribute_spec,
declaration_header,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_declaration_header(ctx: &C, modifiers: Self, keyword: Self, name: Self, type_parameter_list: Self, left_paren: Self, parameter_list: Self, right_paren: Self, contexts: Self, colon: Self, readonly_return: Self, type_: Self, where_clause: Self) -> Self {
let syntax = SyntaxVariant::FunctionDeclarationHeader(ctx.get_arena().alloc(FunctionDeclarationHeaderChildren {
modifiers,
keyword,
name,
type_parameter_list,
left_paren,
parameter_list,
right_paren,
contexts,
colon,
readonly_return,
type_,
where_clause,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_contexts(ctx: &C, left_bracket: Self, types: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::Contexts(ctx.get_arena().alloc(ContextsChildren {
left_bracket,
types,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_where_clause(ctx: &C, keyword: Self, constraints: Self) -> Self {
let syntax = SyntaxVariant::WhereClause(ctx.get_arena().alloc(WhereClauseChildren {
keyword,
constraints,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_where_constraint(ctx: &C, left_type: Self, operator: Self, right_type: Self) -> Self {
let syntax = SyntaxVariant::WhereConstraint(ctx.get_arena().alloc(WhereConstraintChildren {
left_type,
operator,
right_type,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_methodish_declaration(ctx: &C, attribute: Self, function_decl_header: Self, function_body: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::MethodishDeclaration(ctx.get_arena().alloc(MethodishDeclarationChildren {
attribute,
function_decl_header,
function_body,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_methodish_trait_resolution(ctx: &C, attribute: Self, function_decl_header: Self, equal: Self, name: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::MethodishTraitResolution(ctx.get_arena().alloc(MethodishTraitResolutionChildren {
attribute,
function_decl_header,
equal,
name,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_classish_declaration(ctx: &C, attribute: Self, modifiers: Self, xhp: Self, keyword: Self, name: Self, type_parameters: Self, extends_keyword: Self, extends_list: Self, implements_keyword: Self, implements_list: Self, where_clause: Self, body: Self) -> Self {
let syntax = SyntaxVariant::ClassishDeclaration(ctx.get_arena().alloc(ClassishDeclarationChildren {
attribute,
modifiers,
xhp,
keyword,
name,
type_parameters,
extends_keyword,
extends_list,
implements_keyword,
implements_list,
where_clause,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_classish_body(ctx: &C, left_brace: Self, elements: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::ClassishBody(ctx.get_arena().alloc(ClassishBodyChildren {
left_brace,
elements,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use_precedence_item(ctx: &C, name: Self, keyword: Self, removed_names: Self) -> Self {
let syntax = SyntaxVariant::TraitUsePrecedenceItem(ctx.get_arena().alloc(TraitUsePrecedenceItemChildren {
name,
keyword,
removed_names,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use_alias_item(ctx: &C, aliasing_name: Self, keyword: Self, modifiers: Self, aliased_name: Self) -> Self {
let syntax = SyntaxVariant::TraitUseAliasItem(ctx.get_arena().alloc(TraitUseAliasItemChildren {
aliasing_name,
keyword,
modifiers,
aliased_name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use_conflict_resolution(ctx: &C, keyword: Self, names: Self, left_brace: Self, clauses: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::TraitUseConflictResolution(ctx.get_arena().alloc(TraitUseConflictResolutionChildren {
keyword,
names,
left_brace,
clauses,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_trait_use(ctx: &C, keyword: Self, names: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::TraitUse(ctx.get_arena().alloc(TraitUseChildren {
keyword,
names,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_require_clause(ctx: &C, keyword: Self, kind: Self, name: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::RequireClause(ctx.get_arena().alloc(RequireClauseChildren {
keyword,
kind,
name,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_const_declaration(ctx: &C, modifiers: Self, keyword: Self, type_specifier: Self, declarators: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ConstDeclaration(ctx.get_arena().alloc(ConstDeclarationChildren {
modifiers,
keyword,
type_specifier,
declarators,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_constant_declarator(ctx: &C, name: Self, initializer: Self) -> Self {
let syntax = SyntaxVariant::ConstantDeclarator(ctx.get_arena().alloc(ConstantDeclaratorChildren {
name,
initializer,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_const_declaration(ctx: &C, attribute_spec: Self, modifiers: Self, keyword: Self, type_keyword: Self, name: Self, type_parameters: Self, type_constraint: Self, equal: Self, type_specifier: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::TypeConstDeclaration(ctx.get_arena().alloc(TypeConstDeclarationChildren {
attribute_spec,
modifiers,
keyword,
type_keyword,
name,
type_parameters,
type_constraint,
equal,
type_specifier,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_context_const_declaration(ctx: &C, modifiers: Self, const_keyword: Self, ctx_keyword: Self, name: Self, type_parameters: Self, constraint: Self, equal: Self, ctx_list: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ContextConstDeclaration(ctx.get_arena().alloc(ContextConstDeclarationChildren {
modifiers,
const_keyword,
ctx_keyword,
name,
type_parameters,
constraint,
equal,
ctx_list,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_decorated_expression(ctx: &C, decorator: Self, expression: Self) -> Self {
let syntax = SyntaxVariant::DecoratedExpression(ctx.get_arena().alloc(DecoratedExpressionChildren {
decorator,
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_parameter_declaration(ctx: &C, attribute: Self, visibility: Self, call_convention: Self, readonly: Self, type_: Self, name: Self, default_value: Self) -> Self {
let syntax = SyntaxVariant::ParameterDeclaration(ctx.get_arena().alloc(ParameterDeclarationChildren {
attribute,
visibility,
call_convention,
readonly,
type_,
name,
default_value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_variadic_parameter(ctx: &C, call_convention: Self, type_: Self, ellipsis: Self) -> Self {
let syntax = SyntaxVariant::VariadicParameter(ctx.get_arena().alloc(VariadicParameterChildren {
call_convention,
type_,
ellipsis,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_old_attribute_specification(ctx: &C, left_double_angle: Self, attributes: Self, right_double_angle: Self) -> Self {
let syntax = SyntaxVariant::OldAttributeSpecification(ctx.get_arena().alloc(OldAttributeSpecificationChildren {
left_double_angle,
attributes,
right_double_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_attribute_specification(ctx: &C, attributes: Self) -> Self {
let syntax = SyntaxVariant::AttributeSpecification(ctx.get_arena().alloc(AttributeSpecificationChildren {
attributes,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_attribute(ctx: &C, at: Self, attribute_name: Self) -> Self {
let syntax = SyntaxVariant::Attribute(ctx.get_arena().alloc(AttributeChildren {
at,
attribute_name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_inclusion_expression(ctx: &C, require: Self, filename: Self) -> Self {
let syntax = SyntaxVariant::InclusionExpression(ctx.get_arena().alloc(InclusionExpressionChildren {
require,
filename,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_inclusion_directive(ctx: &C, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::InclusionDirective(ctx.get_arena().alloc(InclusionDirectiveChildren {
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_compound_statement(ctx: &C, left_brace: Self, statements: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::CompoundStatement(ctx.get_arena().alloc(CompoundStatementChildren {
left_brace,
statements,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_expression_statement(ctx: &C, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ExpressionStatement(ctx.get_arena().alloc(ExpressionStatementChildren {
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_markup_section(ctx: &C, hashbang: Self, suffix: Self) -> Self {
let syntax = SyntaxVariant::MarkupSection(ctx.get_arena().alloc(MarkupSectionChildren {
hashbang,
suffix,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_markup_suffix(ctx: &C, less_than_question: Self, name: Self) -> Self {
let syntax = SyntaxVariant::MarkupSuffix(ctx.get_arena().alloc(MarkupSuffixChildren {
less_than_question,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_unset_statement(ctx: &C, keyword: Self, left_paren: Self, variables: Self, right_paren: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::UnsetStatement(ctx.get_arena().alloc(UnsetStatementChildren {
keyword,
left_paren,
variables,
right_paren,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_using_statement_block_scoped(ctx: &C, await_keyword: Self, using_keyword: Self, left_paren: Self, expressions: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::UsingStatementBlockScoped(ctx.get_arena().alloc(UsingStatementBlockScopedChildren {
await_keyword,
using_keyword,
left_paren,
expressions,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_using_statement_function_scoped(ctx: &C, await_keyword: Self, using_keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::UsingStatementFunctionScoped(ctx.get_arena().alloc(UsingStatementFunctionScopedChildren {
await_keyword,
using_keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_while_statement(ctx: &C, keyword: Self, left_paren: Self, condition: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::WhileStatement(ctx.get_arena().alloc(WhileStatementChildren {
keyword,
left_paren,
condition,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_if_statement(ctx: &C, keyword: Self, left_paren: Self, condition: Self, right_paren: Self, statement: Self, elseif_clauses: Self, else_clause: Self) -> Self {
let syntax = SyntaxVariant::IfStatement(ctx.get_arena().alloc(IfStatementChildren {
keyword,
left_paren,
condition,
right_paren,
statement,
elseif_clauses,
else_clause,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_elseif_clause(ctx: &C, keyword: Self, left_paren: Self, condition: Self, right_paren: Self, statement: Self) -> Self {
let syntax = SyntaxVariant::ElseifClause(ctx.get_arena().alloc(ElseifClauseChildren {
keyword,
left_paren,
condition,
right_paren,
statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_else_clause(ctx: &C, keyword: Self, statement: Self) -> Self {
let syntax = SyntaxVariant::ElseClause(ctx.get_arena().alloc(ElseClauseChildren {
keyword,
statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_try_statement(ctx: &C, keyword: Self, compound_statement: Self, catch_clauses: Self, finally_clause: Self) -> Self {
let syntax = SyntaxVariant::TryStatement(ctx.get_arena().alloc(TryStatementChildren {
keyword,
compound_statement,
catch_clauses,
finally_clause,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_catch_clause(ctx: &C, keyword: Self, left_paren: Self, type_: Self, variable: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::CatchClause(ctx.get_arena().alloc(CatchClauseChildren {
keyword,
left_paren,
type_,
variable,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_finally_clause(ctx: &C, keyword: Self, body: Self) -> Self {
let syntax = SyntaxVariant::FinallyClause(ctx.get_arena().alloc(FinallyClauseChildren {
keyword,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_do_statement(ctx: &C, keyword: Self, body: Self, while_keyword: Self, left_paren: Self, condition: Self, right_paren: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::DoStatement(ctx.get_arena().alloc(DoStatementChildren {
keyword,
body,
while_keyword,
left_paren,
condition,
right_paren,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_for_statement(ctx: &C, keyword: Self, left_paren: Self, initializer: Self, first_semicolon: Self, control: Self, second_semicolon: Self, end_of_loop: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::ForStatement(ctx.get_arena().alloc(ForStatementChildren {
keyword,
left_paren,
initializer,
first_semicolon,
control,
second_semicolon,
end_of_loop,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_foreach_statement(ctx: &C, keyword: Self, left_paren: Self, collection: Self, await_keyword: Self, as_: Self, key: Self, arrow: Self, value: Self, right_paren: Self, body: Self) -> Self {
let syntax = SyntaxVariant::ForeachStatement(ctx.get_arena().alloc(ForeachStatementChildren {
keyword,
left_paren,
collection,
await_keyword,
as_,
key,
arrow,
value,
right_paren,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_switch_statement(ctx: &C, keyword: Self, left_paren: Self, expression: Self, right_paren: Self, left_brace: Self, sections: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::SwitchStatement(ctx.get_arena().alloc(SwitchStatementChildren {
keyword,
left_paren,
expression,
right_paren,
left_brace,
sections,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_switch_section(ctx: &C, labels: Self, statements: Self, fallthrough: Self) -> Self {
let syntax = SyntaxVariant::SwitchSection(ctx.get_arena().alloc(SwitchSectionChildren {
labels,
statements,
fallthrough,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_switch_fallthrough(ctx: &C, keyword: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::SwitchFallthrough(ctx.get_arena().alloc(SwitchFallthroughChildren {
keyword,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_case_label(ctx: &C, keyword: Self, expression: Self, colon: Self) -> Self {
let syntax = SyntaxVariant::CaseLabel(ctx.get_arena().alloc(CaseLabelChildren {
keyword,
expression,
colon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_default_label(ctx: &C, keyword: Self, colon: Self) -> Self {
let syntax = SyntaxVariant::DefaultLabel(ctx.get_arena().alloc(DefaultLabelChildren {
keyword,
colon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_return_statement(ctx: &C, keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ReturnStatement(ctx.get_arena().alloc(ReturnStatementChildren {
keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_yield_break_statement(ctx: &C, keyword: Self, break_: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::YieldBreakStatement(ctx.get_arena().alloc(YieldBreakStatementChildren {
keyword,
break_,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_throw_statement(ctx: &C, keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ThrowStatement(ctx.get_arena().alloc(ThrowStatementChildren {
keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_break_statement(ctx: &C, keyword: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::BreakStatement(ctx.get_arena().alloc(BreakStatementChildren {
keyword,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_continue_statement(ctx: &C, keyword: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::ContinueStatement(ctx.get_arena().alloc(ContinueStatementChildren {
keyword,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_echo_statement(ctx: &C, keyword: Self, expressions: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::EchoStatement(ctx.get_arena().alloc(EchoStatementChildren {
keyword,
expressions,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_concurrent_statement(ctx: &C, keyword: Self, statement: Self) -> Self {
let syntax = SyntaxVariant::ConcurrentStatement(ctx.get_arena().alloc(ConcurrentStatementChildren {
keyword,
statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_simple_initializer(ctx: &C, equal: Self, value: Self) -> Self {
let syntax = SyntaxVariant::SimpleInitializer(ctx.get_arena().alloc(SimpleInitializerChildren {
equal,
value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_anonymous_class(ctx: &C, class_keyword: Self, left_paren: Self, argument_list: Self, right_paren: Self, extends_keyword: Self, extends_list: Self, implements_keyword: Self, implements_list: Self, body: Self) -> Self {
let syntax = SyntaxVariant::AnonymousClass(ctx.get_arena().alloc(AnonymousClassChildren {
class_keyword,
left_paren,
argument_list,
right_paren,
extends_keyword,
extends_list,
implements_keyword,
implements_list,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_anonymous_function(ctx: &C, attribute_spec: Self, async_keyword: Self, function_keyword: Self, left_paren: Self, parameters: Self, right_paren: Self, ctx_list: Self, colon: Self, readonly_return: Self, type_: Self, use_: Self, body: Self) -> Self {
let syntax = SyntaxVariant::AnonymousFunction(ctx.get_arena().alloc(AnonymousFunctionChildren {
attribute_spec,
async_keyword,
function_keyword,
left_paren,
parameters,
right_paren,
ctx_list,
colon,
readonly_return,
type_,
use_,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_anonymous_function_use_clause(ctx: &C, keyword: Self, left_paren: Self, variables: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::AnonymousFunctionUseClause(ctx.get_arena().alloc(AnonymousFunctionUseClauseChildren {
keyword,
left_paren,
variables,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_lambda_expression(ctx: &C, attribute_spec: Self, async_: Self, signature: Self, arrow: Self, body: Self) -> Self {
let syntax = SyntaxVariant::LambdaExpression(ctx.get_arena().alloc(LambdaExpressionChildren {
attribute_spec,
async_,
signature,
arrow,
body,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_lambda_signature(ctx: &C, left_paren: Self, parameters: Self, right_paren: Self, contexts: Self, colon: Self, readonly_return: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::LambdaSignature(ctx.get_arena().alloc(LambdaSignatureChildren {
left_paren,
parameters,
right_paren,
contexts,
colon,
readonly_return,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_cast_expression(ctx: &C, left_paren: Self, type_: Self, right_paren: Self, operand: Self) -> Self {
let syntax = SyntaxVariant::CastExpression(ctx.get_arena().alloc(CastExpressionChildren {
left_paren,
type_,
right_paren,
operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_scope_resolution_expression(ctx: &C, qualifier: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::ScopeResolutionExpression(ctx.get_arena().alloc(ScopeResolutionExpressionChildren {
qualifier,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_member_selection_expression(ctx: &C, object: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::MemberSelectionExpression(ctx.get_arena().alloc(MemberSelectionExpressionChildren {
object,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_safe_member_selection_expression(ctx: &C, object: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::SafeMemberSelectionExpression(ctx.get_arena().alloc(SafeMemberSelectionExpressionChildren {
object,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_embedded_member_selection_expression(ctx: &C, object: Self, operator: Self, name: Self) -> Self {
let syntax = SyntaxVariant::EmbeddedMemberSelectionExpression(ctx.get_arena().alloc(EmbeddedMemberSelectionExpressionChildren {
object,
operator,
name,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_yield_expression(ctx: &C, keyword: Self, operand: Self) -> Self {
let syntax = SyntaxVariant::YieldExpression(ctx.get_arena().alloc(YieldExpressionChildren {
keyword,
operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_prefix_unary_expression(ctx: &C, operator: Self, operand: Self) -> Self {
let syntax = SyntaxVariant::PrefixUnaryExpression(ctx.get_arena().alloc(PrefixUnaryExpressionChildren {
operator,
operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_postfix_unary_expression(ctx: &C, operand: Self, operator: Self) -> Self {
let syntax = SyntaxVariant::PostfixUnaryExpression(ctx.get_arena().alloc(PostfixUnaryExpressionChildren {
operand,
operator,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_binary_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::BinaryExpression(ctx.get_arena().alloc(BinaryExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_is_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::IsExpression(ctx.get_arena().alloc(IsExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_as_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::AsExpression(ctx.get_arena().alloc(AsExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_nullable_as_expression(ctx: &C, left_operand: Self, operator: Self, right_operand: Self) -> Self {
let syntax = SyntaxVariant::NullableAsExpression(ctx.get_arena().alloc(NullableAsExpressionChildren {
left_operand,
operator,
right_operand,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_conditional_expression(ctx: &C, test: Self, question: Self, consequence: Self, colon: Self, alternative: Self) -> Self {
let syntax = SyntaxVariant::ConditionalExpression(ctx.get_arena().alloc(ConditionalExpressionChildren {
test,
question,
consequence,
colon,
alternative,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_eval_expression(ctx: &C, keyword: Self, left_paren: Self, argument: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::EvalExpression(ctx.get_arena().alloc(EvalExpressionChildren {
keyword,
left_paren,
argument,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_isset_expression(ctx: &C, keyword: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::IssetExpression(ctx.get_arena().alloc(IssetExpressionChildren {
keyword,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_call_expression(ctx: &C, receiver: Self, type_args: Self, enum_atom: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::FunctionCallExpression(ctx.get_arena().alloc(FunctionCallExpressionChildren {
receiver,
type_args,
enum_atom,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_pointer_expression(ctx: &C, receiver: Self, type_args: Self) -> Self {
let syntax = SyntaxVariant::FunctionPointerExpression(ctx.get_arena().alloc(FunctionPointerExpressionChildren {
receiver,
type_args,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_parenthesized_expression(ctx: &C, left_paren: Self, expression: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ParenthesizedExpression(ctx.get_arena().alloc(ParenthesizedExpressionChildren {
left_paren,
expression,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_braced_expression(ctx: &C, left_brace: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::BracedExpression(ctx.get_arena().alloc(BracedExpressionChildren {
left_brace,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_et_splice_expression(ctx: &C, dollar: Self, left_brace: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::ETSpliceExpression(ctx.get_arena().alloc(ETSpliceExpressionChildren {
dollar,
left_brace,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_embedded_braced_expression(ctx: &C, left_brace: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::EmbeddedBracedExpression(ctx.get_arena().alloc(EmbeddedBracedExpressionChildren {
left_brace,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_list_expression(ctx: &C, keyword: Self, left_paren: Self, members: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ListExpression(ctx.get_arena().alloc(ListExpressionChildren {
keyword,
left_paren,
members,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_collection_literal_expression(ctx: &C, name: Self, left_brace: Self, initializers: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::CollectionLiteralExpression(ctx.get_arena().alloc(CollectionLiteralExpressionChildren {
name,
left_brace,
initializers,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_object_creation_expression(ctx: &C, new_keyword: Self, object: Self) -> Self {
let syntax = SyntaxVariant::ObjectCreationExpression(ctx.get_arena().alloc(ObjectCreationExpressionChildren {
new_keyword,
object,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_constructor_call(ctx: &C, type_: Self, left_paren: Self, argument_list: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ConstructorCall(ctx.get_arena().alloc(ConstructorCallChildren {
type_,
left_paren,
argument_list,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_record_creation_expression(ctx: &C, type_: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::RecordCreationExpression(ctx.get_arena().alloc(RecordCreationExpressionChildren {
type_,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_darray_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::DarrayIntrinsicExpression(ctx.get_arena().alloc(DarrayIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_dictionary_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::DictionaryIntrinsicExpression(ctx.get_arena().alloc(DictionaryIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_keyset_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::KeysetIntrinsicExpression(ctx.get_arena().alloc(KeysetIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_varray_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::VarrayIntrinsicExpression(ctx.get_arena().alloc(VarrayIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_vector_intrinsic_expression(ctx: &C, keyword: Self, explicit_type: Self, left_bracket: Self, members: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::VectorIntrinsicExpression(ctx.get_arena().alloc(VectorIntrinsicExpressionChildren {
keyword,
explicit_type,
left_bracket,
members,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_element_initializer(ctx: &C, key: Self, arrow: Self, value: Self) -> Self {
let syntax = SyntaxVariant::ElementInitializer(ctx.get_arena().alloc(ElementInitializerChildren {
key,
arrow,
value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_subscript_expression(ctx: &C, receiver: Self, left_bracket: Self, index: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::SubscriptExpression(ctx.get_arena().alloc(SubscriptExpressionChildren {
receiver,
left_bracket,
index,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_embedded_subscript_expression(ctx: &C, receiver: Self, left_bracket: Self, index: Self, right_bracket: Self) -> Self {
let syntax = SyntaxVariant::EmbeddedSubscriptExpression(ctx.get_arena().alloc(EmbeddedSubscriptExpressionChildren {
receiver,
left_bracket,
index,
right_bracket,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_awaitable_creation_expression(ctx: &C, attribute_spec: Self, async_: Self, compound_statement: Self) -> Self {
let syntax = SyntaxVariant::AwaitableCreationExpression(ctx.get_arena().alloc(AwaitableCreationExpressionChildren {
attribute_spec,
async_,
compound_statement,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_children_declaration(ctx: &C, keyword: Self, expression: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::XHPChildrenDeclaration(ctx.get_arena().alloc(XHPChildrenDeclarationChildren {
keyword,
expression,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_children_parenthesized_list(ctx: &C, left_paren: Self, xhp_children: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::XHPChildrenParenthesizedList(ctx.get_arena().alloc(XHPChildrenParenthesizedListChildren {
left_paren,
xhp_children,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_category_declaration(ctx: &C, keyword: Self, categories: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::XHPCategoryDeclaration(ctx.get_arena().alloc(XHPCategoryDeclarationChildren {
keyword,
categories,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_enum_type(ctx: &C, keyword: Self, left_brace: Self, values: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::XHPEnumType(ctx.get_arena().alloc(XHPEnumTypeChildren {
keyword,
left_brace,
values,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_lateinit(ctx: &C, at: Self, keyword: Self) -> Self {
let syntax = SyntaxVariant::XHPLateinit(ctx.get_arena().alloc(XHPLateinitChildren {
at,
keyword,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_required(ctx: &C, at: Self, keyword: Self) -> Self {
let syntax = SyntaxVariant::XHPRequired(ctx.get_arena().alloc(XHPRequiredChildren {
at,
keyword,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_class_attribute_declaration(ctx: &C, keyword: Self, attributes: Self, semicolon: Self) -> Self {
let syntax = SyntaxVariant::XHPClassAttributeDeclaration(ctx.get_arena().alloc(XHPClassAttributeDeclarationChildren {
keyword,
attributes,
semicolon,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_class_attribute(ctx: &C, type_: Self, name: Self, initializer: Self, required: Self) -> Self {
let syntax = SyntaxVariant::XHPClassAttribute(ctx.get_arena().alloc(XHPClassAttributeChildren {
type_,
name,
initializer,
required,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_simple_class_attribute(ctx: &C, type_: Self) -> Self {
let syntax = SyntaxVariant::XHPSimpleClassAttribute(ctx.get_arena().alloc(XHPSimpleClassAttributeChildren {
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_simple_attribute(ctx: &C, name: Self, equal: Self, expression: Self) -> Self {
let syntax = SyntaxVariant::XHPSimpleAttribute(ctx.get_arena().alloc(XHPSimpleAttributeChildren {
name,
equal,
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_spread_attribute(ctx: &C, left_brace: Self, spread_operator: Self, expression: Self, right_brace: Self) -> Self {
let syntax = SyntaxVariant::XHPSpreadAttribute(ctx.get_arena().alloc(XHPSpreadAttributeChildren {
left_brace,
spread_operator,
expression,
right_brace,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_open(ctx: &C, left_angle: Self, name: Self, attributes: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::XHPOpen(ctx.get_arena().alloc(XHPOpenChildren {
left_angle,
name,
attributes,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_expression(ctx: &C, open: Self, body: Self, close: Self) -> Self {
let syntax = SyntaxVariant::XHPExpression(ctx.get_arena().alloc(XHPExpressionChildren {
open,
body,
close,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_xhp_close(ctx: &C, left_angle: Self, name: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::XHPClose(ctx.get_arena().alloc(XHPCloseChildren {
left_angle,
name,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_constant(ctx: &C, left_type: Self, separator: Self, right_type: Self) -> Self {
let syntax = SyntaxVariant::TypeConstant(ctx.get_arena().alloc(TypeConstantChildren {
left_type,
separator,
right_type,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_vector_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::VectorTypeSpecifier(ctx.get_arena().alloc(VectorTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_keyset_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::KeysetTypeSpecifier(ctx.get_arena().alloc(KeysetTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_tuple_type_explicit_specifier(ctx: &C, keyword: Self, left_angle: Self, types: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::TupleTypeExplicitSpecifier(ctx.get_arena().alloc(TupleTypeExplicitSpecifierChildren {
keyword,
left_angle,
types,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_varray_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::VarrayTypeSpecifier(ctx.get_arena().alloc(VarrayTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_function_ctx_type_specifier(ctx: &C, keyword: Self, variable: Self) -> Self {
let syntax = SyntaxVariant::FunctionCtxTypeSpecifier(ctx.get_arena().alloc(FunctionCtxTypeSpecifierChildren {
keyword,
variable,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_parameter(ctx: &C, attribute_spec: Self, reified: Self, variance: Self, name: Self, param_params: Self, constraints: Self) -> Self {
let syntax = SyntaxVariant::TypeParameter(ctx.get_arena().alloc(TypeParameterChildren {
attribute_spec,
reified,
variance,
name,
param_params,
constraints,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_constraint(ctx: &C, keyword: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::TypeConstraint(ctx.get_arena().alloc(TypeConstraintChildren {
keyword,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_context_constraint(ctx: &C, keyword: Self, ctx_list: Self) -> Self {
let syntax = SyntaxVariant::ContextConstraint(ctx.get_arena().alloc(ContextConstraintChildren {
keyword,
ctx_list,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_darray_type_specifier(ctx: &C, keyword: Self, left_angle: Self, key: Self, comma: Self, value: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::DarrayTypeSpecifier(ctx.get_arena().alloc(DarrayTypeSpecifierChildren {
keyword,
left_angle,
key,
comma,
value,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_dictionary_type_specifier(ctx: &C, keyword: Self, left_angle: Self, members: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::DictionaryTypeSpecifier(ctx.get_arena().alloc(DictionaryTypeSpecifierChildren {
keyword,
left_angle,
members,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_closure_type_specifier(ctx: &C, outer_left_paren: Self, readonly_keyword: Self, function_keyword: Self, inner_left_paren: Self, parameter_list: Self, inner_right_paren: Self, contexts: Self, colon: Self, readonly_return: Self, return_type: Self, outer_right_paren: Self) -> Self {
let syntax = SyntaxVariant::ClosureTypeSpecifier(ctx.get_arena().alloc(ClosureTypeSpecifierChildren {
outer_left_paren,
readonly_keyword,
function_keyword,
inner_left_paren,
parameter_list,
inner_right_paren,
contexts,
colon,
readonly_return,
return_type,
outer_right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_closure_parameter_type_specifier(ctx: &C, call_convention: Self, readonly: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::ClosureParameterTypeSpecifier(ctx.get_arena().alloc(ClosureParameterTypeSpecifierChildren {
call_convention,
readonly,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_classname_type_specifier(ctx: &C, keyword: Self, left_angle: Self, type_: Self, trailing_comma: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::ClassnameTypeSpecifier(ctx.get_arena().alloc(ClassnameTypeSpecifierChildren {
keyword,
left_angle,
type_,
trailing_comma,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_field_specifier(ctx: &C, question: Self, name: Self, arrow: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::FieldSpecifier(ctx.get_arena().alloc(FieldSpecifierChildren {
question,
name,
arrow,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_field_initializer(ctx: &C, name: Self, arrow: Self, value: Self) -> Self {
let syntax = SyntaxVariant::FieldInitializer(ctx.get_arena().alloc(FieldInitializerChildren {
name,
arrow,
value,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_shape_type_specifier(ctx: &C, keyword: Self, left_paren: Self, fields: Self, ellipsis: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ShapeTypeSpecifier(ctx.get_arena().alloc(ShapeTypeSpecifierChildren {
keyword,
left_paren,
fields,
ellipsis,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_shape_expression(ctx: &C, keyword: Self, left_paren: Self, fields: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::ShapeExpression(ctx.get_arena().alloc(ShapeExpressionChildren {
keyword,
left_paren,
fields,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_tuple_expression(ctx: &C, keyword: Self, left_paren: Self, items: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::TupleExpression(ctx.get_arena().alloc(TupleExpressionChildren {
keyword,
left_paren,
items,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_generic_type_specifier(ctx: &C, class_type: Self, argument_list: Self) -> Self {
let syntax = SyntaxVariant::GenericTypeSpecifier(ctx.get_arena().alloc(GenericTypeSpecifierChildren {
class_type,
argument_list,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_nullable_type_specifier(ctx: &C, question: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::NullableTypeSpecifier(ctx.get_arena().alloc(NullableTypeSpecifierChildren {
question,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_like_type_specifier(ctx: &C, tilde: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::LikeTypeSpecifier(ctx.get_arena().alloc(LikeTypeSpecifierChildren {
tilde,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_soft_type_specifier(ctx: &C, at: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::SoftTypeSpecifier(ctx.get_arena().alloc(SoftTypeSpecifierChildren {
at,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_attributized_specifier(ctx: &C, attribute_spec: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::AttributizedSpecifier(ctx.get_arena().alloc(AttributizedSpecifierChildren {
attribute_spec,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_reified_type_argument(ctx: &C, reified: Self, type_: Self) -> Self {
let syntax = SyntaxVariant::ReifiedTypeArgument(ctx.get_arena().alloc(ReifiedTypeArgumentChildren {
reified,
type_,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_arguments(ctx: &C, left_angle: Self, types: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::TypeArguments(ctx.get_arena().alloc(TypeArgumentsChildren {
left_angle,
types,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_type_parameters(ctx: &C, left_angle: Self, parameters: Self, right_angle: Self) -> Self {
let syntax = SyntaxVariant::TypeParameters(ctx.get_arena().alloc(TypeParametersChildren {
left_angle,
parameters,
right_angle,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_tuple_type_specifier(ctx: &C, left_paren: Self, types: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::TupleTypeSpecifier(ctx.get_arena().alloc(TupleTypeSpecifierChildren {
left_paren,
types,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_union_type_specifier(ctx: &C, left_paren: Self, types: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::UnionTypeSpecifier(ctx.get_arena().alloc(UnionTypeSpecifierChildren {
left_paren,
types,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_intersection_type_specifier(ctx: &C, left_paren: Self, types: Self, right_paren: Self) -> Self {
let syntax = SyntaxVariant::IntersectionTypeSpecifier(ctx.get_arena().alloc(IntersectionTypeSpecifierChildren {
left_paren,
types,
right_paren,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_error(ctx: &C, error: Self) -> Self {
let syntax = SyntaxVariant::ErrorSyntax(ctx.get_arena().alloc(ErrorSyntaxChildren {
error,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_list_item(ctx: &C, item: Self, separator: Self) -> Self {
let syntax = SyntaxVariant::ListItem(ctx.get_arena().alloc(ListItemChildren {
item,
separator,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
fn make_enum_atom_expression(ctx: &C, hash: Self, expression: Self) -> Self {
let syntax = SyntaxVariant::EnumAtomExpression(ctx.get_arena().alloc(EnumAtomExpressionChildren {
hash,
expression,
}));
let value = V::from_values(syntax.iter_children().map(|child| &child.value));
Self::make(syntax, value)
}
}
| 41.152209 | 292 | 0.615933 |
9039ec35afe6efd7934d099364f745f896720913
| 19,850 |
use ic_canister_client::Sender;
use ic_nns_common::types::{NeuronId, ProposalId, UpdateIcpXdrConversionRatePayload};
use ic_nns_constants::ids::{
TEST_NEURON_1_OWNER_KEYPAIR, TEST_USER1_PRINCIPAL, TEST_USER2_PRINCIPAL, TEST_USER3_PRINCIPAL,
TEST_USER4_PRINCIPAL, TEST_USER5_PRINCIPAL, TEST_USER6_PRINCIPAL, TEST_USER7_PRINCIPAL,
};
use ic_nns_governance::pb::v1::{
add_or_remove_node_provider::Change,
manage_neuron::{Command, NeuronIdOrSubaccount},
manage_neuron_response::Command as CommandResponse,
proposal::Action,
AddOrRemoveNodeProvider, GovernanceError, ManageNeuron, ManageNeuronResponse, NnsFunction,
NodeProvider, Proposal, ProposalStatus, RewardNodeProvider, RewardNodeProviders,
};
use ic_nns_test_utils::governance::submit_external_update_proposal;
use ic_nns_test_utils::{
governance::{get_pending_proposals, wait_for_final_state},
ids::TEST_NEURON_1_ID,
itest_helpers::{local_test_on_nns_subnet, NnsCanisters, NnsInitPayloadsBuilder},
};
use ic_protobuf::registry::dc::v1::{AddOrRemoveDataCentersProposalPayload, DataCenterRecord};
use ic_protobuf::registry::node_rewards::v2::{
NodeRewardRate, NodeRewardRates, UpdateNodeRewardsTableProposalPayload,
};
use maplit::btreemap;
use registry_canister::mutations::do_add_node_operator::AddNodeOperatorPayload;
use cycles_minting_canister::IcpXdrConversionRateCertifiedResponse;
use dfn_candid::candid_one;
use dfn_protobuf::protobuf;
use ic_nns_common::pb::v1::NeuronId as ProtoNeuronId;
use ic_nns_governance::pb::v1::reward_node_provider::{RewardMode, RewardToAccount};
use ic_types::PrincipalId;
use ledger_canister::{AccountBalanceArgs, AccountIdentifier, Tokens, TOKEN_SUBDIVIDABLE_BY};
use std::collections::BTreeMap;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
fn test_automated_node_provider_remuneration() {
local_test_on_nns_subnet(|runtime| async move {
let nns_init_payload = NnsInitPayloadsBuilder::new()
.with_initial_invariant_compliant_mutations()
.with_test_neurons()
.build();
let nns_canisters = NnsCanisters::set_up(&runtime, nns_init_payload).await;
add_data_centers(&nns_canisters).await;
add_node_rewards_table(&nns_canisters).await;
// Define the set of node operators and node providers
let node_operator_id_1 = *TEST_USER1_PRINCIPAL;
let node_provider_id_1 = *TEST_USER2_PRINCIPAL;
let node_provider_1_account = AccountIdentifier::from(node_provider_id_1);
let node_provider_1 = NodeProvider {
id: Some(node_provider_id_1),
reward_account: None,
};
let reward_mode_1 = Some(RewardMode::RewardToAccount(RewardToAccount {
to_account: Some(node_provider_1_account.into()),
}));
let expected_rewards_e8s_1 =
(((10 * 24_000) + (21 * 68_000) + (6 * 11_000)) * TOKEN_SUBDIVIDABLE_BY) / 155_000;
assert_eq!(expected_rewards_e8s_1, 1118709677);
let expected_node_provider_reward_1 = RewardNodeProvider {
node_provider: Some(node_provider_1.clone()),
amount_e8s: expected_rewards_e8s_1,
reward_mode: reward_mode_1,
};
let node_operator_id_2 = *TEST_USER3_PRINCIPAL;
let node_provider_id_2 = *TEST_USER4_PRINCIPAL;
let node_provider_2_account = AccountIdentifier::from(node_provider_id_2);
let node_provider_2 = NodeProvider {
id: Some(node_provider_id_2),
reward_account: None,
};
let reward_mode_2 = Some(RewardMode::RewardToAccount(RewardToAccount {
to_account: Some(node_provider_2_account.into()),
}));
let expected_rewards_e8s_2 =
(((35 * 68_000) + (17 * 11_000)) * TOKEN_SUBDIVIDABLE_BY) / 155_000;
assert_eq!(expected_rewards_e8s_2, 1656129032);
let expected_node_provider_reward_2 = RewardNodeProvider {
node_provider: Some(node_provider_2.clone()),
amount_e8s: expected_rewards_e8s_2,
reward_mode: reward_mode_2,
};
let node_operator_id_3 = *TEST_USER5_PRINCIPAL;
let node_provider_id_3 = *TEST_USER6_PRINCIPAL;
let node_provider_3_account = AccountIdentifier::from(*TEST_USER7_PRINCIPAL);
let node_provider_3 = NodeProvider {
id: Some(node_provider_id_3),
reward_account: Some(node_provider_3_account.into()),
};
let reward_mode_3 = Some(RewardMode::RewardToAccount(RewardToAccount {
to_account: Some(node_provider_3_account.into()),
}));
let expected_rewards_e8s_3 =
(((19 * 234_000) + (33 * 907_000) + (4 * 103_000)) * TOKEN_SUBDIVIDABLE_BY) / 155_000;
assert_eq!(expected_rewards_e8s_3, 22444516129);
let expected_node_provider_reward_3 = RewardNodeProvider {
node_provider: Some(node_provider_3.clone()),
amount_e8s: expected_rewards_e8s_3,
reward_mode: reward_mode_3,
};
let node_operator_id_4 = *TEST_USER7_PRINCIPAL;
// Add Node Providers
add_node_provider(&nns_canisters, node_provider_1).await;
add_node_provider(&nns_canisters, node_provider_2).await;
add_node_provider(&nns_canisters, node_provider_3).await;
// Add Node Operator 1
let rewardable_nodes_1 = btreemap! { "default".to_string() => 10 };
add_node_operator(
&nns_canisters,
&node_operator_id_1,
&node_provider_id_1,
"AN1",
rewardable_nodes_1,
)
.await;
// Add Node Operator 2
let rewardable_nodes_2 = btreemap! {
"default".to_string() => 35,
"small".to_string() => 17,
};
add_node_operator(
&nns_canisters,
&node_operator_id_2,
&node_provider_id_2,
"BC1",
rewardable_nodes_2,
)
.await;
// Add Node Operator 3
let rewardable_nodes_3 = btreemap! {
"default".to_string() => 19,
"small".to_string() => 33,
"storage_upgrade".to_string() => 4,
};
add_node_operator(
&nns_canisters,
&node_operator_id_3,
&node_provider_id_3,
"FM1",
rewardable_nodes_3,
)
.await;
// Add Node Operator 4
let rewardable_nodes_4 = btreemap! {
"default".to_string() => 21,
"small".to_string() => 6,
};
add_node_operator(
&nns_canisters,
&node_operator_id_4,
&node_provider_id_1,
"BC1",
rewardable_nodes_4,
)
.await;
// Add conversion rates to populate the average conversion rate
let mut payload = UpdateIcpXdrConversionRatePayload {
timestamp_seconds: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs(),
xdr_permyriad_per_icp: 10_000,
..Default::default()
};
for _ in 0..30 {
set_icp_xdr_conversion_rate(&nns_canisters, payload.clone()).await;
payload.timestamp_seconds += 86400;
payload.xdr_permyriad_per_icp += 10_000;
}
let average_rate_result: IcpXdrConversionRateCertifiedResponse = nns_canisters
.cycles_minting
.query_("get_average_icp_xdr_conversion_rate", candid_one, ())
.await
.expect("Error calling get_average_icp_xdr_conversion_rate");
let average_xdr_permyriad_per_icp = average_rate_result.data.xdr_permyriad_per_icp;
assert_eq!(average_xdr_permyriad_per_icp, 155_000);
// Call get_monthly_node_provider_rewards assert the value is as expected
let monthly_node_provider_rewards_result: Result<RewardNodeProviders, GovernanceError> =
nns_canisters
.governance
.update_("get_monthly_node_provider_rewards", candid_one, ())
.await
.expect("Error calling get_monthly_node_provider_rewards");
let monthly_node_provider_rewards = monthly_node_provider_rewards_result.unwrap();
assert_eq!(monthly_node_provider_rewards.rewards.len(), 3);
assert!(monthly_node_provider_rewards
.rewards
.contains(&expected_node_provider_reward_1));
assert!(monthly_node_provider_rewards
.rewards
.contains(&expected_node_provider_reward_2));
assert!(monthly_node_provider_rewards
.rewards
.contains(&expected_node_provider_reward_3));
// Assert account balances are 0
assert_account_balance(&nns_canisters, node_provider_1_account, 0).await;
assert_account_balance(&nns_canisters, node_provider_2_account, 0).await;
assert_account_balance(&nns_canisters, node_provider_3_account, 0).await;
// Submit and execute proposal to pay NPs via Registry-driven rewards
reward_node_providers_via_registry(&nns_canisters).await;
// Assert account balances are as expected
assert_account_balance(
&nns_canisters,
node_provider_1_account,
expected_node_provider_reward_1.amount_e8s,
)
.await;
assert_account_balance(
&nns_canisters,
node_provider_2_account,
expected_node_provider_reward_2.amount_e8s,
)
.await;
assert_account_balance(
&nns_canisters,
node_provider_3_account,
expected_node_provider_reward_3.amount_e8s,
)
.await;
Ok(())
});
}
/// Submit and execute a RewardNodeProviders proposal with the `use_registry_derived_rewards`
/// flag set to `true`. This causes Node Providers to be rewarded with the rewards returned
/// by Governance's `get_monthly_node_provider_rewards` method.
async fn reward_node_providers_via_registry(nns_canisters: &NnsCanisters<'_>) {
let sender = Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR);
let result: ManageNeuronResponse = nns_canisters
.governance
.update_from_sender(
"manage_neuron",
candid_one,
ManageNeuron {
neuron_id_or_subaccount: Some(NeuronIdOrSubaccount::NeuronId(ProtoNeuronId {
id: TEST_NEURON_1_ID,
})),
id: None,
command: Some(Command::MakeProposal(Box::new(Proposal {
title: Some("Reward NPs".to_string()),
summary: "".to_string(),
url: "".to_string(),
action: Some(Action::RewardNodeProviders(RewardNodeProviders {
rewards: vec![],
use_registry_derived_rewards: Some(true),
})),
}))),
},
&sender,
)
.await
.expect("Error calling the manage_neuron api.");
let pid = match result.expect("Error making proposal").command.unwrap() {
CommandResponse::MakeProposal(resp) => resp.proposal_id.unwrap(),
_ => panic!("Invalid response"),
};
// Wait for the proposal to be accepted and executed.
assert_eq!(
wait_for_final_state(&nns_canisters.governance, ProposalId::from(pid))
.await
.status(),
ProposalStatus::Executed
);
}
/// Assert the given account has the given token balance on the Ledger
async fn assert_account_balance(
nns_canisters: &NnsCanisters<'_>,
account: AccountIdentifier,
e8s: u64,
) {
let user_balance: Tokens = nns_canisters
.ledger
.query_(
"account_balance_pb",
protobuf,
AccountBalanceArgs { account },
)
.await
.unwrap();
assert_eq!(Tokens::from_e8s(e8s), user_balance);
}
/// Add test Data Centers to the Registry
async fn add_data_centers(nns_canisters: &NnsCanisters<'_>) {
let data_centers = vec![
DataCenterRecord {
id: "AN1".into(),
region: "EU,Belgium,Antwerp".into(),
owner: "Alice".into(),
gps: None,
},
DataCenterRecord {
id: "BC1".into(),
region: "North America,Canada,BC".into(),
owner: "Bob".into(),
gps: None,
},
DataCenterRecord {
id: "FM1".into(),
region: "North America,US,CA,Fremont".into(),
owner: "Carol".into(),
gps: None,
},
];
let payload = AddOrRemoveDataCentersProposalPayload {
data_centers_to_add: data_centers,
data_centers_to_remove: vec![],
};
let proposal_id: ProposalId = submit_external_update_proposal(
&nns_canisters.governance,
Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR),
NeuronId(TEST_NEURON_1_ID),
NnsFunction::AddOrRemoveDataCenters,
payload.clone(),
"<proposal created by test_get_monthly_node_provider_rewards>".to_string(),
"".to_string(),
)
.await;
// Wait for the proposal to be accepted and executed.
assert_eq!(
wait_for_final_state(&nns_canisters.governance, proposal_id)
.await
.status(),
ProposalStatus::Executed
);
// No proposals should be pending now.
let pending_proposals = get_pending_proposals(&nns_canisters.governance).await;
assert_eq!(pending_proposals, vec![]);
}
/// Add a test rewards table to the Registry
async fn add_node_rewards_table(nns_canisters: &NnsCanisters<'_>) {
let new_entries = btreemap! {
"EU".to_string() => NodeRewardRates {
rates: btreemap!{
"default".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 24_000,
},
"small".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 35_000,
},
}
},
"North America,Canada".to_string() => NodeRewardRates {
rates: btreemap!{
"default".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 68_000,
},
"small".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 11_000,
},
}
},
"North America,US,CA".to_string() => NodeRewardRates {
rates: btreemap!{
"default".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 234_000,
},
"small".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 907_000,
},
"storage_upgrade".to_string() => NodeRewardRate {
xdr_permyriad_per_node_per_month: 103_000,
},
}
}
};
let payload = UpdateNodeRewardsTableProposalPayload { new_entries };
let proposal_id: ProposalId = submit_external_update_proposal(
&nns_canisters.governance,
Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR),
NeuronId(TEST_NEURON_1_ID),
NnsFunction::UpdateNodeRewardsTable,
payload.clone(),
"<proposal created by test_get_monthly_node_provider_rewards>".to_string(),
"".to_string(),
)
.await;
// Wait for the proposal to be accepted and executed.
assert_eq!(
wait_for_final_state(&nns_canisters.governance, proposal_id)
.await
.status(),
ProposalStatus::Executed
);
// No proposals should be pending now.
let pending_proposals = get_pending_proposals(&nns_canisters.governance).await;
assert_eq!(pending_proposals, vec![]);
}
/// Submit and execute a proposal to add the given node operator
async fn add_node_operator(
nns_canisters: &NnsCanisters<'_>,
no_id: &PrincipalId,
np_id: &PrincipalId,
dc_id: &str,
rewardable_nodes: BTreeMap<String, u32>,
) {
let proposal_payload = AddNodeOperatorPayload {
node_operator_principal_id: Some(*no_id),
node_allowance: 5,
node_provider_principal_id: Some(*np_id),
dc_id: dc_id.into(),
rewardable_nodes,
};
let proposal_id: ProposalId = submit_external_update_proposal(
&nns_canisters.governance,
Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR),
NeuronId(TEST_NEURON_1_ID),
NnsFunction::AssignNoid,
proposal_payload.clone(),
"<proposal created by test_get_monthly_node_provider_rewards>".to_string(),
"".to_string(),
)
.await;
// Wait for the proposal to be accepted and executed.
assert_eq!(
wait_for_final_state(&nns_canisters.governance, proposal_id)
.await
.status(),
ProposalStatus::Executed
);
// No proposals should be pending now.
let pending_proposals = get_pending_proposals(&nns_canisters.governance).await;
assert_eq!(pending_proposals, vec![]);
}
/// Submit and execute a proposal to add the given node provider
pub async fn add_node_provider(nns_canisters: &NnsCanisters<'_>, np: NodeProvider) {
let result: ManageNeuronResponse = nns_canisters
.governance
.update_from_sender(
"manage_neuron",
candid_one,
ManageNeuron {
neuron_id_or_subaccount: Some(NeuronIdOrSubaccount::NeuronId(
ic_nns_common::pb::v1::NeuronId {
id: TEST_NEURON_1_ID,
},
)),
id: None,
command: Some(Command::MakeProposal(Box::new(Proposal {
title: Some("Add a Node Provider".to_string()),
summary: "".to_string(),
url: "".to_string(),
action: Some(Action::AddOrRemoveNodeProvider(AddOrRemoveNodeProvider {
change: Some(Change::ToAdd(np)),
})),
}))),
},
&Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR),
)
.await
.expect("Error calling the manage_neuron api.");
let pid = match result.expect("Error making proposal").command.unwrap() {
CommandResponse::MakeProposal(resp) => resp.proposal_id.unwrap(),
_ => panic!("Invalid response"),
};
// Wait for the proposal to be accepted and executed.
assert_eq!(
wait_for_final_state(&nns_canisters.governance, ProposalId::from(pid))
.await
.status(),
ProposalStatus::Executed
);
}
/// Submit and execute a proposal to set the given conversion rate
async fn set_icp_xdr_conversion_rate(
nns_canisters: &NnsCanisters<'_>,
payload: UpdateIcpXdrConversionRatePayload,
) {
let proposal_id: ProposalId = submit_external_update_proposal(
&nns_canisters.governance,
Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR),
NeuronId(TEST_NEURON_1_ID),
NnsFunction::IcpXdrConversionRate,
payload.clone(),
"<proposal created by test_get_monthly_node_provider_rewards>".to_string(),
"".to_string(),
)
.await;
// Wait for the proposal to be accepted and executed.
assert_eq!(
wait_for_final_state(&nns_canisters.governance, proposal_id)
.await
.status(),
ProposalStatus::Executed
);
// No proposals should be pending now.
let pending_proposals = get_pending_proposals(&nns_canisters.governance).await;
assert_eq!(pending_proposals, vec![]);
}
| 37.102804 | 98 | 0.629924 |
22a3bcf907b721483e590c4fa9925fc6ebf169b7
| 12,971 |
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::iter::repeat;
use std::thread::sleep;
use std::time::{Duration, Instant, SystemTime};
use byteorder::{ByteOrder, LittleEndian};
use object::{Object, ObjectSymbol};
use object::elf::PT_LOAD;
use object::Endianness;
use regex::Regex;
use crate::connection::Connection;
use crate::crc::crc32;
use crate::ElfFile;
pub struct TestBinary<'data> {
pub file: ElfFile<'data>,
}
impl<'data> TestBinary<'data> {
pub fn new(file: ElfFile<'data>) -> Self {
Self { file }
}
}
pub struct LoadSegment {
addr: u32,
data: Vec<u8>,
}
impl Debug for LoadSegment {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"LoadSegment(0x{:x}, 0x{:x})",
self.addr,
self.data.len()
))
}
}
impl LoadSegment {
pub fn get_from_file(binary: &TestBinary) -> Vec<LoadSegment> {
let mut segments_to_load = Vec::new();
let file_data = binary.file.data();
for header in binary.file.raw_segments().iter() {
let p_type = header.p_type.get(Endianness::Little);
if p_type & PT_LOAD == 0 {
continue;
}
let file_size = header.p_filesz.get(Endianness::Little) as usize;
if file_size == 0 {
continue;
}
let offset = header.p_offset.get(Endianness::Little) as usize;
let physical_address = header.p_paddr.get(Endianness::Little);
let load_data = &file_data[offset..offset + file_size];
let segment = LoadSegment {
addr: physical_address,
data: load_data.to_vec(),
};
segments_to_load.push(segment);
}
segments_to_load
}
pub fn collapse_segments(mut segments: Vec<LoadSegment>) -> Option<LoadSegment> {
if segments.len() < 1 {
return None;
}
segments.sort_by(|x, y| {
if x.addr > y.addr {
Ordering::Greater
} else if x.addr < y.addr {
Ordering::Less
} else {
Ordering::Equal
}
});
let first = &segments[0];
let mut binary = first.data.to_vec();
let mut current_addr = first.addr as usize + first.data.len();
for segment in &segments[1..segments.len()] {
let segment_addr = segment.addr as usize;
if segment_addr > current_addr {
binary.extend(repeat(0xFF).take(segment_addr - current_addr));
}
binary.extend(&segment.data);
current_addr = segment_addr + segment.data.len();
}
Some(LoadSegment {
addr: first.addr,
data: binary,
})
}
pub fn start_addr(&self) -> u32 {
self.addr
}
pub fn end_addr(&self) -> u32 {
self.addr + (self.data.len() as u32)
}
}
#[derive(Clone)]
pub struct TestCase {
pub suite_name: String,
pub test_name: String,
pub addr: u32,
}
impl TestCase {
pub fn symbol_name(&self) -> String {
format!(
"__test_{}__target_test__{}",
self.suite_name, self.test_name
)
}
}
#[derive(Clone)]
pub struct FailedAssert {
pub lineno: Option<u32>,
pub file_name: Option<String>,
pub assertion: Option<TargetAssertion>,
}
#[derive(Clone)]
pub struct TestResult {
pub case: TestCase,
pub timestamp: SystemTime,
pub error: Option<FailedAssert>,
}
enum TargetState {
Idle,
Ready,
Started,
Passed,
Failed,
}
#[derive(Clone)]
pub enum TargetAssertion {
Equal,
True,
False,
Other(u32),
}
struct TargetData {
state: Option<TargetState>,
executed_function: Option<u32>,
fail_reason: Option<TargetAssertion>,
file_path: Option<String>,
lineno: Option<u32>,
}
impl TargetData {
fn crc32(data: &[u8]) -> u32 {
crc32(data)
}
fn fetch(connection: &mut impl Connection, addr: u32) -> Result<TargetData, String> {
let data = connection.read_ram(addr, 6 * 4)?;
let ref_crc = Self::crc32(&data[0..data.len() - 4]);
let crc = LittleEndian::read_u32(&data[20..data.len()]);
if crc != ref_crc {
return Err(format!("Connection failed to read from RAM: Invalid CRC"));
}
let state = LittleEndian::read_u32(&data[0..4]);
let executed_function = LittleEndian::read_u32(&data[4..8]);
let fail_reason = LittleEndian::read_u32(&data[8..12]);
let fail_reason = match fail_reason {
0 => None,
1 => Some(TargetAssertion::Equal),
2 => Some(TargetAssertion::True),
3 => Some(TargetAssertion::False),
x => Some(TargetAssertion::Other(x)),
};
let state = match state {
0 => None,
0x8C3F82FA => Some(TargetState::Idle),
0xD79A2E5F => Some(TargetState::Ready),
0xCD833CB7 => Some(TargetState::Started),
0xBAF2C481 => Some(TargetState::Passed),
0xCA83D14E => Some(TargetState::Failed),
x => { return Err(format!("Invalid data on target: State was: {}", x)); }
};
let file_path = LittleEndian::read_u32(&data[12..16]);
let lineno = LittleEndian::read_u32(&data[16..20]);
let file_path = if file_path != 0 {
Some(connection.read_utf8_string(file_path)?)
} else {
None
};
Ok(TargetData {
state,
executed_function: if executed_function != 0 { Some(executed_function) } else { None },
fail_reason,
file_path,
lineno: if lineno != 0 { Some(lineno) } else { None },
})
}
}
pub struct Runner<T: Connection> {
data: LoadSegment,
stack_pointer: u32,
entry_point: u32,
run_test_addr: u32,
test_data_addr: u32,
tests: Vec<TestCase>,
connection: T,
}
impl<T: Connection> Runner<T> {
pub fn new(
binary: &TestBinary,
vector_table_addr: u32,
connection: T,
) -> Result<Self, String> {
let segments_to_load = LoadSegment::get_from_file(binary);
let segment = LoadSegment::collapse_segments(segments_to_load);
let segment = segment.ok_or(format!("Binary does not contain a loadable segment."))?;
if vector_table_addr < segment.addr || vector_table_addr + 8 > segment.end_addr() {
return Err(format!("Vector table not in binary."));
}
let addr = (vector_table_addr - segment.addr) as usize;
let stack_pointer = LittleEndian::read_u32(&segment.data[addr..addr + 4]);
let entry_point = LittleEndian::read_u32(&segment.data[addr + 4..addr + 8]);
let mut symbols = HashMap::new();
for symbol in binary.file.symbols() {
symbols.insert(symbol.name().unwrap().to_string(), symbol.address() as u32);
}
let run_test_addr = Self::retrieve_symbol(&symbols, "target_test_fun_to_run")?;
let test_data_addr = Self::retrieve_symbol(&symbols, "target_test_data")?;
Ok(Self {
data: segment,
stack_pointer,
entry_point,
run_test_addr,
tests: Self::enumerate_tests(binary),
test_data_addr,
connection,
})
}
fn retrieve_symbol(symbols: &HashMap<String, u32>, name: &str) -> Result<u32, String> {
match symbols.get(name) {
None => {
return Err(format!(
"Did not find test runner in binary (symbol `{}` missing). Did you link it?",
name
));
}
Some(x) => Ok(*x),
}
}
fn enumerate_tests(binary: &TestBinary) -> Vec<TestCase> {
let test_re =
Regex::new(r"^target_test_test_(?P<suite_name>.*?)__target_test__(?P<test_name>.*?)$")
.unwrap();
let mut tests = Vec::new();
for symbol in binary.file.symbols() {
let name = symbol.name().unwrap();
if let Some(captures) = test_re.captures(name) {
let suite_name = captures.name("suite_name").unwrap().as_str().to_string();
let test_name = captures.name("test_name").unwrap().as_str().to_string();
tests.push(TestCase {
suite_name,
test_name,
addr: symbol.address() as u32,
})
}
}
tests
}
pub fn download(&mut self) -> Result<(), String> {
self.connection.download(self.data.addr, &self.data.data)
}
pub fn run_test(&mut self, test_case: &TestCase) -> Result<TestResult, String> {
log::debug!("Running test: {} @ {:X}", test_case.test_name, test_case.addr);
self.connection.reset_run(self.stack_pointer, self.entry_point)?;
log::debug!("Waiting for device to boot and enter test framework");
self.wait_for_ready(Duration::from_millis(500))?;
log::debug!("Halting device again to write test function pointer");
self.connection.halt(Duration::from_millis(100))?;
let mut fun_ptr = [0_u8; 4];
LittleEndian::write_u32(&mut fun_ptr, test_case.addr as u32);
self.connection.write_ram(self.run_test_addr as u32, &fun_ptr)?;
self.connection.run()?;
let data = self.wait_for_done(Duration::from_millis(500))?;
let test_passed = matches!( &data.state, Some(TargetState::Passed));
if let Some(executed_function) = data.executed_function {
if executed_function != test_case.addr {
return Err(format!("Test framework executed wrong test function. Expected function @{:X} but executed @{:X}", test_case.addr, executed_function));
}
} else {
return Err(format!("Test framework did not execute a test function. Expected function @{:X}", test_case.addr));
}
let error = if !test_passed {
Some(FailedAssert {
lineno: data.lineno,
file_name: data.file_path,
assertion: data.fail_reason,
})
} else {
None
};
Ok(TestResult {
case: test_case.clone(),
timestamp: SystemTime::now(),
error,
})
}
pub fn run_all_tests(&mut self) -> Result<Vec<TestResult>, String> {
let mut ret = Vec::new();
let tests = self.tests.clone();
for test in tests {
println!("Running test: {} -- {}", test.suite_name, test.test_name);
let result = self.run_test(&test)?;
if let Some(error) = &result.error {
let file_name = match &error.file_name {
None => "".to_string(),
Some(x) => x.to_string()
};
println!("Test failed at: {}:{}", file_name, error.lineno.unwrap_or_default());
} else {
println!("Test Passed\n");
}
ret.push(result);
}
Ok(ret)
}
fn wait_for_done(&mut self, timeout: Duration) -> Result<TargetData, String> {
let now = Instant::now();
while now.elapsed().as_millis() < timeout.as_millis() {
sleep(Duration::from_millis(10));
let addr = self.test_data_addr;
let data = TargetData::fetch(&mut self.connection, addr)?;
let done = match data.state {
Some(TargetState::Passed) | Some(TargetState::Failed) => true,
_ => false,
};
if done {
return Ok(data);
}
}
Err(format!("Timeout while waiting for test to finish"))
}
pub fn wait_for_ready(&mut self, timeout: Duration) -> Result<(), String> {
let now = Instant::now();
while now.elapsed().as_millis() < timeout.as_millis() {
sleep(Duration::from_millis(10));
let addr = self.test_data_addr;
let data = self.connection.read_ram(addr, 6 * 4)?;
let crc = LittleEndian::read_u32(&data[20..data.len()]);
if crc == 0 {
continue;
}
let data = TargetData::fetch(&mut self.connection, addr)?;
let done = match data.state {
Some(TargetState::Ready) => true,
_ => false,
};
if done {
return Ok(());
}
}
Err(format!("Timeout while waiting for test suite to start up"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_crc() {
let crc = TargetData::crc32(&[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]);
assert_eq!(crc, 0xCBF43926);
}
}
| 31.948276 | 162 | 0.551924 |
0a0b43c1953b0bcf870e19767bdc4f811b38bb67
| 1,531 |
use crate::internal;
#[repr(u32)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum Align {
Auto = 0,
FlexStart = 1,
Center = 2,
FlexEnd = 3,
Stretch = 4,
Baseline = 5,
SpaceBetween = 6,
SpaceAround = 7,
}
impl Default for Align {
fn default() -> Self {
Self::Auto
}
}
impl From<Align> for internal::YGAlign {
fn from(a: Align) -> internal::YGAlign {
match a {
Align::Auto => internal::YGAlign::YGAlignAuto,
Align::FlexStart => internal::YGAlign::YGAlignFlexStart,
Align::Center => internal::YGAlign::YGAlignCenter,
Align::FlexEnd => internal::YGAlign::YGAlignFlexEnd,
Align::Stretch => internal::YGAlign::YGAlignStretch,
Align::Baseline => internal::YGAlign::YGAlignBaseline,
Align::SpaceBetween => internal::YGAlign::YGAlignSpaceBetween,
Align::SpaceAround => internal::YGAlign::YGAlignSpaceAround,
}
}
}
impl From<internal::YGAlign> for Align {
fn from(a: internal::YGAlign) -> Align {
match a {
internal::YGAlign::YGAlignAuto => Align::Auto,
internal::YGAlign::YGAlignFlexStart => Align::FlexStart,
internal::YGAlign::YGAlignCenter => Align::Center,
internal::YGAlign::YGAlignFlexEnd => Align::FlexEnd,
internal::YGAlign::YGAlignStretch => Align::Stretch,
internal::YGAlign::YGAlignBaseline => Align::Baseline,
internal::YGAlign::YGAlignSpaceBetween => Align::SpaceBetween,
internal::YGAlign::YGAlignSpaceAround => Align::SpaceAround,
}
}
}
| 29.442308 | 70 | 0.695624 |
7956cfe4dcef3b5b58e7b89a67dfa688b6666cb9
| 67,013 |
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::convert::{TryFrom, TryInto};
use std::fs::{
read_dir, remove_dir, remove_file, rename, DirBuilder, File, FileType, OpenOptions, ReadDir,
};
use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::time::SystemTime;
use log::trace;
use rustc_data_structures::fx::FxHashMap;
use rustc_middle::ty::{self, layout::LayoutOf};
use rustc_target::abi::{Align, Size};
use crate::*;
use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
use shims::time::system_time_to_duration;
#[derive(Debug)]
struct FileHandle {
file: File,
writable: bool,
}
trait FileDescriptor: std::fmt::Debug {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle>;
fn read<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>>;
fn write<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>>;
fn seek<'tcx>(
&mut self,
communicate_allowed: bool,
offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>>;
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>>;
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>>;
}
impl FileDescriptor for FileHandle {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
Ok(&self)
}
fn read<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
Ok(self.file.read(bytes))
}
fn write<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
Ok(self.file.write(bytes))
}
fn seek<'tcx>(
&mut self,
communicate_allowed: bool,
offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
Ok(self.file.seek(offset))
}
fn close<'tcx>(
self: Box<Self>,
communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
// We sync the file if it was opened in a mode different than read-only.
if self.writable {
// `File::sync_all` does the checks that are done when closing a file. We do this to
// to handle possible errors correctly.
let result = self.file.sync_all().map(|_| 0i32);
// Now we actually close the file.
drop(self);
// And return the result.
Ok(result)
} else {
// We drop the file, this closes it but ignores any errors
// produced when closing it. This is done because
// `File::sync_all` cannot be done over files like
// `/dev/urandom` which are read-only. Check
// https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
// for a deeper discussion.
drop(self);
Ok(Ok(0))
}
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
let duplicated = self.file.try_clone()?;
Ok(Box::new(FileHandle { file: duplicated, writable: self.writable }))
}
}
impl FileDescriptor for io::Stdin {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
throw_unsup_format!("stdin cannot be used as FileHandle");
}
fn read<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
if !communicate_allowed {
// We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
helpers::isolation_abort_error("`read` from stdin")?;
}
Ok(Read::read(self, bytes))
}
fn write<'tcx>(
&mut self,
_communicate_allowed: bool,
_bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
throw_unsup_format!("cannot write to stdin");
}
fn seek<'tcx>(
&mut self,
_communicate_allowed: bool,
_offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
throw_unsup_format!("cannot seek on stdin");
}
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
throw_unsup_format!("stdin cannot be closed");
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
Ok(Box::new(io::stdin()))
}
}
impl FileDescriptor for io::Stdout {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
throw_unsup_format!("stdout cannot be used as FileHandle");
}
fn read<'tcx>(
&mut self,
_communicate_allowed: bool,
_bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
throw_unsup_format!("cannot read from stdout");
}
fn write<'tcx>(
&mut self,
_communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
// We allow writing to stderr even with isolation enabled.
let result = Write::write(self, bytes);
// Stdout is buffered, flush to make sure it appears on the
// screen. This is the write() syscall of the interpreted
// program, we want it to correspond to a write() syscall on
// the host -- there is no good in adding extra buffering
// here.
io::stdout().flush().unwrap();
Ok(result)
}
fn seek<'tcx>(
&mut self,
_communicate_allowed: bool,
_offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
throw_unsup_format!("cannot seek on stdout");
}
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
throw_unsup_format!("stdout cannot be closed");
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
Ok(Box::new(io::stdout()))
}
}
impl FileDescriptor for io::Stderr {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
throw_unsup_format!("stderr cannot be used as FileHandle");
}
fn read<'tcx>(
&mut self,
_communicate_allowed: bool,
_bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
throw_unsup_format!("cannot read from stderr");
}
fn write<'tcx>(
&mut self,
_communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
// We allow writing to stderr even with isolation enabled.
// No need to flush, stderr is not buffered.
Ok(Write::write(self, bytes))
}
fn seek<'tcx>(
&mut self,
_communicate_allowed: bool,
_offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
throw_unsup_format!("cannot seek on stderr");
}
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
throw_unsup_format!("stderr cannot be closed");
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
Ok(Box::new(io::stderr()))
}
}
#[derive(Debug)]
pub struct FileHandler {
handles: BTreeMap<i32, Box<dyn FileDescriptor>>,
}
impl<'tcx> Default for FileHandler {
fn default() -> Self {
let mut handles: BTreeMap<_, Box<dyn FileDescriptor>> = BTreeMap::new();
handles.insert(0i32, Box::new(io::stdin()));
handles.insert(1i32, Box::new(io::stdout()));
handles.insert(2i32, Box::new(io::stderr()));
FileHandler { handles }
}
}
impl<'tcx> FileHandler {
fn insert_fd(&mut self, file_handle: Box<dyn FileDescriptor>) -> i32 {
self.insert_fd_with_min_fd(file_handle, 0)
}
fn insert_fd_with_min_fd(&mut self, file_handle: Box<dyn FileDescriptor>, min_fd: i32) -> i32 {
// Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
// between used FDs, the find_map combinator will return it. If the first such unused FD
// is after all other used FDs, the find_map combinator will return None, and we will use
// the FD following the greatest FD thus far.
let candidate_new_fd =
self.handles.range(min_fd..).zip(min_fd..).find_map(|((fd, _fh), counter)| {
if *fd != counter {
// There was a gap in the fds stored, return the first unused one
// (note that this relies on BTreeMap iterating in key order)
Some(counter)
} else {
// This fd is used, keep going
None
}
});
let new_fd = candidate_new_fd.unwrap_or_else(|| {
// find_map ran out of BTreeMap entries before finding a free fd, use one plus the
// maximum fd in the map
self.handles
.last_key_value()
.map(|(fd, _)| fd.checked_add(1).unwrap())
.unwrap_or(min_fd)
});
self.handles.try_insert(new_fd, file_handle).unwrap();
new_fd
}
}
impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
fn macos_stat_write_buf(
&mut self,
metadata: FileMetadata,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let mode: u16 = metadata.mode.to_u16()?;
let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
let dev_t_layout = this.libc_ty_layout("dev_t")?;
let mode_t_layout = this.libc_ty_layout("mode_t")?;
let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
let ino_t_layout = this.libc_ty_layout("ino_t")?;
let uid_t_layout = this.libc_ty_layout("uid_t")?;
let gid_t_layout = this.libc_ty_layout("gid_t")?;
let time_t_layout = this.libc_ty_layout("time_t")?;
let long_layout = this.libc_ty_layout("c_long")?;
let off_t_layout = this.libc_ty_layout("off_t")?;
let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
let imms = [
immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
immty_from_uint_checked(0u128, uint32_t_layout)?, // padding
immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
];
let buf = this.deref_operand(buf_op)?;
this.write_packed_immediates(&buf, &imms)?;
Ok(0)
}
/// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
/// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
/// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
/// types (like `read`, that returns an `i64`).
fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
let this = self.eval_context_mut();
let ebadf = this.eval_libc("EBADF")?;
this.set_last_error(ebadf)?;
Ok((-1).into())
}
fn file_type_to_d_type(
&mut self,
file_type: std::io::Result<FileType>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
match file_type {
Ok(file_type) => {
if file_type.is_dir() {
Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
} else if file_type.is_file() {
Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
} else if file_type.is_symlink() {
Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
} else {
// Certain file types are only supported when the host is a Unix system.
// (i.e. devices and sockets) If it is, check those cases, if not, fall back to
// DT_UNKNOWN sooner.
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt;
if file_type.is_block_device() {
Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
} else if file_type.is_char_device() {
Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
} else if file_type.is_fifo() {
Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
} else if file_type.is_socket() {
Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
} else {
Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
}
}
#[cfg(not(unix))]
Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
}
}
Err(e) =>
return match e.raw_os_error() {
Some(error) => Ok(error),
None =>
throw_unsup_format!(
"the error {} couldn't be converted to a return value",
e
),
},
}
}
}
#[derive(Debug)]
pub struct DirHandler {
/// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
/// and closedir.
///
/// When opendir is called, a directory iterator is created on the host for the target
/// directory, and an entry is stored in this hash map, indexed by an ID which represents
/// the directory stream. When readdir is called, the directory stream ID is used to look up
/// the corresponding ReadDir iterator from this map, and information from the next
/// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
/// the map.
streams: FxHashMap<u64, ReadDir>,
/// ID number to be used by the next call to opendir
next_id: u64,
}
impl DirHandler {
fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
let id = self.next_id;
self.next_id += 1;
self.streams.try_insert(id, read_dir).unwrap();
id
}
}
impl Default for DirHandler {
fn default() -> DirHandler {
DirHandler {
streams: FxHashMap::default(),
// Skip 0 as an ID, because it looks like a null pointer to libc
next_id: 1,
}
}
}
fn maybe_sync_file(
file: &File,
writable: bool,
operation: fn(&File) -> std::io::Result<()>,
) -> std::io::Result<i32> {
if !writable && cfg!(windows) {
// sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
// for writing. (FlushFileBuffers requires that the file handle have the
// GENERIC_WRITE right)
Ok(0i32)
} else {
let result = operation(file);
result.map(|_| 0i32)
}
}
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
fn open(&mut self, args: &[OpTy<'tcx, Tag>]) -> InterpResult<'tcx, i32> {
if args.len() < 2 || args.len() > 3 {
throw_ub_format!(
"incorrect number of arguments for `open`: got {}, expected 2 or 3",
args.len()
);
}
let this = self.eval_context_mut();
let path_op = &args[0];
let flag = this.read_scalar(&args[1])?.to_i32()?;
let mut options = OpenOptions::new();
let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
let o_wronly = this.eval_libc_i32("O_WRONLY")?;
let o_rdwr = this.eval_libc_i32("O_RDWR")?;
// The first two bits of the flag correspond to the access mode in linux, macOS and
// windows. We need to check that in fact the access mode flags for the current target
// only use these two bits, otherwise we are in an unsupported target and should error.
if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
throw_unsup_format!("access mode flags on this target are unsupported");
}
let mut writable = true;
// Now we check the access mode
let access_mode = flag & 0b11;
if access_mode == o_rdonly {
writable = false;
options.read(true);
} else if access_mode == o_wronly {
options.write(true);
} else if access_mode == o_rdwr {
options.read(true).write(true);
} else {
throw_unsup_format!("unsupported access mode {:#x}", access_mode);
}
// We need to check that there aren't unsupported options in `flag`. For this we try to
// reproduce the content of `flag` in the `mirror` variable using only the supported
// options.
let mut mirror = access_mode;
let o_append = this.eval_libc_i32("O_APPEND")?;
if flag & o_append != 0 {
options.append(true);
mirror |= o_append;
}
let o_trunc = this.eval_libc_i32("O_TRUNC")?;
if flag & o_trunc != 0 {
options.truncate(true);
mirror |= o_trunc;
}
let o_creat = this.eval_libc_i32("O_CREAT")?;
if flag & o_creat != 0 {
// Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
// C integer promotion rules mean that on the ABI level, it gets passed as `u32`
// (see https://github.com/rust-lang/rust/issues/71915).
let mode = if let Some(arg) = args.get(2) {
this.read_scalar(arg)?.to_u32()?
} else {
throw_ub_format!(
"incorrect number of arguments for `open` with `O_CREAT`: got {}, expected 3",
args.len()
);
};
if mode != 0o666 {
throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
}
mirror |= o_creat;
let o_excl = this.eval_libc_i32("O_EXCL")?;
if flag & o_excl != 0 {
mirror |= o_excl;
options.create_new(true);
} else {
options.create(true);
}
}
let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
if flag & o_cloexec != 0 {
// We do not need to do anything for this flag because `std` already sets it.
// (Technically we do not support *not* setting this flag, but we ignore that.)
mirror |= o_cloexec;
}
// If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
// then we throw an error.
if flag != mirror {
throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
}
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`open`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let fd = options.open(&path).map(|file| {
let fh = &mut this.machine.file_handler;
fh.insert_fd(Box::new(FileHandle { file, writable }))
});
this.try_unwrap_io_result(fd)
}
fn fcntl(&mut self, args: &[OpTy<'tcx, Tag>]) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
if args.len() < 2 {
throw_ub_format!(
"incorrect number of arguments for fcntl: got {}, expected at least 2",
args.len()
);
}
let fd = this.read_scalar(&args[0])?.to_i32()?;
let cmd = this.read_scalar(&args[1])?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fcntl`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
// We only support getting the flags for a descriptor.
if cmd == this.eval_libc_i32("F_GETFD")? {
// Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
// `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
// always sets this flag when opening a file. However we still need to check that the
// file itself is open.
let &[_, _] = check_arg_count(args)?;
if this.machine.file_handler.handles.contains_key(&fd) {
Ok(this.eval_libc_i32("FD_CLOEXEC")?)
} else {
this.handle_not_found()
}
} else if cmd == this.eval_libc_i32("F_DUPFD")?
|| cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
{
// Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
// because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
// differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
// thus they can share the same implementation here.
let &[_, _, ref start] = check_arg_count(args)?;
let start = this.read_scalar(start)?.to_i32()?;
let fh = &mut this.machine.file_handler;
match fh.handles.get_mut(&fd) {
Some(file_descriptor) => {
let dup_result = file_descriptor.dup();
match dup_result {
Ok(dup_fd) => Ok(fh.insert_fd_with_min_fd(dup_fd, start)),
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(-1)
}
}
}
None => return this.handle_not_found(),
}
} else if this.tcx.sess.target.os == "macos" && cmd == this.eval_libc_i32("F_FULLFSYNC")? {
let &[_, _] = check_arg_count(args)?;
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support fullfsync for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_all);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
} else {
throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
}
}
fn close(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
if let Some(file_descriptor) = this.machine.file_handler.handles.remove(&fd) {
let result = file_descriptor.close(this.machine.communicate())?;
this.try_unwrap_io_result(result)
} else {
this.handle_not_found()
}
}
fn read(&mut self, fd: i32, buf: Pointer<Option<Tag>>, count: u64) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescriptor` trait.
trace!("Reading from FD {}, size {}", fd, count);
// Check that the *entire* buffer is actually valid memory.
this.memory.check_ptr_access_align(
buf,
Size::from_bytes(count),
Align::ONE,
CheckInAllocMsg::MemoryAccessTest,
)?;
// We cap the number of read bytes to the largest value that we are able to fit in both the
// host's and target's `isize`. This saves us from having to handle overflows later.
let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
let communicate = this.machine.communicate();
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
trace!("read: FD mapped to {:?}", file_descriptor);
// We want to read at most `count` bytes. We are sure that `count` is not negative
// because it was a target's `usize`. Also we are sure that its smaller than
// `usize::MAX` because it is a host's `isize`.
let mut bytes = vec![0; count as usize];
// `File::read` never returns a value larger than `count`,
// so this cannot fail.
let result =
file_descriptor.read(communicate, &mut bytes)?.map(|c| i64::try_from(c).unwrap());
match result {
Ok(read_bytes) => {
// If reading to `bytes` did not fail, we write those bytes to the buffer.
this.memory.write_bytes(buf, bytes)?;
Ok(read_bytes)
}
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(-1)
}
}
} else {
trace!("read: FD not found");
this.handle_not_found()
}
}
fn write(&mut self, fd: i32, buf: Pointer<Option<Tag>>, count: u64) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescriptor` trait.
// Check that the *entire* buffer is actually valid memory.
this.memory.check_ptr_access_align(
buf,
Size::from_bytes(count),
Align::ONE,
CheckInAllocMsg::MemoryAccessTest,
)?;
// We cap the number of written bytes to the largest value that we are able to fit in both the
// host's and target's `isize`. This saves us from having to handle overflows later.
let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
let communicate = this.machine.communicate();
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
let result =
file_descriptor.write(communicate, &bytes)?.map(|c| i64::try_from(c).unwrap());
this.try_unwrap_io_result(result)
} else {
this.handle_not_found()
}
}
fn lseek64(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
offset_op: &OpTy<'tcx, Tag>,
whence_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescriptor` trait.
let fd = this.read_scalar(fd_op)?.to_i32()?;
let offset = this.read_scalar(offset_op)?.to_i64()?;
let whence = this.read_scalar(whence_op)?.to_i32()?;
let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
SeekFrom::Start(u64::try_from(offset).unwrap())
} else if whence == this.eval_libc_i32("SEEK_CUR")? {
SeekFrom::Current(offset)
} else if whence == this.eval_libc_i32("SEEK_END")? {
SeekFrom::End(offset)
} else {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
return Ok(-1);
};
let communicate = this.machine.communicate();
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
let result = file_descriptor
.seek(communicate, seek_from)?
.map(|offset| i64::try_from(offset).unwrap());
this.try_unwrap_io_result(result)
} else {
this.handle_not_found()
}
}
fn unlink(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`unlink`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = remove_file(path).map(|_| 0);
this.try_unwrap_io_result(result)
}
fn symlink(
&mut self,
target_op: &OpTy<'tcx, Tag>,
linkpath_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
#[cfg(unix)]
fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
#[cfg(windows)]
fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
use std::os::windows::fs;
if src.is_dir() { fs::symlink_dir(src, dst) } else { fs::symlink_file(src, dst) }
}
let this = self.eval_context_mut();
let target = this.read_path_from_c_str(this.read_pointer(target_op)?)?;
let linkpath = this.read_path_from_c_str(this.read_pointer(linkpath_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`symlink`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = create_link(&target, &linkpath).map(|_| 0);
this.try_unwrap_io_result(result)
}
fn macos_stat(
&mut self,
path_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "stat");
let path_scalar = this.read_pointer(path_op)?;
let path = this.read_path_from_c_str(path_scalar)?.into_owned();
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`stat`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(-1);
}
// `stat` always follows symlinks.
let metadata = match FileMetadata::from_path(this, &path, true)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
// `lstat` is used to get symlink metadata.
fn macos_lstat(
&mut self,
path_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "lstat");
let path_scalar = this.read_pointer(path_op)?;
let path = this.read_path_from_c_str(path_scalar)?.into_owned();
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`lstat`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(-1);
}
let metadata = match FileMetadata::from_path(this, &path, false)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
fn macos_fstat(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "fstat");
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fstat`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
let metadata = match FileMetadata::from_fd(this, fd)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
fn linux_statx(
&mut self,
dirfd_op: &OpTy<'tcx, Tag>, // Should be an `int`
pathname_op: &OpTy<'tcx, Tag>, // Should be a `const char *`
flags_op: &OpTy<'tcx, Tag>, // Should be an `int`
_mask_op: &OpTy<'tcx, Tag>, // Should be an `unsigned int`
statxbuf_op: &OpTy<'tcx, Tag>, // Should be a `struct statx *`
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("linux", "statx");
let statxbuf_ptr = this.read_pointer(statxbuf_op)?;
let pathname_ptr = this.read_pointer(pathname_op)?;
// If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
if this.ptr_is_null(statxbuf_ptr)? || this.ptr_is_null(pathname_ptr)? {
let efault = this.eval_libc("EFAULT")?;
this.set_last_error(efault)?;
return Ok(-1);
}
// Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
// proper `MemPlace` and then write the results of this function to it. However, the
// `syscall` function is untyped. This means that all the `statx` parameters are provided
// as `isize`s instead of having the proper types. Thus, we have to recover the layout of
// `statxbuf_op` by using the `libc::statx` struct type.
let statxbuf_place = {
// FIXME: This long path is required because `libc::statx` is an struct and also a
// function and `resolve_path` is returning the latter.
let statx_ty = this
.resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
.ty(*this.tcx, ty::ParamEnv::reveal_all());
let statx_layout = this.layout_of(statx_ty)?;
MPlaceTy::from_aligned_ptr(statxbuf_ptr, statx_layout)
};
let path = this.read_path_from_c_str(pathname_ptr)?.into_owned();
// See <https://github.com/rust-lang/rust/pull/79196> for a discussion of argument sizes.
let flags = this.read_scalar(flags_op)?.to_i32()?;
let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
// We only support:
// * interpreting `path` as an absolute directory,
// * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
// * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
// set.
// Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
// found this error, please open an issue reporting it.
if !(path.is_absolute()
|| dirfd == this.eval_libc_i32("AT_FDCWD")?
|| (path.as_os_str().is_empty() && empty_path_flag))
{
throw_unsup_format!(
"using statx is only supported with absolute paths, relative paths with the file \
descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
file descriptor"
)
}
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`statx`", reject_with)?;
let ecode = if path.is_absolute() || dirfd == this.eval_libc_i32("AT_FDCWD")? {
// since `path` is provided, either absolute or
// relative to CWD, `EACCES` is the most relevant.
this.eval_libc("EACCES")?
} else {
// `dirfd` is set to target file, and `path` is empty
// (or we would have hit the `throw_unsup_format`
// above). `EACCES` would violate the spec.
assert!(empty_path_flag);
this.eval_libc("EBADF")?
};
this.set_last_error(ecode)?;
return Ok(-1);
}
// the `_mask_op` paramter specifies the file information that the caller requested.
// However `statx` is allowed to return information that was not requested or to not
// return information that was requested. This `mask` represents the information we can
// actually provide for any target.
let mut mask =
this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
// If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
// symbolic links.
let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
// If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
// represented by dirfd, whether it's a directory or otherwise.
let metadata = if path.as_os_str().is_empty() && empty_path_flag {
FileMetadata::from_fd(this, dirfd)?
} else {
FileMetadata::from_path(this, &path, follow_symlink)?
};
let metadata = match metadata {
Some(metadata) => metadata,
None => return Ok(-1),
};
// The `mode` field specifies the type of the file and the permissions over the file for
// the owner, its group and other users. Given that we can only provide the file type
// without using platform specific methods, we only set the bits corresponding to the file
// type. This should be an `__u16` but `libc` provides its values as `u32`.
let mode: u16 = metadata
.mode
.to_u32()?
.try_into()
.unwrap_or_else(|_| bug!("libc contains bad value for constant"));
// We need to set the corresponding bits of `mask` if the access, creation and modification
// times were available. Otherwise we let them be zero.
let (access_sec, access_nsec) = metadata
.accessed
.map(|tup| {
mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
InterpResult::Ok(tup)
})
.unwrap_or(Ok((0, 0)))?;
let (created_sec, created_nsec) = metadata
.created
.map(|tup| {
mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
InterpResult::Ok(tup)
})
.unwrap_or(Ok((0, 0)))?;
let (modified_sec, modified_nsec) = metadata
.modified
.map(|tup| {
mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
InterpResult::Ok(tup)
})
.unwrap_or(Ok((0, 0)))?;
let __u32_layout = this.libc_ty_layout("__u32")?;
let __u64_layout = this.libc_ty_layout("__u64")?;
let __u16_layout = this.libc_ty_layout("__u16")?;
// Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
// zero for the unavailable fields.
let imms = [
immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
];
this.write_packed_immediates(&statxbuf_place, &imms)?;
Ok(0)
}
fn rename(
&mut self,
oldpath_op: &OpTy<'tcx, Tag>,
newpath_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let oldpath_ptr = this.read_pointer(oldpath_op)?;
let newpath_ptr = this.read_pointer(newpath_op)?;
if this.ptr_is_null(oldpath_ptr)? || this.ptr_is_null(newpath_ptr)? {
let efault = this.eval_libc("EFAULT")?;
this.set_last_error(efault)?;
return Ok(-1);
}
let oldpath = this.read_path_from_c_str(oldpath_ptr)?;
let newpath = this.read_path_from_c_str(newpath_ptr)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`rename`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = rename(oldpath, newpath).map(|_| 0);
this.try_unwrap_io_result(result)
}
fn mkdir(
&mut self,
path_op: &OpTy<'tcx, Tag>,
mode_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
#[cfg_attr(not(unix), allow(unused_variables))]
let mode = if this.tcx.sess.target.os == "macos" {
u32::from(this.read_scalar(mode_op)?.to_u16()?)
} else {
this.read_scalar(mode_op)?.to_u32()?
};
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`mkdir`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = DirBuilder::new();
// If the host supports it, forward on the mode of the directory
// (i.e. permission bits and the sticky bit)
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(mode.into());
}
let result = builder.create(path).map(|_| 0i32);
this.try_unwrap_io_result(result)
}
fn rmdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`rmdir`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = remove_dir(path).map(|_| 0i32);
this.try_unwrap_io_result(result)
}
fn opendir(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
let this = self.eval_context_mut();
let name = this.read_path_from_c_str(this.read_pointer(name_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`opendir`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(Scalar::null_ptr(this));
}
let result = read_dir(name);
match result {
Ok(dir_iter) => {
let id = this.machine.dir_handler.insert_new(dir_iter);
// The libc API for opendir says that this method returns a pointer to an opaque
// structure, but we are returning an ID number. Thus, pass it as a scalar of
// pointer width.
Ok(Scalar::from_machine_usize(id, this))
}
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(Scalar::null_ptr(this))
}
}
}
fn linux_readdir64_r(
&mut self,
dirp_op: &OpTy<'tcx, Tag>,
entry_op: &OpTy<'tcx, Tag>,
result_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("linux", "readdir64_r");
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`readdir64_r`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
})?;
match dir_iter.next() {
Some(Ok(dir_entry)) => {
// Write into entry, write pointer to result, return 0 on success.
// The name is written with write_os_str_to_c_str, while the rest of the
// dirent64 struct is written using write_packed_immediates.
// For reference:
// pub struct dirent64 {
// pub d_ino: ino64_t,
// pub d_off: off64_t,
// pub d_reclen: c_ushort,
// pub d_type: c_uchar,
// pub d_name: [c_char; 256],
// }
let entry_place = this.deref_operand(entry_op)?;
let name_place = this.mplace_field(&entry_place, 4)?;
let file_name = dir_entry.file_name(); // not a Path as there are no separators!
let (name_fits, _) = this.write_os_str_to_c_str(
&file_name,
name_place.ptr,
name_place.layout.size.bytes(),
)?;
if !name_fits {
throw_unsup_format!(
"a directory entry had a name too large to fit in libc::dirent64"
);
}
let entry_place = this.deref_operand(entry_op)?;
let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
let off64_t_layout = this.libc_ty_layout("off64_t")?;
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
// If the host is a Unix system, fill in the inode number with its real value.
// If not, use 0 as a fallback value.
#[cfg(unix)]
let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
#[cfg(not(unix))]
let ino = 0u64;
let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
let imms = [
immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
];
this.write_packed_immediates(&entry_place, &imms)?;
let result_place = this.deref_operand(result_op)?;
this.write_scalar(this.read_scalar(entry_op)?, &result_place.into())?;
Ok(0)
}
None => {
// end of stream: return 0, assign *result=NULL
this.write_null(&this.deref_operand(result_op)?.into())?;
Ok(0)
}
Some(Err(e)) =>
match e.raw_os_error() {
// return positive error number on error
Some(error) => Ok(error),
None => {
throw_unsup_format!(
"the error {} couldn't be converted to a return value",
e
)
}
},
}
}
fn macos_readdir_r(
&mut self,
dirp_op: &OpTy<'tcx, Tag>,
entry_op: &OpTy<'tcx, Tag>,
result_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "readdir_r");
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`readdir_r`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
})?;
match dir_iter.next() {
Some(Ok(dir_entry)) => {
// Write into entry, write pointer to result, return 0 on success.
// The name is written with write_os_str_to_c_str, while the rest of the
// dirent struct is written using write_packed_Immediates.
// For reference:
// pub struct dirent {
// pub d_ino: u64,
// pub d_seekoff: u64,
// pub d_reclen: u16,
// pub d_namlen: u16,
// pub d_type: u8,
// pub d_name: [c_char; 1024],
// }
let entry_place = this.deref_operand(entry_op)?;
let name_place = this.mplace_field(&entry_place, 5)?;
let file_name = dir_entry.file_name(); // not a Path as there are no separators!
let (name_fits, file_name_len) = this.write_os_str_to_c_str(
&file_name,
name_place.ptr,
name_place.layout.size.bytes(),
)?;
if !name_fits {
throw_unsup_format!(
"a directory entry had a name too large to fit in libc::dirent"
);
}
let entry_place = this.deref_operand(entry_op)?;
let ino_t_layout = this.libc_ty_layout("ino_t")?;
let off_t_layout = this.libc_ty_layout("off_t")?;
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
// If the host is a Unix system, fill in the inode number with its real value.
// If not, use 0 as a fallback value.
#[cfg(unix)]
let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
#[cfg(not(unix))]
let ino = 0u64;
let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
let imms = [
immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
];
this.write_packed_immediates(&entry_place, &imms)?;
let result_place = this.deref_operand(result_op)?;
this.write_scalar(this.read_scalar(entry_op)?, &result_place.into())?;
Ok(0)
}
None => {
// end of stream: return 0, assign *result=NULL
this.write_null(&this.deref_operand(result_op)?.into())?;
Ok(0)
}
Some(Err(e)) =>
match e.raw_os_error() {
// return positive error number on error
Some(error) => Ok(error),
None => {
throw_unsup_format!(
"the error {} couldn't be converted to a return value",
e
)
}
},
}
}
fn closedir(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`closedir`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
drop(dir_iter);
Ok(0)
} else {
this.handle_not_found()
}
}
fn ftruncate64(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
length_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
let length = this.read_scalar(length_op)?.to_i64()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`ftruncate64`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
// FIXME: Support ftruncate64 for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
if *writable {
if let Ok(length) = length.try_into() {
let result = file.set_len(length);
this.try_unwrap_io_result(result.map(|_| 0i32))
} else {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
Ok(-1)
}
} else {
// The file is not writable
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
Ok(-1)
}
} else {
this.handle_not_found()
}
}
fn fsync(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
// On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
// underlying disk to finish writing. In the interest of host compatibility,
// we conservatively implement this with `sync_all`, which
// *does* wait for the disk.
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fsync`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support fsync for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_all);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
}
fn fdatasync(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fdatasync`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support fdatasync for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_data);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
}
fn sync_file_range(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
offset_op: &OpTy<'tcx, Tag>,
nbytes_op: &OpTy<'tcx, Tag>,
flags_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
let offset = this.read_scalar(offset_op)?.to_i64()?;
let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
let flags = this.read_scalar(flags_op)?.to_i32()?;
if offset < 0 || nbytes < 0 {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
return Ok(-1);
}
let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
| this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
| this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
if flags & allowed_flags != flags {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
return Ok(-1);
}
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`sync_file_range`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support sync_data_range for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_data);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
}
fn readlink(
&mut self,
pathname_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
bufsize_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
let pathname = this.read_path_from_c_str(this.read_pointer(pathname_op)?)?;
let buf = this.read_pointer(buf_op)?;
let bufsize = this.read_scalar(bufsize_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`readlink`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(-1);
}
let result = std::fs::read_link(pathname);
match result {
Ok(resolved) => {
let resolved = this.convert_path_separator(
Cow::Borrowed(resolved.as_ref()),
crate::shims::os_str::PathConversion::HostToTarget,
);
let mut path_bytes = crate::shims::os_str::os_str_to_bytes(resolved.as_ref())?;
let bufsize: usize = bufsize.try_into().unwrap();
if path_bytes.len() > bufsize {
path_bytes = &path_bytes[..bufsize]
}
// 'readlink' truncates the resolved path if
// the provided buffer is not large enough.
this.memory.write_bytes(buf, path_bytes.iter().copied())?;
Ok(path_bytes.len().try_into().unwrap())
}
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(-1)
}
}
}
}
/// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
/// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
/// epoch.
fn extract_sec_and_nsec<'tcx>(
time: std::io::Result<SystemTime>,
) -> InterpResult<'tcx, Option<(u64, u32)>> {
time.ok()
.map(|time| {
let duration = system_time_to_duration(&time)?;
Ok((duration.as_secs(), duration.subsec_nanos()))
})
.transpose()
}
/// Stores a file's metadata in order to avoid code duplication in the different metadata related
/// shims.
struct FileMetadata {
mode: Scalar<Tag>,
size: u64,
created: Option<(u64, u32)>,
accessed: Option<(u64, u32)>,
modified: Option<(u64, u32)>,
}
impl FileMetadata {
fn from_path<'tcx, 'mir>(
ecx: &mut MiriEvalContext<'mir, 'tcx>,
path: &Path,
follow_symlink: bool,
) -> InterpResult<'tcx, Option<FileMetadata>> {
let metadata =
if follow_symlink { std::fs::metadata(path) } else { std::fs::symlink_metadata(path) };
FileMetadata::from_meta(ecx, metadata)
}
fn from_fd<'tcx, 'mir>(
ecx: &mut MiriEvalContext<'mir, 'tcx>,
fd: i32,
) -> InterpResult<'tcx, Option<FileMetadata>> {
let option = ecx.machine.file_handler.handles.get(&fd);
let file = match option {
Some(file_descriptor) => &file_descriptor.as_file_handle()?.file,
None => return ecx.handle_not_found().map(|_: i32| None),
};
let metadata = file.metadata();
FileMetadata::from_meta(ecx, metadata)
}
fn from_meta<'tcx, 'mir>(
ecx: &mut MiriEvalContext<'mir, 'tcx>,
metadata: Result<std::fs::Metadata, std::io::Error>,
) -> InterpResult<'tcx, Option<FileMetadata>> {
let metadata = match metadata {
Ok(metadata) => metadata,
Err(e) => {
ecx.set_last_error_from_io_error(e.kind())?;
return Ok(None);
}
};
let file_type = metadata.file_type();
let mode_name = if file_type.is_file() {
"S_IFREG"
} else if file_type.is_dir() {
"S_IFDIR"
} else {
"S_IFLNK"
};
let mode = ecx.eval_libc(mode_name)?;
let size = metadata.len();
let created = extract_sec_and_nsec(metadata.created())?;
let accessed = extract_sec_and_nsec(metadata.accessed())?;
let modified = extract_sec_and_nsec(metadata.modified())?;
// FIXME: Provide more fields using platform specific methods.
Ok(Some(FileMetadata { mode, size, created, accessed, modified }))
}
}
| 39.582398 | 104 | 0.569457 |
9c1d3d7a08de827cc783497a7b5207c984d95f51
| 332 |
#[test]
fn test_path_rename() {
assert_wasi_output!(
"../../wasitests/path_rename.wasm",
"path_rename",
vec![],
vec![(
"temp".to_string(),
::std::path::PathBuf::from("wasitests/test_fs/temp")
),],
vec![],
"../../wasitests/path_rename.out"
);
}
| 22.133333 | 64 | 0.475904 |
2987792a3699dc0b61bcc22de13ac0b5ad358233
| 30,569 |
use super::*;
macro_rules! start(
($rt:ident, $for_n_expr:ident) => {
if let Some(ref start_expr) = $for_n_expr.start {
let start = match $rt.expression(start_expr, Side::Right)? {
(x, Flow::Return) => { return Ok((x, Flow::Return)); }
(Some(x), Flow::Continue) => x,
_ => return Err($rt.module.error(start_expr.source_range(),
&format!("{}\nExpected number from for start",
$rt.stack_trace()), $rt))
};
let start = match $rt.resolve(&start) {
&Variable::F64(val, _) => val,
x => return Err($rt.module.error(start_expr.source_range(),
&$rt.expected(x, "number"), $rt))
};
start
} else { 0.0 }
};
);
macro_rules! end(
($rt:ident, $for_n_expr:ident) => {{
let end = match $rt.expression(&$for_n_expr.end, Side::Right)? {
(x, Flow::Return) => { return Ok((x, Flow::Return)); }
(Some(x), Flow::Continue) => x,
_ => return Err($rt.module.error($for_n_expr.end.source_range(),
&format!("{}\nExpected number from for end",
$rt.stack_trace()), $rt))
};
match $rt.resolve(&end) {
&Variable::F64(val, _) => val,
x => return Err($rt.module.error($for_n_expr.end.source_range(),
&$rt.expected(x, "number"), $rt))
}
}};
);
macro_rules! cond(
($rt:ident, $for_n_expr:ident, $st:ident, $end:ident) => {
match &$rt.stack[$st - 1] {
&Variable::F64(val, _) => {
if val < $end {}
else { break }
val
}
x => return Err($rt.module.error($for_n_expr.source_range,
&$rt.expected(x, "number"), $rt))
}
};
);
macro_rules! break_(
($x:ident, $for_n_expr:ident, $flow:ident) => {{
if let Some(label) = $x {
let same =
if let Some(ref for_label) = $for_n_expr.label {
&label == for_label
} else { false };
if !same {
$flow = Flow::Break(Some(label))
}
}
break;
}};
($x:ident, $for_n_expr:ident, $flow:ident, $label:tt) => {{
if let Some(label) = $x {
let same =
if let Some(ref for_label) = $for_n_expr.label {
&label == for_label
} else { false };
if !same {
$flow = Flow::Break(Some(label))
}
}
break $label;
}};
);
macro_rules! continue_(
($x:ident, $for_n_expr:ident, $flow:ident) => {{
if let Some(label) = $x {
let same =
if let Some(ref for_label) = $for_n_expr.label {
&label == for_label
} else { false };
if !same {
$flow = Flow::ContinueLoop(Some(label));
break;
}
}
}};
);
macro_rules! inc(
($rt:ident, $for_n_expr:ident, $st:ident) => {{
let error = if let Variable::F64(ref mut val, _) = $rt.stack[$st - 1] {
*val += 1.0;
false
} else { true };
if error {
return Err($rt.module.error($for_n_expr.source_range,
&$rt.expected(&$rt.stack[$st - 1], "number"), $rt))
}
}};
);
impl Runtime {
pub(crate) fn for_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(_, Flow::Continue) => {}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((None, flow))
}
pub(crate) fn sum_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let mut sum = 0.0;
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::F64(val, _) => sum += val,
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "number"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `number`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::f64(sum)), flow))
}
pub(crate) fn prod_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let mut prod = 1.0;
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::F64(val, _) => prod *= val,
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "number"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `number`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::f64(prod)), flow))
}
pub(crate) fn min_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
let mut min = ::std::f64::NAN;
let mut sec = None;
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
let ind = cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::F64(val, ref val_sec) => {
if min.is_nan() || min > val {
min = val;
sec = match *val_sec {
None => Some(Box::new(vec![Variable::f64(ind)])),
Some(ref arr) => {
let mut arr = arr.clone();
arr.push(Variable::f64(ind));
Some(arr)
}
};
}
}
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "number"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `number or option`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::F64(min, sec)), flow))
}
pub(crate) fn max_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
let mut max = ::std::f64::NAN;
let mut sec = None;
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
let ind = cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::F64(val, ref val_sec) => {
if max.is_nan() || max < val {
max = val;
sec = match *val_sec {
None => Some(Box::new(vec![Variable::f64(ind)])),
Some(ref arr) => {
let mut arr = arr.clone();
arr.push(Variable::f64(ind));
Some(arr)
}
};
}
}
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "number"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `number`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::F64(max, sec)), flow))
}
pub(crate) fn any_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
let mut any = false;
let mut sec = None;
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
let ind = cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::Bool(val, ref val_sec) => {
if val {
any = true;
sec = match *val_sec {
None => Some(Box::new(vec![Variable::f64(ind)])),
Some(ref arr) => {
let mut arr = arr.clone();
arr.push(Variable::f64(ind));
Some(arr)
}
};
break;
}
}
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "boolean"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `boolean`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::Bool(any, sec)), flow))
}
pub(crate) fn all_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
let mut all = true;
let mut sec = None;
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
let ind = cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::Bool(val, ref val_sec) => {
if !val {
all = false;
sec = match *val_sec {
None => Some(Box::new(vec![Variable::f64(ind)])),
Some(ref arr) => {
let mut arr = arr.clone();
arr.push(Variable::f64(ind));
Some(arr)
}
};
break;
}
}
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "boolean"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `boolean`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::Bool(all, sec)), flow))
}
pub(crate) fn link_for_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
use Link;
fn sub_link_for_n_expr(
res: &mut Link,
rt: &mut Runtime,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = rt.stack.len();
let prev_lc = rt.local_stack.len();
let start = start!(rt, for_n_expr);
let end = end!(rt, for_n_expr);
// Initialize counter.
rt.local_stack
.push((for_n_expr.name.clone(), rt.stack.len()));
rt.stack.push(Variable::f64(start));
let st = rt.stack.len();
let lc = rt.local_stack.len();
let mut flow = Flow::Continue;
'outer: loop {
cond!(rt, for_n_expr, st, end);
match for_n_expr.block.expressions[0] {
ast::Expression::Link(ref link) => {
// Evaluate link items directly.
'inner: for item in &link.items {
match rt.expression(item, Side::Right)? {
(Some(ref x), Flow::Continue) => match res.push(rt.resolve(x)) {
Err(err) => {
return Err(rt.module.error(
for_n_expr.source_range,
&format!("{}\n{}", rt.stack_trace(), err),
rt,
))
}
Ok(()) => {}
},
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow, 'outer),
(_, Flow::ContinueLoop(x)) => match x {
Some(label) => {
let same = if let Some(ref for_label) = for_n_expr.label {
&label == for_label
} else {
false
};
if !same {
flow = Flow::ContinueLoop(Some(label));
break 'outer;
} else {
break 'inner;
}
}
None => {
break 'inner;
}
},
}
}
}
ast::Expression::LinkFor(ref for_n) => {
// Pass on control to next link loop.
match sub_link_for_n_expr(res, rt, for_n) {
Ok((None, Flow::Continue)) => {}
Ok((_, Flow::Break(x))) => break_!(x, for_n_expr, flow, 'outer),
Ok((_, Flow::ContinueLoop(x))) => {
if let Some(label) = x {
let same = if let Some(ref for_label) = for_n_expr.label {
&label == for_label
} else {
false
};
if !same {
flow = Flow::ContinueLoop(Some(label));
break 'outer;
}
}
}
x => return x,
}
}
_ => {
panic!("Link body is not link");
}
}
inc!(rt, for_n_expr, st);
rt.stack.truncate(st);
rt.local_stack.truncate(lc);
}
rt.stack.truncate(prev_st);
rt.local_stack.truncate(prev_lc);
Ok((None, flow))
}
let mut res: Link = Link::new();
match sub_link_for_n_expr(&mut res, self, for_n_expr) {
Ok((None, Flow::Continue)) => Ok((Some(Variable::Link(Box::new(res))), Flow::Continue)),
x => x,
}
}
pub(crate) fn sift_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let mut res: Vec<Variable> = vec![];
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => res.push(x),
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected variable",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::Array(Arc::new(res))), flow))
}
pub(crate) fn sum_vec4_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let mut sum: [f32; 4] = [0.0; 4];
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::Vec4(val) => {
for i in 0..4 {
sum[i] += val[i]
}
}
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "vec4"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `vec4`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::Vec4(sum)), flow))
}
pub(crate) fn prod_vec4_n_expr(
&mut self,
for_n_expr: &ast::ForN,
) -> Result<(Option<Variable>, Flow), String> {
let prev_st = self.stack.len();
let prev_lc = self.local_stack.len();
let mut prod: [f32; 4] = [1.0; 4];
let start = start!(self, for_n_expr);
let end = end!(self, for_n_expr);
// Initialize counter.
self.local_stack
.push((for_n_expr.name.clone(), self.stack.len()));
self.stack.push(Variable::f64(start));
let st = self.stack.len();
let lc = self.local_stack.len();
let mut flow = Flow::Continue;
loop {
cond!(self, for_n_expr, st, end);
match self.block(&for_n_expr.block)? {
(Some(x), Flow::Continue) => {
match self.resolve(&x) {
&Variable::Vec4(val) => {
for i in 0..4 {
prod[i] *= val[i]
}
}
x => {
return Err(self.module.error(
for_n_expr.block.source_range,
&self.expected(x, "vec4"),
self,
))
}
};
}
(x, Flow::Return) => {
return Ok((x, Flow::Return));
}
(None, Flow::Continue) => {
return Err(self.module.error(
for_n_expr.block.source_range,
"Expected `vec4`",
self,
))
}
(_, Flow::Break(x)) => break_!(x, for_n_expr, flow),
(_, Flow::ContinueLoop(x)) => continue_!(x, for_n_expr, flow),
}
inc!(self, for_n_expr, st);
self.stack.truncate(st);
self.local_stack.truncate(lc);
}
self.stack.truncate(prev_st);
self.local_stack.truncate(prev_lc);
Ok((Some(Variable::Vec4(prod)), flow))
}
}
| 37.600246 | 100 | 0.393274 |
5da320e9ca9951fe5224ad8824f770456342eb46
| 10,297 |
use std::{
collections::{BTreeMap, HashMap, VecDeque},
sync::Arc,
time::Instant,
};
use itertools::Itertools;
use tracing::{debug, trace};
use casper_execution_engine::{
core::engine_state::{
self, step::EvictItem, DeployItem, EngineState, ExecuteRequest,
ExecutionResult as EngineExecutionResult, ExecutionResults, GetEraValidatorsRequest,
RewardItem, StepError, StepRequest, StepSuccess,
},
shared::{additive_map::AdditiveMap, newtypes::CorrelationId, transform::Transform},
storage::global_state::lmdb::LmdbGlobalState,
};
use casper_hashing::Digest;
use casper_types::{EraId, ExecutionResult, Key, ProtocolVersion, PublicKey, U512};
use crate::{
components::{
consensus::EraReport,
contract_runtime::{
error::BlockExecutionError, types::StepEffectAndUpcomingEraValidators,
BlockAndExecutionEffects, ContractRuntimeMetrics, ExecutionPreState,
},
},
types::{Block, Deploy, DeployHash, DeployHeader, FinalizedBlock},
};
/// Executes a finalized block.
pub fn execute_finalized_block(
engine_state: &EngineState<LmdbGlobalState>,
metrics: Option<Arc<ContractRuntimeMetrics>>,
protocol_version: ProtocolVersion,
execution_pre_state: ExecutionPreState,
finalized_block: FinalizedBlock,
deploys: Vec<Deploy>,
transfers: Vec<Deploy>,
) -> Result<BlockAndExecutionEffects, BlockExecutionError> {
if finalized_block.height() != execution_pre_state.next_block_height {
return Err(BlockExecutionError::WrongBlockHeight {
finalized_block: Box::new(finalized_block),
execution_pre_state: Box::new(execution_pre_state),
});
}
let ExecutionPreState {
pre_state_root_hash,
parent_hash,
parent_seed,
next_block_height: _,
} = execution_pre_state;
let mut state_root_hash = pre_state_root_hash;
let mut execution_results: HashMap<DeployHash, (DeployHeader, ExecutionResult)> =
HashMap::new();
// Run any deploys that must be executed
let block_time = finalized_block.timestamp().millis();
let start = Instant::now();
for deploy in deploys.into_iter().chain(transfers) {
let deploy_hash = *deploy.id();
let deploy_header = deploy.header().clone();
let execute_request = ExecuteRequest::new(
state_root_hash,
block_time,
vec![DeployItem::from(deploy)],
protocol_version,
finalized_block.proposer().clone(),
);
// TODO: this is currently working coincidentally because we are passing only one
// deploy_item per exec. The execution results coming back from the ee lacks the
// mapping between deploy_hash and execution result, and this outer logic is
// enriching it with the deploy hash. If we were passing multiple deploys per exec
// the relation between the deploy and the execution results would be lost.
let result = execute(engine_state, metrics.clone(), execute_request)?;
trace!(?deploy_hash, ?result, "deploy execution result");
// As for now a given state is expected to exist.
let (state_hash, execution_result) = commit_execution_effects(
engine_state,
metrics.clone(),
state_root_hash,
deploy_hash,
result,
)?;
execution_results.insert(deploy_hash, (deploy_header, execution_result));
state_root_hash = state_hash;
}
// Flush once, after all deploys have been executed.
engine_state.flush_environment()?;
if let Some(metrics) = metrics.as_ref() {
metrics.exec_block.observe(start.elapsed().as_secs_f64());
}
// If the finalized block has an era report, run the auction contract and get the upcoming era
// validators
let maybe_step_effect_and_upcoming_era_validators =
if let Some(era_report) = finalized_block.era_report() {
let StepSuccess {
post_state_hash,
execution_journal: step_execution_journal,
} = commit_step(
engine_state,
metrics.clone(),
protocol_version,
state_root_hash,
era_report,
finalized_block.timestamp().millis(),
finalized_block.era_id().successor(),
)?;
state_root_hash = post_state_hash;
let upcoming_era_validators = engine_state.get_era_validators(
CorrelationId::new(),
GetEraValidatorsRequest::new(state_root_hash, protocol_version),
)?;
Some(StepEffectAndUpcomingEraValidators {
step_execution_journal,
upcoming_era_validators,
})
} else {
None
};
// Update the metric.
let block_height = finalized_block.height();
if let Some(metrics) = metrics.as_ref() {
metrics.chain_height.set(block_height as i64);
}
let next_era_validator_weights: Option<BTreeMap<PublicKey, U512>> =
maybe_step_effect_and_upcoming_era_validators
.as_ref()
.and_then(
|StepEffectAndUpcomingEraValidators {
upcoming_era_validators,
..
}| {
upcoming_era_validators
.get(&finalized_block.era_id().successor())
.cloned()
},
);
let block = Block::new(
parent_hash,
parent_seed,
state_root_hash,
finalized_block,
next_era_validator_weights,
protocol_version,
)?;
Ok(BlockAndExecutionEffects {
block,
execution_results,
maybe_step_effect_and_upcoming_era_validators,
})
}
/// Commits the execution effects.
fn commit_execution_effects(
engine_state: &EngineState<LmdbGlobalState>,
metrics: Option<Arc<ContractRuntimeMetrics>>,
state_root_hash: Digest,
deploy_hash: DeployHash,
execution_results: ExecutionResults,
) -> Result<(Digest, ExecutionResult), BlockExecutionError> {
let ee_execution_result = execution_results
.into_iter()
.exactly_one()
.map_err(|_| BlockExecutionError::MoreThanOneExecutionResult)?;
let json_execution_result = ExecutionResult::from(&ee_execution_result);
let execution_effect: AdditiveMap<Key, Transform> = match ee_execution_result {
EngineExecutionResult::Success {
execution_journal,
cost,
..
} => {
// We do want to see the deploy hash and cost in the logs.
// We don't need to see the effects in the logs.
debug!(?deploy_hash, %cost, "execution succeeded");
execution_journal
}
EngineExecutionResult::Failure {
error,
execution_journal,
cost,
..
} => {
// Failure to execute a contract is a user error, not a system error.
// We do want to see the deploy hash, error, and cost in the logs.
// We don't need to see the effects in the logs.
debug!(?deploy_hash, ?error, %cost, "execution failure");
execution_journal
}
}
.into();
let new_state_root =
commit_transforms(engine_state, metrics, state_root_hash, execution_effect)?;
Ok((new_state_root, json_execution_result))
}
fn commit_transforms(
engine_state: &EngineState<LmdbGlobalState>,
metrics: Option<Arc<ContractRuntimeMetrics>>,
state_root_hash: Digest,
effects: AdditiveMap<Key, Transform>,
) -> Result<Digest, engine_state::Error> {
trace!(?state_root_hash, ?effects, "commit");
let correlation_id = CorrelationId::new();
let start = Instant::now();
let result = engine_state.apply_effect(correlation_id, state_root_hash, effects);
if let Some(metrics) = metrics {
metrics.apply_effect.observe(start.elapsed().as_secs_f64());
}
trace!(?result, "commit result");
result.map(Digest::from)
}
fn execute(
engine_state: &EngineState<LmdbGlobalState>,
metrics: Option<Arc<ContractRuntimeMetrics>>,
execute_request: ExecuteRequest,
) -> Result<VecDeque<EngineExecutionResult>, engine_state::Error> {
trace!(?execute_request, "execute");
let correlation_id = CorrelationId::new();
let start = Instant::now();
let result = engine_state.run_execute(correlation_id, execute_request);
if let Some(metrics) = metrics {
metrics.run_execute.observe(start.elapsed().as_secs_f64());
}
trace!(?result, "execute result");
result
}
fn commit_step(
engine_state: &EngineState<LmdbGlobalState>,
maybe_metrics: Option<Arc<ContractRuntimeMetrics>>,
protocol_version: ProtocolVersion,
pre_state_root_hash: Digest,
era_report: &EraReport<PublicKey>,
era_end_timestamp_millis: u64,
next_era_id: EraId,
) -> Result<StepSuccess, StepError> {
// Extract the rewards and the inactive validators if this is a switch block
let EraReport {
equivocators,
rewards,
inactive_validators,
} = era_report;
let reward_items = rewards
.iter()
.map(|(vid, value)| RewardItem::new(vid.clone(), *value))
.collect();
// Both inactive validators and equivocators are evicted
let evict_items = inactive_validators
.iter()
.chain(equivocators)
.cloned()
.map(EvictItem::new)
.collect();
let step_request = StepRequest {
pre_state_hash: pre_state_root_hash,
protocol_version,
reward_items,
// Note: The Casper Network does not slash, but another network could
slash_items: vec![],
evict_items,
next_era_id,
era_end_timestamp_millis,
};
// Have the EE commit the step.
let correlation_id = CorrelationId::new();
let start = Instant::now();
let result = engine_state.commit_step(correlation_id, step_request);
if let Some(metrics) = maybe_metrics {
metrics.commit_step.observe(start.elapsed().as_secs_f64());
}
trace!(?result, "step response");
result
}
| 35.506897 | 98 | 0.643586 |
03f41e71358981200ecf690769e5d47c6a80acff
| 281 |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
pub fn main() {
let x: u32 = rmc::nondet();
if x < u32::MAX >> 1 {
let y = x * 2;
assert!(y % 2 == 0);
assert!(y % 2 != 3);
}
}
| 23.416667 | 69 | 0.519573 |
e2777d3e2c271b6256582b6773435271c015173d
| 5,381 |
use embedded_hal::blocking::i2c::{Read, Write};
use heapless::{Vec, ArrayLength};
use heapless::consts::*;
use crc_all::Crc;
pub enum Command {
StartContinuousMeasurement = 0x0010,
StopContinuousMeasurement = 0x0104,
SetMeasurementInterval = 0x4600,
GetDataReadyStatus = 0x0202,
ReadMeasurement = 0x0300,
SetAutomaticSelfCalibration = 0x5306,
SetForcedRecalibrationValue = 0x5204,
SetTemperatureOffset = 0x5403,
SetAltitude = 0x5102,
ReadFirmwareVersion = 0xd100,
SoftReset = 0xd304,
}
const EXPECT_MSG: &str = "Vec was not large enough";
const ADDRESS: u8 = 0x61 << 1;
pub struct Scd30<T> {
comm: T,
address: u8,
}
#[derive(Debug)]
pub struct Measurement {
pub co2: f32,
pub humidity: f32,
pub temperature: f32,
}
/// See the [datasheet] for I²c parameters.
///
/// [datasheet]: https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/9.5_CO2/Sensirion_CO2_Sensors_SCD30_Interface_Description.pdf
impl<T, E> Scd30<T> where T: Read<Error = E> + Write<Error = E> {
fn add_argument<N>(&mut self, buf: &mut Vec<u8, N>, data: &[u8]) -> Result<(), ()> where N: ArrayLength<u8> {
buf.extend_from_slice(data)?;
let mut crc = Crc::<u8>::new(0x31, 8, 0xff, 0, false);
crc.update(data);
buf.push(crc.finish()).map_err(|_| ())
}
/// Returns an [Scd30] instance with the default address 0x61 shifted one place to the left.
/// You may or may not need this bitshift depending on the byte size of
/// your [I²c](embedded_hal::blocking::i2c) peripheral.
pub fn new(i2c: T) -> Self {
Scd30 {
comm: i2c,
address: ADDRESS
}
}
/// Returns an [Scd30] instance with the specified address.
pub fn new_with_address(i2c: T, address: u8) -> Self {
Scd30 {
comm: i2c,
address
}
}
pub fn soft_reset(&mut self) -> Result<(), E> {
self.comm.write(self.address, &(Command::SoftReset as u16).to_be_bytes())
}
pub fn stop_measuring(&mut self) -> Result<(), E> {
self.comm.write(self.address, &(Command::StopContinuousMeasurement as u16).to_be_bytes())
}
/// Enable or disable automatic self calibration (ASC).
///
/// According to the datasheet, the sensor should be active continously for at least
/// 7 days to find the initial parameter for ASC. The sensor has to be exposed to
/// at least 1 hour of fresh air (~400ppm CO₂) per day.
pub fn set_automatic_calibration(&mut self, enable: bool) -> Result<(), E> {
let mut vec: Vec<u8, U5> = Vec::new();
vec.extend_from_slice(&(Command::SetAutomaticSelfCalibration as u16).to_be_bytes()).expect(EXPECT_MSG);
self.add_argument(&mut vec, &(enable as u16).to_be_bytes()).expect(EXPECT_MSG);
self.comm.write(self.address, &vec)
}
pub fn set_forced_recalibration_value(&mut self, co2: u16) -> Result<(), E> {
let mut vec: Vec<u8, U5> = Vec::new();
vec.extend_from_slice(&(Command::SetForcedRecalibrationValue as u16).to_be_bytes()).expect(EXPECT_MSG);
self.add_argument(&mut vec, &co2.to_be_bytes()).expect(EXPECT_MSG);
self.comm.write(self.address, &vec)
}
/// Start measuring without mbar compensation.
pub fn start_measuring(&mut self) -> Result<(), E> {
self.start_measuring_with_mbar(0)
}
pub fn set_measurement_interval(&mut self, seconds: u16) -> Result<(), E> {
let mut vec: Vec<u8, U5> = Vec::new();
vec.extend_from_slice(&(Command::SetMeasurementInterval as u16).to_be_bytes()).expect(EXPECT_MSG);
self.add_argument(&mut vec, &seconds.to_be_bytes()).expect(EXPECT_MSG);
self.comm.write(self.address, &vec)
}
/// Start measuring with mbar (pressure) compensation.
pub fn start_measuring_with_mbar(&mut self, pressure: u16) -> Result<(), E> {
let mut vec: Vec<u8, U5> = Vec::new();
vec.extend_from_slice(&(Command::StartContinuousMeasurement as u16).to_be_bytes()).expect(EXPECT_MSG);
self.add_argument(&mut vec, &pressure.to_be_bytes()).expect(EXPECT_MSG);
self.comm.write(self.address, &vec)
}
pub fn data_ready(&mut self) -> Result<bool, E> {
let mut buf = [0u8; 2];
self.comm.write(self.address, &(Command::GetDataReadyStatus as u16).to_be_bytes())?;
self.comm.read(self.address, &mut buf)?;
Ok(u16::from_be_bytes(buf) == 1)
}
pub fn read(&mut self) -> Result<Option<Measurement>, E> {
match self.data_ready() {
Ok(true) => {
let mut buf = [0u8; 6 * 3];
self.comm.write(self.address, &(Command::ReadMeasurement as u16).to_be_bytes())?;
self.comm.read(self.address, &mut buf)?;
Ok(Some(Measurement {
co2: f32::from_bits(u32::from_be_bytes([ buf[0], buf[1], buf[3], buf[4] ])),
temperature: f32::from_bits(u32::from_be_bytes([ buf[6], buf[7], buf[9], buf[10] ])),
humidity: f32::from_bits(u32::from_be_bytes([ buf[12], buf[13], buf[15], buf[16] ])),
}))
},
Ok(false) => Ok(None),
Err(e) => Err(e),
}
}
}
| 38.71223 | 156 | 0.606207 |
8f7361be1b0f2118f9af7e583ed359130f198c33
| 6,966 |
//! # Lexical Environment
//!
//! <https://tc39.es/ecma262/#sec-lexical-environment-operations>
//!
//! The following operations are used to operate upon lexical environments
//! This is the entrypoint to lexical environments.
use super::global_environment_record::GlobalEnvironmentRecord;
use crate::{
environment::environment_record_trait::EnvironmentRecordTrait, object::JsObject, BoaProfiler,
Context, JsResult, JsValue,
};
use gc::Gc;
use std::{collections::VecDeque, error, fmt};
/// Environments are wrapped in a Box and then in a GC wrapper
pub type Environment = Gc<Box<dyn EnvironmentRecordTrait>>;
/// Give each environment an easy way to declare its own type
/// This helps with comparisons
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EnvironmentType {
Declarative,
Function,
Global,
Object,
}
/// The scope of a given variable
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VariableScope {
/// The variable declaration is scoped to the current block (`let` and `const`)
Block,
/// The variable declaration is scoped to the current function (`var`)
Function,
}
#[derive(Debug, Clone)]
pub struct LexicalEnvironment {
environment_stack: VecDeque<Environment>,
}
/// An error that occurred during lexing or compiling of the source input.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EnvironmentError {
details: String,
}
impl EnvironmentError {
pub fn new(msg: &str) -> Self {
Self {
details: msg.to_string(),
}
}
}
impl fmt::Display for EnvironmentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.details)
}
}
impl error::Error for EnvironmentError {}
impl LexicalEnvironment {
pub fn new(global: JsObject) -> Self {
let _timer = BoaProfiler::global().start_event("LexicalEnvironment::new", "env");
let global_env = GlobalEnvironmentRecord::new(global.clone(), global);
let mut lexical_env = Self {
environment_stack: VecDeque::new(),
};
// lexical_env.push(global_env);
lexical_env.environment_stack.push_back(global_env.into());
lexical_env
}
}
impl Context {
pub(crate) fn push_environment<T: Into<Environment>>(&mut self, env: T) {
self.realm
.environment
.environment_stack
.push_back(env.into());
}
pub(crate) fn pop_environment(&mut self) -> Option<Environment> {
self.realm.environment.environment_stack.pop_back()
}
pub(crate) fn get_this_binding(&mut self) -> JsResult<JsValue> {
self.get_current_environment()
.recursive_get_this_binding(self)
}
pub(crate) fn get_global_this_binding(&mut self) -> JsResult<JsValue> {
let global = self.realm.global_env.clone();
global.get_this_binding(self)
}
pub(crate) fn create_mutable_binding(
&mut self,
name: &str,
deletion: bool,
scope: VariableScope,
) -> JsResult<()> {
self.get_current_environment()
.recursive_create_mutable_binding(name, deletion, scope, self)
}
pub(crate) fn create_immutable_binding(
&mut self,
name: &str,
deletion: bool,
scope: VariableScope,
) -> JsResult<()> {
self.get_current_environment()
.recursive_create_immutable_binding(name, deletion, scope, self)
}
pub(crate) fn set_mutable_binding(
&mut self,
name: &str,
value: JsValue,
strict: bool,
) -> JsResult<()> {
self.get_current_environment()
.recursive_set_mutable_binding(name, value, strict, self)
}
pub(crate) fn initialize_binding(&mut self, name: &str, value: JsValue) -> JsResult<()> {
let _timer =
BoaProfiler::global().start_event("LexicalEnvironment::initialize_binding", "env");
self.get_current_environment()
.recursive_initialize_binding(name, value, self)
}
/// When neededing to clone an environment (linking it with another environnment)
/// cloning is more suited. The GC will remove the env once nothing is linking to it anymore
pub(crate) fn get_current_environment(&mut self) -> Environment {
let _timer =
BoaProfiler::global().start_event("LexicalEnvironment::get_current_environment", "env");
self.realm
.environment
.environment_stack
.back_mut()
.expect("Could not get mutable reference to back object")
.clone()
}
pub(crate) fn has_binding(&mut self, name: &str) -> JsResult<bool> {
let _timer = BoaProfiler::global().start_event("LexicalEnvironment::has_binding", "env");
self.get_current_environment()
.recursive_has_binding(name, self)
}
pub(crate) fn get_binding_value(&mut self, name: &str) -> JsResult<JsValue> {
let _timer =
BoaProfiler::global().start_event("LexicalEnvironment::get_binding_value", "env");
self.get_current_environment()
.recursive_get_binding_value(name, self)
}
}
#[cfg(test)]
mod tests {
use crate::exec;
#[test]
fn let_is_blockscoped() {
let scenario = r#"
{
let bar = "bar";
}
try{
bar;
} catch (err) {
err.message
}
"#;
assert_eq!(&exec(scenario), "\"bar is not defined\"");
}
#[test]
fn const_is_blockscoped() {
let scenario = r#"
{
const bar = "bar";
}
try{
bar;
} catch (err) {
err.message
}
"#;
assert_eq!(&exec(scenario), "\"bar is not defined\"");
}
#[test]
fn var_not_blockscoped() {
let scenario = r#"
{
var bar = "bar";
}
bar == "bar";
"#;
assert_eq!(&exec(scenario), "true");
}
#[test]
fn functions_use_declaration_scope() {
let scenario = r#"
function foo() {
try {
bar;
} catch (err) {
return err.message;
}
}
{
let bar = "bar";
foo();
}
"#;
assert_eq!(&exec(scenario), "\"bar is not defined\"");
}
#[test]
fn set_outer_var_in_blockscope() {
let scenario = r#"
var bar;
{
bar = "foo";
}
bar == "foo";
"#;
assert_eq!(&exec(scenario), "true");
}
#[test]
fn set_outer_let_in_blockscope() {
let scenario = r#"
let bar;
{
bar = "foo";
}
bar == "foo";
"#;
assert_eq!(&exec(scenario), "true");
}
}
| 26.792308 | 100 | 0.579098 |
56ec0c7e4754a66362629fa7e332062ac1567023
| 3,471 |
mod fpkm;
mod method;
mod tpm;
mod writer;
pub use self::{fpkm::calculate_fpkms, method::Method, tpm::calculate_tpms, writer::Writer};
use std::{collections::HashMap, error, fmt};
use crate::Feature;
type FeatureMap = HashMap<String, Vec<Feature>>;
#[derive(Debug)]
pub enum Error {
MissingFeature(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingFeature(name) => write!(f, "missing feature: {}", name),
}
}
}
impl error::Error for Error {}
fn sum_nonoverlapping_feature_lengths(features: &[Feature]) -> u64 {
merge_features(features).iter().map(|f| f.len()).sum()
}
/// Merges a list of overlapping features into a list of non-overlapping intervals.
///
/// The intervals are assumed to be inclusive.
///
/// # Panics
///
/// Panics when the input list of features is empty.
///
/// # Example
///
/// Given the list of intervals [2, 5], [3, 4], [5, 7], [9, 12], [10, 15], and
/// [16, 21], the following overlap and are combined into single features.
///
/// * [2, 5], [3, 4], [5, 7] => [2, 7]
/// * [9, 12], [10, 15] => [9, 15]
/// * [16, 21] => [16, 21]
fn merge_features(features: &[Feature]) -> Vec<Feature> {
assert!(!features.is_empty());
let mut features = features.to_vec();
features.sort_unstable_by_key(|i| i.start());
let mut merged_features = Vec::with_capacity(features.len());
merged_features.push(features[0].clone());
for b in features {
let a = merged_features.last_mut().expect("list cannot be empty");
if b.start() > a.end() {
merged_features.push(b);
continue;
}
if a.end() < b.end() {
*a.end_mut() = b.end();
}
}
merged_features
}
#[cfg(test)]
mod tests {
use crate::Feature;
use noodles::gff;
use super::*;
#[test]
fn test_sum_nonoverlapping_feature_lengths() {
let reference_name = String::from("chr1");
let strand = gff::record::Strand::Forward;
let features = [
Feature::new(reference_name.clone(), 2, 5, strand),
Feature::new(reference_name.clone(), 3, 4, strand),
Feature::new(reference_name.clone(), 5, 7, strand),
Feature::new(reference_name.clone(), 9, 12, strand),
Feature::new(reference_name.clone(), 10, 15, strand),
Feature::new(reference_name, 16, 21, strand),
];
let len = sum_nonoverlapping_feature_lengths(&features);
assert_eq!(len, 19);
}
#[test]
fn test_merge_features() {
let reference_name = String::from("chr1");
let strand = gff::record::Strand::Forward;
let features = [
Feature::new(reference_name.clone(), 2, 5, strand),
Feature::new(reference_name.clone(), 3, 4, strand),
Feature::new(reference_name.clone(), 5, 7, strand),
Feature::new(reference_name.clone(), 9, 12, strand),
Feature::new(reference_name.clone(), 10, 15, strand),
Feature::new(reference_name.clone(), 16, 21, strand),
];
let actual = merge_features(&features);
let expected = [
Feature::new(reference_name.clone(), 2, 7, strand),
Feature::new(reference_name.clone(), 9, 15, strand),
Feature::new(reference_name, 16, 21, strand),
];
assert_eq!(actual, expected);
}
}
| 27.991935 | 91 | 0.583693 |
084e4f4c11b413fd7c7a713c7dcf2171396fb9f6
| 1,987 |
// 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::fmt;
use common_datavalues::columns::DataColumn;
use common_datavalues::prelude::DataColumnsWithField;
use common_datavalues::DataField;
use common_datavalues::DataType;
use common_exception::Result;
use crate::scalars::function_factory::FunctionDescription;
use crate::scalars::function_factory::FunctionFeatures;
use crate::scalars::Function;
#[derive(Clone)]
pub struct CrashMeFunction {
_display_name: String,
}
impl CrashMeFunction {
pub fn try_create(display_name: &str) -> Result<Box<dyn Function>> {
Ok(Box::new(CrashMeFunction {
_display_name: display_name.to_string(),
}))
}
pub fn desc() -> FunctionDescription {
FunctionDescription::creator(Box::new(Self::try_create))
.features(FunctionFeatures::default().num_arguments(1))
}
}
impl Function for CrashMeFunction {
fn name(&self) -> &str {
"CrashMeFunction"
}
fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
Ok(DataType::Null)
}
fn nullable(&self, _arg_fields: &[DataField]) -> Result<bool> {
Ok(false)
}
fn eval(&self, _columns: &DataColumnsWithField, _input_rows: usize) -> Result<DataColumn> {
panic!("crash me function");
}
}
impl fmt::Display for CrashMeFunction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "crashme")
}
}
| 29.220588 | 95 | 0.689985 |
fb995e0dd652d42d9e1f1dee67ef6b2016f0caa2
| 8,844 |
use ic_interfaces::execution_environment::{
HypervisorError::{self},
HypervisorResult, SystemApi,
};
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::PageIndex;
use ic_sys::PageBytes;
use ic_types::{Cycles, NumBytes, NumInstructions, Time};
const MESSAGE_UNIMPLEMENTED: &str =
"Empty System API should not be called. Only used by the embedder to create an ExecutionState instance";
/// This struct implements the SystemApi trait
/// and is only used by the `embedder` to create an `ExecutionState` instance.
pub struct SystemApiEmpty;
impl SystemApi for SystemApiEmpty {
fn set_execution_error(&mut self, _error: HypervisorError) {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn get_execution_error(&self) -> Option<&HypervisorError> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn get_num_instructions_from_bytes(&self, _num_bytes: NumBytes) -> NumInstructions {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn stable_memory_dirty_pages(&self) -> Vec<(PageIndex, &PageBytes)> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn stable_memory_size(&self) -> usize {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn subnet_type(&self) -> SubnetType {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_caller_copy(&self, _: u32, _: u32, _: u32, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_caller_size(&self) -> HypervisorResult<u32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_arg_data_size(&self) -> HypervisorResult<u32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_arg_data_copy(&self, _: u32, _: u32, _: u32, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_method_name_size(&self) -> HypervisorResult<u32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_method_name_copy(
&self,
_: u32,
_: u32,
_: u32,
_: &mut [u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_accept_message(&mut self) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_reply_data_append(&mut self, _: u32, _: u32, _: &[u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_reply(&mut self) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_reject_code(&self) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_reject(&mut self, _: u32, _: u32, _: &[u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_reject_msg_size(&self) -> HypervisorResult<u32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_reject_msg_copy(
&self,
_: u32,
_: u32,
_: u32,
_: &mut [u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_canister_self_size(&self) -> HypervisorResult<usize> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_canister_self_copy(
&mut self,
_: u32,
_: u32,
_: u32,
_: &mut [u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_controller_size(&self) -> HypervisorResult<usize> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_controller_copy(
&mut self,
_: u32,
_: u32,
_: u32,
_: &mut [u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_debug_print(&self, _: u32, _: u32, _: &[u8]) {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_trap(&self, _: u32, _: u32, _: &[u8]) -> HypervisorError {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_simple(
&mut self,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: &[u8],
) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_new(
&mut self,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: u32,
_: &[u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_data_append(&mut self, _: u32, _: u32, _: &[u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_on_cleanup(&mut self, _: u32, _: u32) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_cycles_add(&mut self, _: u64) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_cycles_add128(&mut self, _: Cycles) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_call_perform(&mut self) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable_size(&self) -> HypervisorResult<u32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable_grow(&mut self, _: u32) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable_read(&self, _: u32, _: u32, _: u32, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable_write(&mut self, _: u32, _: u32, _: u32, _: &[u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable64_size(&self) -> HypervisorResult<u64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable64_grow(&mut self, _: u64) -> HypervisorResult<i64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable64_read(&self, _: u64, _: u64, _: u64, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_stable64_write(&mut self, _: u64, _: u64, _: u64, _: &[u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_time(&self) -> HypervisorResult<Time> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn out_of_instructions(&self) -> HypervisorError {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn update_available_memory(&mut self, _: i32, _: u32) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_canister_cycle_balance(&self) -> HypervisorResult<u64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_canister_cycles_balance128(&self, _: u32, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_cycles_available(&self) -> HypervisorResult<u64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_cycles_available128(&self, _: u32, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_cycles_refunded(&self) -> HypervisorResult<u64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_cycles_refunded128(&self, _: u32, _: &mut [u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_cycles_accept(&mut self, _: u64) -> HypervisorResult<u64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_msg_cycles_accept128(
&mut self,
_: Cycles,
_: u32,
_: &mut [u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_certified_data_set(&mut self, _: u32, _: u32, _: &[u8]) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_data_certificate_present(&self) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_data_certificate_size(&self) -> HypervisorResult<i32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_data_certificate_copy(
&self,
_: u32,
_: u32,
_: u32,
_: &mut [u8],
) -> HypervisorResult<()> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_canister_status(&self) -> HypervisorResult<u32> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
fn ic0_mint_cycles(&mut self, _: u64) -> HypervisorResult<u64> {
unimplemented!("{}", MESSAGE_UNIMPLEMENTED)
}
}
| 35.518072 | 108 | 0.605834 |
871e721aada789efb0a03dee2f56e5a0936883d4
| 72,981 |
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module translates the bytecode of a module to Boogie code.
use std::collections::{BTreeMap, BTreeSet};
use itertools::Itertools;
#[allow(unused_imports)]
use log::{debug, info, log, warn, Level};
use move_model::{
code_writer::CodeWriter,
emit, emitln,
model::{GlobalEnv, QualifiedInstId, StructEnv, StructId},
pragmas::{ADDITION_OVERFLOW_UNCHECKED_PRAGMA, SEED_PRAGMA, TIMEOUT_PRAGMA},
ty::{PrimitiveType, Type},
};
use move_stackless_bytecode::{
function_target::FunctionTarget,
function_target_pipeline::{FunctionTargetsHolder, VerificationFlavor},
mono_analysis,
stackless_bytecode::{BorrowEdge, BorrowNode, Bytecode, Constant, HavocKind, Operation},
};
use crate::{
boogie_helpers::{
boogie_byte_blob, boogie_debug_track_abort, boogie_debug_track_local,
boogie_debug_track_return, boogie_equality_for_type, boogie_field_sel, boogie_field_update,
boogie_function_name, boogie_make_vec_from_strings, boogie_modifies_memory_name,
boogie_resource_memory_name, boogie_struct_name, boogie_temp, boogie_type,
boogie_type_param, boogie_type_suffix, boogie_type_suffix_for_struct,
boogie_well_formed_check, boogie_well_formed_expr,
},
options::BoogieOptions,
spec_translator::SpecTranslator,
};
use codespan::LineIndex;
use move_model::{
ast::{TempIndex, TraceKind},
model::{Loc, NodeId},
ty::{TypeDisplayContext, BOOL_TYPE},
};
use move_stackless_bytecode::{
function_target_pipeline::FunctionVariant,
stackless_bytecode::{AbortAction, PropKind},
};
pub struct BoogieTranslator<'env> {
env: &'env GlobalEnv,
options: &'env BoogieOptions,
writer: &'env CodeWriter,
spec_translator: SpecTranslator<'env>,
targets: &'env FunctionTargetsHolder,
}
pub struct FunctionTranslator<'env> {
parent: &'env BoogieTranslator<'env>,
fun_target: &'env FunctionTarget<'env>,
type_inst: &'env [Type],
}
pub struct StructTranslator<'env> {
parent: &'env BoogieTranslator<'env>,
struct_env: &'env StructEnv<'env>,
type_inst: &'env [Type],
}
impl<'env> BoogieTranslator<'env> {
pub fn new(
env: &'env GlobalEnv,
options: &'env BoogieOptions,
targets: &'env FunctionTargetsHolder,
writer: &'env CodeWriter,
) -> Self {
Self {
env,
options,
targets,
writer,
spec_translator: SpecTranslator::new(writer, env, options),
}
}
pub fn translate(&mut self) {
let writer = self.writer;
let env = self.env;
let spec_translator = &self.spec_translator;
let mono_info = mono_analysis::get_info(self.env);
let empty = &BTreeSet::new();
emitln!(
writer,
"\n\n//==================================\n// Begin Translation\n"
);
// Add given type declarations for type parameters.
emitln!(writer, "\n\n// Given Types for Type Parameters\n");
for idx in &mono_info.type_params {
let param_type = boogie_type_param(env, *idx);
let suffix = boogie_type_suffix(env, &Type::TypeParameter(*idx));
emitln!(writer, "type {};", param_type);
emitln!(
writer,
"function {{:inline}} $IsEqual'{}'(x1: {}, x2: {}): bool {{ x1 == x2 }}",
suffix,
param_type,
param_type
);
emitln!(
writer,
"function {{:inline}} $IsValid'{}'(x: {}): bool {{ true }}",
suffix,
param_type,
);
}
emitln!(writer);
self.spec_translator
.translate_axioms(env, mono_info.as_ref());
let mut translated_types = BTreeSet::new();
let mut translated_funs = BTreeSet::new();
let mut verified_functions_count = 0;
info!("generating verification conditions");
for module_env in self.env.get_modules() {
self.writer.set_location(&module_env.env.internal_loc());
spec_translator.translate_spec_vars(&module_env, mono_info.as_ref());
spec_translator.translate_spec_funs(&module_env, mono_info.as_ref());
for ref struct_env in module_env.get_structs() {
if struct_env.is_native_or_intrinsic() {
continue;
}
for type_inst in mono_info
.structs
.get(&struct_env.get_qualified_id())
.unwrap_or(empty)
{
let struct_name = boogie_struct_name(struct_env, type_inst);
if !translated_types.insert(struct_name) {
continue;
}
StructTranslator {
parent: self,
struct_env,
type_inst: type_inst.as_slice(),
}
.translate();
}
}
for ref fun_env in module_env.get_functions() {
if fun_env.is_native_or_intrinsic() {
continue;
}
for (variant, ref fun_target) in self.targets.get_targets(fun_env) {
if variant.is_verified() {
verified_functions_count += 1;
// Always produce a verified functions with an empty instantiation such that
// there is at least one top-level entry points for a VC.
FunctionTranslator {
parent: self,
fun_target,
type_inst: &[],
}
.translate();
// There maybe more verification targets that needs to be produced as we
// defer the instantiation of verified functions to this stage
for type_inst in mono_info
.funs
.get(&(fun_target.func_env.get_qualified_id(), variant))
.unwrap_or(empty)
{
// Skip the none instantiation (i.e., each type parameter is
// instantiated to itself as a concrete type). This has the same
// effect as `type_inst: &[]` and is already captured above.
let is_none_inst = type_inst.iter().enumerate().all(
|(i, t)| matches!(t, Type::TypeParameter(idx) if *idx == i as u16),
);
if is_none_inst {
continue;
}
verified_functions_count += 1;
FunctionTranslator {
parent: self,
fun_target,
type_inst,
}
.translate();
}
} else {
// This variant is inlined, so translate for all type instantiations.
for type_inst in mono_info
.funs
.get(&(
fun_target.func_env.get_qualified_id(),
FunctionVariant::Baseline,
))
.unwrap_or(empty)
{
let fun_name = boogie_function_name(fun_env, type_inst);
if !translated_funs.insert(fun_name) {
continue;
}
FunctionTranslator {
parent: self,
fun_target,
type_inst,
}
.translate();
}
}
}
}
}
// Emit any finalization items required by spec translation.
self.spec_translator.finalize();
info!("{} verification conditions", verified_functions_count);
}
}
// =================================================================================================
// Struct Translation
impl<'env> StructTranslator<'env> {
fn inst(&self, ty: &Type) -> Type {
ty.instantiate(self.type_inst)
}
/// Translates the given struct.
fn translate(&self) {
let writer = self.parent.writer;
let struct_env = self.struct_env;
let env = struct_env.module_env.env;
let qid = struct_env
.get_qualified_id()
.instantiate(self.type_inst.to_owned());
emitln!(
writer,
"// struct {} {}",
env.display(&qid),
struct_env.get_loc().display(env)
);
// Set the location to internal as default.
writer.set_location(&env.internal_loc());
// Emit data type
let struct_name = boogie_struct_name(struct_env, self.type_inst);
emitln!(writer, "type {{:datatype}} {};", struct_name);
// Emit constructor
let fields = struct_env
.get_fields()
.map(|field| {
format!(
"${}: {}",
field.get_name().display(env.symbol_pool()),
boogie_type(env, &self.inst(&field.get_type()))
)
})
.join(", ");
emitln!(
writer,
"function {{:constructor}} {}({}): {};",
struct_name,
fields,
struct_name
);
let suffix = boogie_type_suffix_for_struct(struct_env, self.type_inst);
// Emit $UpdateField functions.
let fields = struct_env.get_fields().collect_vec();
for (pos, field_env) in fields.iter().enumerate() {
let field_name = field_env.get_name().display(env.symbol_pool()).to_string();
self.emit_function(
&format!(
"$Update'{}'_{}(s: {}, x: {}): {}",
suffix,
field_name,
struct_name,
boogie_type(env, &self.inst(&field_env.get_type())),
struct_name
),
|| {
let args = fields
.iter()
.enumerate()
.map(|(p, f)| {
if p == pos {
"x".to_string()
} else {
format!("{}(s)", boogie_field_sel(f, self.type_inst))
}
})
.join(", ");
emitln!(writer, "{}({})", struct_name, args);
},
);
}
// Emit $IsValid function.
self.emit_function_with_attr(
"", // not inlined!
&format!("$IsValid'{}'(s: {}): bool", suffix, struct_name),
|| {
if struct_env.is_native_or_intrinsic() {
emitln!(writer, "true")
} else {
let mut sep = "";
for field in struct_env.get_fields() {
let sel = format!("{}({})", boogie_field_sel(&field, self.type_inst), "s");
let ty = &field.get_type().instantiate(self.type_inst);
emitln!(writer, "{}{}", sep, boogie_well_formed_expr(env, &sel, ty));
sep = " && ";
}
}
},
);
// Emit equality
self.emit_function(
&format!(
"$IsEqual'{}'(s1: {}, s2: {}): bool",
suffix, struct_name, struct_name
),
|| {
if struct_has_native_equality(struct_env, self.type_inst, self.parent.options) {
emitln!(writer, "s1 == s2")
} else {
let mut sep = "";
for field in &fields {
let sel_fun = boogie_field_sel(field, self.type_inst);
let field_suffix = boogie_type_suffix(env, &self.inst(&field.get_type()));
emit!(
writer,
"{}$IsEqual'{}'({}(s1), {}(s2))",
sep,
field_suffix,
sel_fun,
sel_fun,
);
sep = "\n&& ";
}
}
},
);
if struct_env.has_memory() {
// Emit memory variable.
let memory_name = boogie_resource_memory_name(
env,
&struct_env
.get_qualified_id()
.instantiate(self.type_inst.to_owned()),
&None,
);
emitln!(writer, "var {}: $Memory {};", memory_name, struct_name);
}
emitln!(writer);
}
fn emit_function(&self, signature: &str, body_fn: impl Fn()) {
self.emit_function_with_attr("{:inline} ", signature, body_fn)
}
fn emit_function_with_attr(&self, attr: &str, signature: &str, body_fn: impl Fn()) {
let writer = self.parent.writer;
emitln!(writer, "function {}{} {{", attr, signature);
writer.indent();
body_fn();
writer.unindent();
emitln!(writer, "}");
}
}
// =================================================================================================
// Function Translation
impl<'env> FunctionTranslator<'env> {
fn inst(&self, ty: &Type) -> Type {
ty.instantiate(self.type_inst)
}
fn inst_slice(&self, tys: &[Type]) -> Vec<Type> {
tys.iter().map(|ty| self.inst(ty)).collect()
}
fn get_local_type(&self, idx: TempIndex) -> Type {
self.fun_target
.get_local_type(idx)
.instantiate(self.type_inst)
}
/// Translates the given function.
fn translate(self) {
let writer = self.parent.writer;
let fun_target = self.fun_target;
let env = fun_target.global_env();
let qid = fun_target
.func_env
.get_qualified_id()
.instantiate(self.type_inst.to_owned());
emitln!(
writer,
"// fun {} [{}] {}",
env.display(&qid),
fun_target.data.variant,
fun_target.get_loc().display(env)
);
self.generate_function_sig();
self.generate_function_body();
emitln!(self.parent.writer);
}
/// Return a string for a boogie procedure header. Use inline attribute and name
/// suffix as indicated by `entry_point`.
fn generate_function_sig(&self) {
let writer = self.parent.writer;
let options = self.parent.options;
let fun_target = self.fun_target;
let (args, rets) = self.generate_function_args_and_returns();
let (suffix, attribs) = match &fun_target.data.variant {
FunctionVariant::Baseline => ("".to_string(), "{:inline 1} ".to_string()),
FunctionVariant::Verification(flavor) => {
let timeout = fun_target
.func_env
.get_num_pragma(TIMEOUT_PRAGMA, || options.vc_timeout);
let mut attribs = vec![format!("{{:timeLimit {}}} ", timeout)];
if fun_target.func_env.is_num_pragma_set(SEED_PRAGMA) {
let seed = fun_target
.func_env
.get_num_pragma(SEED_PRAGMA, || options.random_seed);
attribs.push(format!("{{:random_seed {}}} ", seed));
};
let suffix = match flavor {
VerificationFlavor::Regular => "$verify".to_string(),
VerificationFlavor::Instantiated(_) => {
format!("$verify_{}", flavor)
}
VerificationFlavor::Inconsistency(_) => {
attribs.push(format!(
"{{:msg_if_verifies \"inconsistency_detected{}\"}} ",
self.loc_str(&fun_target.get_loc())
));
format!("$verify_{}", flavor)
}
};
(suffix, attribs.join(""))
}
};
writer.set_location(&fun_target.get_loc());
emitln!(
writer,
"procedure {}{}{}({}) returns ({})",
attribs,
boogie_function_name(fun_target.func_env, self.type_inst),
suffix,
args,
rets,
)
}
/// Generate boogie representation of function args and return args.
fn generate_function_args_and_returns(&self) -> (String, String) {
let fun_target = self.fun_target;
let env = fun_target.global_env();
let args = (0..fun_target.get_parameter_count())
.map(|i| {
let ty = self.get_local_type(i);
// Boogie does not allow to assign to parameters, so we need to proxy them.
let prefix = if self.parameter_needs_to_be_mutable(fun_target, i) {
"_$"
} else {
"$"
};
format!("{}t{}: {}", prefix, i, boogie_type(env, &ty))
})
.join(", ");
let mut_ref_inputs = (0..fun_target.get_parameter_count())
.filter_map(|idx| {
let ty = self.get_local_type(idx);
if ty.is_mutable_reference() {
Some(ty)
} else {
None
}
})
.collect_vec();
let rets = fun_target
.get_return_types()
.iter()
.enumerate()
.map(|(i, s)| {
let s = self.inst(s);
format!("$ret{}: {}", i, boogie_type(env, &s))
})
// Add implicit return parameters for &mut
.chain(mut_ref_inputs.into_iter().enumerate().map(|(i, ty)| {
format!(
"$ret{}: {}",
usize::saturating_add(fun_target.get_return_count(), i),
boogie_type(env, &ty)
)
}))
.join(", ");
(args, rets)
}
/// Generates boogie implementation body.
fn generate_function_body(&self) {
let writer = self.parent.writer;
let fun_target = self.fun_target;
let variant = &fun_target.data.variant;
let instantiation = &fun_target.data.type_args;
let env = fun_target.global_env();
// Be sure to set back location to the whole function definition as a default.
writer.set_location(&fun_target.get_loc().at_start());
emitln!(writer, "{");
writer.indent();
// Print instantiation information
if !instantiation.is_empty() {
let display_ctxt = TypeDisplayContext::WithEnv {
env,
type_param_names: None,
};
emitln!(
writer,
"// function instantiation <{}>",
instantiation
.iter()
.map(|ty| ty.display(&display_ctxt))
.join(", ")
);
emitln!(writer, "");
}
// Generate local variable declarations. They need to appear first in boogie.
emitln!(writer, "// declare local variables");
let num_args = fun_target.get_parameter_count();
for i in num_args..fun_target.get_local_count() {
let local_type = &self.get_local_type(i);
emitln!(writer, "var $t{}: {};", i, boogie_type(env, local_type));
}
// Generate declarations for renamed parameters.
let proxied_parameters = self.get_mutable_parameters();
for (idx, ty) in &proxied_parameters {
emitln!(
writer,
"var $t{}: {};",
idx,
boogie_type(env, &ty.instantiate(self.type_inst))
);
}
// Generate declarations for modifies condition.
let mut mem_inst_seen = BTreeSet::new();
for qid in fun_target.get_modify_ids() {
let memory = qid.instantiate(self.type_inst);
if !mem_inst_seen.contains(&memory) {
emitln!(
writer,
"var {}: {}",
boogie_modifies_memory_name(fun_target.global_env(), &memory),
"[int]bool;"
);
mem_inst_seen.insert(memory);
}
}
// Declare temporaries for debug tracing and other purposes.
for (_, (ref ty, cnt)) in self.compute_needed_temps() {
for i in 0..cnt {
emitln!(
writer,
"var {}: {};",
boogie_temp(env, ty, i),
boogie_type(env, ty)
);
}
}
// Generate memory snapshot variable declarations.
let code = fun_target.get_bytecode();
let labels = code
.iter()
.filter_map(|bc| {
use Bytecode::*;
match bc {
SaveMem(_, lab, mem) => Some((lab, mem)),
SaveSpecVar(..) => panic!("spec var memory snapshots NYI"),
_ => None,
}
})
.collect::<BTreeSet<_>>();
for (lab, mem) in labels {
let mem = &mem.to_owned().instantiate(self.type_inst);
let name = boogie_resource_memory_name(env, mem, &Some(*lab));
emitln!(
writer,
"var {}: $Memory {};",
name,
boogie_struct_name(&env.get_struct_qid(mem.to_qualified_id()), &mem.inst)
);
}
// Initialize renamed parameters.
for (idx, _) in proxied_parameters {
emitln!(writer, "$t{} := _$t{};", idx, idx);
}
// Initialize mutations to have empty paths so $IsParentMutation works correctly.
for i in num_args..fun_target.get_local_count() {
if self.get_local_type(i).is_mutable_reference() {
emitln!(writer, "assume IsEmptyVec(p#$Mutation($t{}));", i);
}
}
// Initial assumptions
if variant.is_verified() {
self.translate_verify_entry_assumptions(fun_target);
}
// Generate bytecode
emitln!(writer, "\n// bytecode translation starts here");
let mut last_tracked_loc = None;
for bytecode in code.iter() {
self.translate_bytecode(&mut last_tracked_loc, bytecode);
}
writer.unindent();
emitln!(writer, "}");
}
fn get_mutable_parameters(&self) -> Vec<(TempIndex, Type)> {
let fun_target = self.fun_target;
(0..fun_target.get_parameter_count())
.filter_map(|i| {
if self.parameter_needs_to_be_mutable(fun_target, i) {
Some((i, fun_target.get_local_type(i).clone()))
} else {
None
}
})
.collect_vec()
}
/// Determines whether the parameter of a function needs to be mutable.
/// Boogie does not allow to assign to procedure parameters. In some cases
/// (e.g. for memory instrumentation, but also as a result of copy propagation),
/// we may need to assign to parameters.
fn parameter_needs_to_be_mutable(
&self,
_fun_target: &FunctionTarget<'_>,
_idx: TempIndex,
) -> bool {
// For now, we just always say true. This could be optimized because the actual (known
// so far) sources for mutability are parameters which are used in WriteBack(LocalRoot(p))
// position.
true
}
fn translate_verify_entry_assumptions(&self, fun_target: &FunctionTarget<'_>) {
let writer = self.parent.writer;
emitln!(writer, "\n// verification entrypoint assumptions");
// Prelude initialization
emitln!(writer, "call $InitVerification();");
// Assume reference parameters to be based on the Param(i) Location, ensuring
// they are disjoint from all other references. This prevents aliasing and is justified as
// follows:
// - for mutual references, by their exclusive access in Move.
// - for immutable references because we have eliminated them
for i in 0..fun_target.get_parameter_count() {
let ty = fun_target.get_local_type(i);
if ty.is_reference() {
emitln!(writer, "assume l#$Mutation($t{}) == $Param({});", i, i);
}
}
}
}
// =================================================================================================
// Bytecode Translation
impl<'env> FunctionTranslator<'env> {
/// Translates one bytecode instruction.
fn translate_bytecode(
&self,
last_tracked_loc: &mut Option<(Loc, LineIndex)>,
bytecode: &Bytecode,
) {
use Bytecode::*;
let writer = self.parent.writer;
let spec_translator = &self.parent.spec_translator;
let options = self.parent.options;
let fun_target = self.fun_target;
let env = fun_target.global_env();
// Set location of this code in the CodeWriter.
let attr_id = bytecode.get_attr_id();
let loc = fun_target.get_bytecode_loc(attr_id);
writer.set_location(&loc);
// Print location.
emitln!(
writer,
"// {} {}",
bytecode.display(fun_target, &BTreeMap::default()),
loc.display(env)
);
// Print debug comments.
if let Some(comment) = fun_target.get_debug_comment(attr_id) {
emitln!(writer, "// {}", comment);
}
// Track location for execution traces.
if matches!(bytecode, Call(_, _, Operation::TraceAbort, ..)) {
// Ensure that aborts always has the precise location instead of the
// line-approximated one
*last_tracked_loc = None;
}
self.track_loc(last_tracked_loc, &loc);
// Helper function to get a a string for a local
let str_local = |idx: usize| format!("$t{}", idx);
// Translate the bytecode instruction.
match bytecode {
SaveMem(_, label, mem) => {
let mem = &mem.to_owned().instantiate(self.type_inst);
let snapshot = boogie_resource_memory_name(env, mem, &Some(*label));
let current = boogie_resource_memory_name(env, mem, &None);
emitln!(writer, "{} := {};", snapshot, current);
}
SaveSpecVar(_, _label, _var) => {
panic!("spec var snapshot NYI")
}
Prop(id, kind, exp) => match kind {
PropKind::Assert => {
emit!(writer, "assert ");
let info = fun_target
.get_vc_info(*id)
.map(|s| s.as_str())
.unwrap_or("unknown assertion failed");
emit!(
writer,
"{{:msg \"assert_failed{}: {}\"}}\n ",
self.loc_str(&loc),
info
);
spec_translator.translate(exp, self.type_inst);
emitln!(writer, ";");
}
PropKind::Assume => {
emit!(writer, "assume ");
spec_translator.translate(exp, self.type_inst);
emitln!(writer, ";");
}
PropKind::Modifies => {
let ty = &self.inst(&env.get_node_type(exp.node_id()));
let (mid, sid, inst) = ty.require_struct();
let memory = boogie_resource_memory_name(
env,
&mid.qualified_inst(sid, inst.to_owned()),
&None,
);
let exists_str = boogie_temp(env, &BOOL_TYPE, 0);
emitln!(writer, "havoc {};", exists_str);
emitln!(writer, "if ({}) {{", exists_str);
writer.with_indent(|| {
let val_str = boogie_temp(env, ty, 0);
emitln!(writer, "havoc {};", val_str);
emit!(writer, "{} := $ResourceUpdate({}, ", memory, memory);
spec_translator.translate(&exp.call_args()[0], self.type_inst);
emitln!(writer, ", {});", val_str);
});
emitln!(writer, "} else {");
writer.with_indent(|| {
emit!(writer, "{} := $ResourceRemove({}, ", memory, memory);
spec_translator.translate(&exp.call_args()[0], self.type_inst);
emitln!(writer, ");");
});
emitln!(writer, "}");
}
},
Label(_, label) => {
writer.unindent();
emitln!(writer, "L{}:", label.as_usize());
writer.indent();
}
Jump(_, target) => emitln!(writer, "goto L{};", target.as_usize()),
Branch(_, then_target, else_target, idx) => emitln!(
writer,
"if ({}) {{ goto L{}; }} else {{ goto L{}; }}",
str_local(*idx),
then_target.as_usize(),
else_target.as_usize(),
),
Assign(_, dest, src, _) => {
emitln!(writer, "{} := {};", str_local(*dest), str_local(*src));
}
Ret(_, rets) => {
for (i, r) in rets.iter().enumerate() {
emitln!(writer, "$ret{} := {};", i, str_local(*r));
}
// Also assign input to output $mut parameters
let mut ret_idx = rets.len();
for i in 0..fun_target.get_parameter_count() {
if self.get_local_type(i).is_mutable_reference() {
emitln!(writer, "$ret{} := {};", ret_idx, str_local(i));
ret_idx = usize::saturating_add(ret_idx, 1);
}
}
emitln!(writer, "return;");
}
Load(_, dest, c) => {
let value = match c {
Constant::Bool(true) => "true".to_string(),
Constant::Bool(false) => "false".to_string(),
Constant::U8(num) => num.to_string(),
Constant::U64(num) => num.to_string(),
Constant::U128(num) => num.to_string(),
Constant::Address(val) => val.to_string(),
Constant::ByteArray(val) => boogie_byte_blob(options, val),
};
let dest_str = str_local(*dest);
emitln!(writer, "{} := {};", dest_str, value);
// Insert a WellFormed assumption so the new value gets tagged as u8, ...
let ty = &self.get_local_type(*dest);
let check = boogie_well_formed_check(env, &dest_str, ty);
if !check.is_empty() {
emitln!(writer, &check);
}
}
Call(_, dests, oper, srcs, aa) => {
use Operation::*;
match oper {
FreezeRef => unreachable!(),
UnpackRef | UnpackRefDeep | PackRef | PackRefDeep => {
// No effect
}
OpaqueCallBegin(_, _, _) | OpaqueCallEnd(_, _, _) => {
// These are just markers. There is no generated code.
}
WriteBack(node, edge) => {
self.translate_write_back(node, edge, srcs[0]);
}
IsParent(node, edge) => {
if let BorrowNode::Reference(parent) = node {
let src_str = str_local(srcs[0]);
let edge_pattern = edge
.flatten()
.into_iter()
.filter_map(|e| match e {
BorrowEdge::Field(_, offset) => Some(format!("{}", offset)),
BorrowEdge::Index => Some("-1".to_owned()),
BorrowEdge::Direct => None,
_ => unreachable!(),
})
.collect_vec();
if edge_pattern.len() == 1 {
emitln!(
writer,
"{} := $IsParentMutation({}, {}, {});",
str_local(dests[0]),
str_local(*parent),
edge_pattern[0],
src_str
);
} else {
emitln!(
writer,
"{} := $IsParentMutationHyper({}, {}, {});",
str_local(dests[0]),
str_local(*parent),
boogie_make_vec_from_strings(&edge_pattern),
src_str
);
}
} else {
panic!("inconsistent IsParent instruction: expected a reference node")
}
}
BorrowLoc => {
let src = srcs[0];
let dest = dests[0];
emitln!(
writer,
"{} := $Mutation($Local({}), EmptyVec(), {});",
str_local(dest),
src,
str_local(src)
);
}
ReadRef => {
let src = srcs[0];
let dest = dests[0];
emitln!(
writer,
"{} := $Dereference({});",
str_local(dest),
str_local(src)
);
}
WriteRef => {
let reference = srcs[0];
let value = srcs[1];
emitln!(
writer,
"{} := $UpdateMutation({}, {});",
str_local(reference),
str_local(reference),
str_local(value),
);
}
Function(mid, fid, inst) => {
let inst = &self.inst_slice(inst);
let callee_env = env.get_module(*mid).into_function(*fid);
let args_str = srcs.iter().cloned().map(str_local).join(", ");
let dest_str = dests
.iter()
.cloned()
.map(str_local)
// Add implict dest returns for &mut srcs:
// f(x) --> x := f(x) if type(x) = &mut_
.chain(
srcs.iter()
.filter(|idx| self.get_local_type(**idx).is_mutable_reference())
.cloned()
.map(str_local),
)
.join(",");
if dest_str.is_empty() {
emitln!(
writer,
"call {}({});",
boogie_function_name(&callee_env, inst),
args_str
);
} else {
emitln!(
writer,
"call {} := {}({});",
dest_str,
boogie_function_name(&callee_env, inst),
args_str
);
}
// Clear the last track location after function call, as the call inserted
// location tracks before it returns.
*last_tracked_loc = None;
}
Pack(mid, sid, inst) => {
let inst = &self.inst_slice(inst);
let struct_env = env.get_module(*mid).into_struct(*sid);
let args = srcs.iter().cloned().map(str_local).join(", ");
let dest_str = str_local(dests[0]);
emitln!(
writer,
"{} := {}({});",
dest_str,
boogie_struct_name(&struct_env, inst),
args
);
}
Unpack(mid, sid, inst) => {
let inst = &self.inst_slice(inst);
let struct_env = env.get_module(*mid).into_struct(*sid);
for (i, ref field_env) in struct_env.get_fields().enumerate() {
let field_sel = format!(
"{}({})",
boogie_field_sel(field_env, inst),
str_local(srcs[0])
);
emitln!(writer, "{} := {};", str_local(dests[i]), field_sel);
}
}
BorrowField(mid, sid, inst, field_offset) => {
let inst = &self.inst_slice(inst);
let src_str = str_local(srcs[0]);
let dest_str = str_local(dests[0]);
let struct_env = env.get_module(*mid).into_struct(*sid);
let field_env = &struct_env.get_field_by_offset(*field_offset);
let sel_fun = boogie_field_sel(field_env, inst);
emitln!(
writer,
"{} := $ChildMutation({}, {}, {}($Dereference({})));",
dest_str,
src_str,
field_offset,
sel_fun,
src_str
);
}
GetField(mid, sid, inst, field_offset) => {
let inst = &self.inst_slice(inst);
let src = srcs[0];
let mut src_str = str_local(src);
let dest_str = str_local(dests[0]);
let struct_env = env.get_module(*mid).into_struct(*sid);
let field_env = &struct_env.get_field_by_offset(*field_offset);
let sel_fun = boogie_field_sel(field_env, inst);
if self.get_local_type(src).is_reference() {
src_str = format!("$Dereference({})", src_str);
};
emitln!(writer, "{} := {}({});", dest_str, sel_fun, src_str);
}
Exists(mid, sid, inst) => {
let inst = self.inst_slice(inst);
let addr_str = str_local(srcs[0]);
let dest_str = str_local(dests[0]);
let memory = boogie_resource_memory_name(
env,
&mid.qualified_inst(*sid, inst),
&None,
);
emitln!(
writer,
"{} := $ResourceExists({}, {});",
dest_str,
memory,
addr_str
);
}
BorrowGlobal(mid, sid, inst) => {
let inst = self.inst_slice(inst);
let addr_str = str_local(srcs[0]);
let dest_str = str_local(dests[0]);
let memory = boogie_resource_memory_name(
env,
&mid.qualified_inst(*sid, inst),
&None,
);
emitln!(writer, "if (!$ResourceExists({}, {})) {{", memory, addr_str);
writer.with_indent(|| emitln!(writer, "call $ExecFailureAbort();"));
emitln!(writer, "} else {");
writer.with_indent(|| {
emitln!(
writer,
"{} := $Mutation($Global({}), EmptyVec(), $ResourceValue({}, {}));",
dest_str,
addr_str,
memory,
addr_str
);
});
emitln!(writer, "}");
}
GetGlobal(mid, sid, inst) => {
let inst = self.inst_slice(inst);
let memory = boogie_resource_memory_name(
env,
&mid.qualified_inst(*sid, inst),
&None,
);
let addr_str = str_local(srcs[0]);
let dest_str = str_local(dests[0]);
emitln!(writer, "if (!$ResourceExists({}, {})) {{", memory, addr_str);
writer.with_indent(|| emitln!(writer, "call $ExecFailureAbort();"));
emitln!(writer, "} else {");
writer.with_indent(|| {
emitln!(
writer,
"{} := $ResourceValue({}, {});",
dest_str,
memory,
addr_str
);
});
emitln!(writer, "}");
}
MoveTo(mid, sid, inst) => {
let inst = self.inst_slice(inst);
let memory = boogie_resource_memory_name(
env,
&mid.qualified_inst(*sid, inst),
&None,
);
let value_str = str_local(srcs[0]);
let signer_str = str_local(srcs[1]);
emitln!(
writer,
"if ($ResourceExists({}, $addr#$signer({}))) {{",
memory,
signer_str
);
writer.with_indent(|| emitln!(writer, "call $ExecFailureAbort();"));
emitln!(writer, "} else {");
writer.with_indent(|| {
emitln!(
writer,
"{} := $ResourceUpdate({}, $addr#$signer({}), {});",
memory,
memory,
signer_str,
value_str
);
});
emitln!(writer, "}");
}
MoveFrom(mid, sid, inst) => {
let inst = &self.inst_slice(inst);
let memory = boogie_resource_memory_name(
env,
&mid.qualified_inst(*sid, inst.to_owned()),
&None,
);
let addr_str = str_local(srcs[0]);
let dest_str = str_local(dests[0]);
emitln!(writer, "if (!$ResourceExists({}, {})) {{", memory, addr_str);
writer.with_indent(|| emitln!(writer, "call $ExecFailureAbort();"));
emitln!(writer, "} else {");
writer.with_indent(|| {
emitln!(
writer,
"{} := $ResourceValue({}, {});",
dest_str,
memory,
addr_str
);
emitln!(
writer,
"{} := $ResourceRemove({}, {});",
memory,
memory,
addr_str
);
});
emitln!(writer, "}");
}
Havoc(HavocKind::Value) | Havoc(HavocKind::MutationAll) => {
let src_str = str_local(srcs[0]);
emitln!(writer, "havoc {};", src_str);
// Insert a WellFormed check
let ty = &self.get_local_type(srcs[0]);
let check = boogie_well_formed_check(env, &src_str, ty);
if !check.is_empty() {
emitln!(writer, &check);
}
}
Havoc(HavocKind::MutationValue) => {
let ty = &self.get_local_type(srcs[0]);
let src_str = str_local(srcs[0]);
let temp_str = boogie_temp(env, ty.skip_reference(), 0);
emitln!(writer, "havoc {};", temp_str);
emitln!(
writer,
"{} := $UpdateMutation({}, {});",
src_str,
src_str,
temp_str
);
// Insert a WellFormed check
let check = boogie_well_formed_check(env, &src_str, ty);
if !check.is_empty() {
emitln!(writer, &check);
}
}
Stop => {
// the two statements combined terminate any execution trace that reaches it
emitln!(writer, "assume false;");
emitln!(writer, "return;");
}
CastU8 => {
let src = srcs[0];
let dest = dests[0];
emitln!(
writer,
"call {} := $CastU8({});",
str_local(dest),
str_local(src)
);
}
CastU64 => {
let src = srcs[0];
let dest = dests[0];
emitln!(
writer,
"call {} := $CastU64({});",
str_local(dest),
str_local(src)
);
}
CastU128 => {
let src = srcs[0];
let dest = dests[0];
emitln!(
writer,
"call {} := $CastU128({});",
str_local(dest),
str_local(src)
);
}
Not => {
let src = srcs[0];
let dest = dests[0];
emitln!(
writer,
"call {} := $Not({});",
str_local(dest),
str_local(src)
);
}
Add => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
let unchecked = if fun_target
.is_pragma_true(ADDITION_OVERFLOW_UNCHECKED_PRAGMA, || false)
{
"_unchecked"
} else {
""
};
let add_type = match &self.get_local_type(dest) {
Type::Primitive(PrimitiveType::U8) => "U8".to_string(),
Type::Primitive(PrimitiveType::U64) => format!("U64{}", unchecked),
Type::Primitive(PrimitiveType::U128) => format!("U128{}", unchecked),
_ => unreachable!(),
};
emitln!(
writer,
"call {} := $Add{}({}, {});",
str_local(dest),
add_type,
str_local(op1),
str_local(op2)
);
}
Sub => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Sub({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Mul => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
let mul_type = match &self.get_local_type(dest) {
Type::Primitive(PrimitiveType::U8) => "U8",
Type::Primitive(PrimitiveType::U64) => "U64",
Type::Primitive(PrimitiveType::U128) => "U128",
_ => unreachable!(),
};
emitln!(
writer,
"call {} := $Mul{}({}, {});",
str_local(dest),
mul_type,
str_local(op1),
str_local(op2)
);
}
Div => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Div({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Mod => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Mod({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Shl => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Shl({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Shr => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Shr({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Lt => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Lt({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Gt => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Gt({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Le => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Le({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Ge => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Ge({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Or => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $Or({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
And => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
emitln!(
writer,
"call {} := $And({}, {});",
str_local(dest),
str_local(op1),
str_local(op2)
);
}
Eq | Neq => {
let dest = dests[0];
let op1 = srcs[0];
let op2 = srcs[1];
let oper =
boogie_equality_for_type(env, oper == &Eq, &self.get_local_type(op1));
emitln!(
writer,
"{} := {}({}, {});",
str_local(dest),
oper,
str_local(op1),
str_local(op2)
);
}
BitOr | BitAnd | Xor => {
emitln!(
writer,
"// bit operation not supported: {:?}\nassert false;",
bytecode
);
}
Destroy => {}
TraceLocal(idx) => {
self.track_local(*idx, srcs[0]);
}
TraceReturn(i) => {
self.track_return(*i, srcs[0]);
}
TraceAbort => self.track_abort(&str_local(srcs[0])),
TraceExp(kind, node_id) => self.track_exp(*kind, *node_id, srcs[0]),
EmitEvent => {
let msg = srcs[0];
let handle = srcs[1];
let translate_local = |idx: usize| {
let ty = &self.get_local_type(idx);
if ty.is_mutable_reference() {
format!("$Dereference({})", str_local(idx))
} else {
str_local(idx)
}
};
let suffix = boogie_type_suffix(env, &self.get_local_type(msg));
emit!(
writer,
"$es := ${}ExtendEventStore'{}'($es, ",
if srcs.len() > 2 { "Cond" } else { "" },
suffix
);
emit!(writer, "{}, {}", translate_local(handle), str_local(msg));
if srcs.len() > 2 {
emit!(writer, ", {}", str_local(srcs[2]));
}
emitln!(writer, ");");
}
EventStoreDiverge => {
emitln!(writer, "call $es := $EventStore__diverge($es);");
}
TraceGlobalMem(mem) => {
let mem = &mem.to_owned().instantiate(self.type_inst);
let node_id = env.new_node(env.unknown_loc(), mem.to_type());
self.track_global_mem(mem, node_id);
}
}
if let Some(AbortAction(target, code)) = aa {
emitln!(writer, "if ($abort_flag) {");
writer.indent();
*last_tracked_loc = None;
self.track_loc(last_tracked_loc, &loc);
let code_str = str_local(*code);
emitln!(writer, "{} := $abort_code;", code_str);
self.track_abort(&code_str);
emitln!(writer, "goto L{};", target.as_usize());
writer.unindent();
emitln!(writer, "}");
}
}
Abort(_, src) => {
emitln!(writer, "$abort_code := {};", str_local(*src));
emitln!(writer, "$abort_flag := true;");
emitln!(writer, "return;")
}
Nop(..) => {}
}
emitln!(writer);
}
fn translate_write_back(&self, dest: &BorrowNode, edge: &BorrowEdge, src: TempIndex) {
use BorrowNode::*;
let writer = self.parent.writer;
let env = self.parent.env;
let src_str = format!("$t{}", src);
match dest {
ReturnPlaceholder(_) => {
unreachable!("unexpected transient borrow node")
}
GlobalRoot(memory) => {
assert!(matches!(edge, BorrowEdge::Direct));
let memory = &memory.to_owned().instantiate(self.type_inst);
let memory_name = boogie_resource_memory_name(env, memory, &None);
emitln!(
writer,
"{} := $ResourceUpdate({}, $GlobalLocationAddress({}),\n \
$Dereference({}));",
memory_name,
memory_name,
src_str,
src_str
);
}
LocalRoot(idx) => {
assert!(matches!(edge, BorrowEdge::Direct));
emitln!(writer, "$t{} := $Dereference({});", idx, src_str);
}
Reference(idx) => {
let dst_value = format!("$Dereference($t{})", idx);
let src_value = format!("$Dereference({})", src_str);
let get_path_index = |offset: usize| {
if offset == 0 {
format!(
"ReadVec(p#$Mutation({}), LenVec(p#$Mutation($t{})))",
src_str, idx
)
} else {
format!(
"ReadVec(p#$Mutation({}), LenVec(p#$Mutation($t{})) + {})",
src_str, idx, offset
)
}
};
let update = if let BorrowEdge::Hyper(edges) = edge {
self.translate_write_back_update(
&mut || dst_value.clone(),
&get_path_index,
src_value,
edges,
0,
)
} else {
self.translate_write_back_update(
&mut || dst_value.clone(),
&get_path_index,
src_value,
&[edge.to_owned()],
0,
)
};
emitln!(
writer,
"$t{} := $UpdateMutation($t{}, {});",
idx,
idx,
update
);
}
}
}
fn translate_write_back_update(
&self,
mk_dest: &mut dyn FnMut() -> String,
get_path_index: &dyn Fn(usize) -> String,
src: String,
edges: &[BorrowEdge],
at: usize,
) -> String {
if at >= edges.len() {
src
} else {
match &edges[at] {
BorrowEdge::Direct => {
self.translate_write_back_update(mk_dest, get_path_index, src, edges, at + 1)
}
BorrowEdge::Field(memory, offset) => {
let memory = memory.to_owned().instantiate(self.type_inst);
let struct_env = &self.parent.env.get_struct_qid(memory.to_qualified_id());
let field_env = &struct_env.get_field_by_offset(*offset);
let sel_fun = boogie_field_sel(field_env, &memory.inst);
let new_dest = format!("{}({})", sel_fun, (*mk_dest)());
let mut new_dest_needed = false;
let new_src = self.translate_write_back_update(
&mut || {
new_dest_needed = true;
format!("$$sel{}", at)
},
get_path_index,
src,
edges,
at + 1,
);
let update_fun = boogie_field_update(field_env, &memory.inst);
if new_dest_needed {
format!(
"(var $$sel{} := {}; {}({}, {}))",
at,
new_dest,
update_fun,
(*mk_dest)(),
new_src
)
} else {
format!("{}({}, {})", update_fun, (*mk_dest)(), new_src)
}
}
BorrowEdge::Index => {
// Compute the offset into the path where to retrieve the index.
let offset = edges[0..at]
.iter()
.filter(|e| !matches!(e, BorrowEdge::Direct))
.count();
let index = (*get_path_index)(offset);
let new_dest = format!("ReadVec({}, {})", (*mk_dest)(), index);
let mut new_dest_needed = false;
let new_src = self.translate_write_back_update(
&mut || {
new_dest_needed = true;
format!("$$sel{}", at)
},
get_path_index,
src,
edges,
at + 1,
);
if new_dest_needed {
format!(
"(var $$sel{} := {}; UpdateVec({}, {}, {}))",
at,
new_dest,
(*mk_dest)(),
index,
new_src
)
} else {
format!("UpdateVec({}, {}, {})", (*mk_dest)(), index, new_src)
}
}
BorrowEdge::Hyper(_) => unreachable!("unexpected borrow edge"),
}
}
}
/// Track location for execution trace, avoiding to track the same line multiple times.
fn track_loc(&self, last_tracked_loc: &mut Option<(Loc, LineIndex)>, loc: &Loc) {
let env = self.fun_target.global_env();
if let Some(l) = env.get_location(loc) {
if let Some((last_loc, last_line)) = last_tracked_loc {
if *last_line == l.line {
// This line already tracked.
return;
}
*last_loc = loc.clone();
*last_line = l.line;
} else {
*last_tracked_loc = Some((loc.clone(), l.line));
}
emitln!(
self.parent.writer,
"assume {{:print \"$at{}\"}} true;",
self.loc_str(loc)
);
}
}
fn track_abort(&self, code_var: &str) {
emitln!(
self.parent.writer,
&boogie_debug_track_abort(self.fun_target, code_var)
);
}
/// Generates an update of the debug information about temporary.
fn track_local(&self, origin_idx: TempIndex, idx: TempIndex) {
emitln!(
self.parent.writer,
&boogie_debug_track_local(self.fun_target, origin_idx, idx, &self.get_local_type(idx),)
);
}
/// Generates an update of the debug information about the return value at given location.
fn track_return(&self, return_idx: usize, idx: TempIndex) {
emitln!(
self.parent.writer,
&boogie_debug_track_return(self.fun_target, return_idx, idx, &self.get_local_type(idx))
);
}
/// Generates the bytecode to print out the value of mem.
fn track_global_mem(&self, mem: &QualifiedInstId<StructId>, node_id: NodeId) {
let env = self.parent.env;
let temp_str = boogie_resource_memory_name(env, mem, &None);
emitln!(
self.parent.writer,
"assume {{:print \"$track_global_mem({}):\", {}}} true;",
node_id.as_usize(),
temp_str,
);
}
fn track_exp(&self, kind: TraceKind, node_id: NodeId, temp: TempIndex) {
let env = self.parent.env;
let writer = self.parent.writer;
let ty = self.get_local_type(temp);
let temp_str = if ty.is_reference() {
let new_temp = boogie_temp(env, ty.skip_reference(), 0);
emitln!(writer, "{} := $Dereference($t{});", new_temp, temp);
new_temp
} else {
format!("$t{}", temp)
};
let suffix = if kind == TraceKind::SubAuto {
"_sub"
} else {
""
};
emitln!(
self.parent.writer,
"assume {{:print \"$track_exp{}({}):\", {}}} true;",
suffix,
node_id.as_usize(),
temp_str,
);
}
fn loc_str(&self, loc: &Loc) -> String {
let file_idx = self.fun_target.global_env().file_id_to_idx(loc.file_id());
format!("({},{},{})", file_idx, loc.span().start(), loc.span().end())
}
/// Compute temporaries needed for the compilation of given function. Because boogie does
/// not allow to declare locals in arbitrary blocks, we need to compute them upfront.
fn compute_needed_temps(&self) -> BTreeMap<String, (Type, usize)> {
use Bytecode::*;
use Operation::*;
let fun_target = self.fun_target;
let env = fun_target.global_env();
let mut res: BTreeMap<String, (Type, usize)> = BTreeMap::new();
let mut need = |ty: &Type, n: usize| {
// Index by type suffix, which is more coarse grained then type.
let ty = ty.skip_reference();
let suffix = boogie_type_suffix(env, ty);
let cnt = res.entry(suffix).or_insert_with(|| (ty.to_owned(), 0));
(*cnt).1 = (*cnt).1.max(n);
};
for bc in &fun_target.data.code {
match bc {
Call(_, _, oper, srcs, ..) => match oper {
TraceExp(_, id) => need(&self.inst(&env.get_node_type(*id)), 1),
TraceReturn(idx) => need(&self.inst(fun_target.get_return_type(*idx)), 1),
TraceLocal(_) => need(&self.get_local_type(srcs[0]), 1),
Havoc(HavocKind::MutationValue) => need(&self.get_local_type(srcs[0]), 1),
_ => {}
},
Prop(_, PropKind::Modifies, exp) => {
need(&BOOL_TYPE, 1);
need(&self.inst(&env.get_node_type(exp.node_id())), 1)
}
_ => {}
}
}
res
}
}
fn struct_has_native_equality(
struct_env: &StructEnv<'_>,
inst: &[Type],
options: &BoogieOptions,
) -> bool {
if options.native_equality {
// Everything has native equality
return true;
}
for field in struct_env.get_fields() {
if !has_native_equality(
struct_env.module_env.env,
options,
&field.get_type().instantiate(inst),
) {
return false;
}
}
true
}
pub fn has_native_equality(env: &GlobalEnv, options: &BoogieOptions, ty: &Type) -> bool {
if options.native_equality {
// Everything has native equality
return true;
}
match ty {
Type::Vector(..) => false,
Type::Struct(mid, sid, sinst) => {
struct_has_native_equality(&env.get_struct_qid(mid.qualified(*sid)), sinst, options)
}
_ => true,
}
}
| 40.567538 | 100 | 0.395692 |
9022077559acfbe773475f548135baa22a4e3429
| 4,933 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! Execution plan for reading in-memory batches of data
use core::fmt;
use std::any::Any;
use std::sync::Arc;
use std::task::{Context, Poll};
use super::{ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream};
use crate::error::{DataFusionError, Result};
use arrow::datatypes::SchemaRef;
use arrow::error::Result as ArrowResult;
use arrow::record_batch::RecordBatch;
use async_trait::async_trait;
use futures::Stream;
/// Execution plan for reading in-memory batches of data
pub struct MemoryExec {
/// The partitions to query
partitions: Vec<Vec<RecordBatch>>,
/// Schema representing the data after the optional projection is applied
schema: SchemaRef,
/// Optional projection
projection: Option<Vec<usize>>,
}
impl fmt::Debug for MemoryExec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "partitions: [...]")?;
write!(f, "schema: {:?}", self.schema)?;
write!(f, "projection: {:?}", self.projection)
}
}
#[async_trait]
impl ExecutionPlan for MemoryExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
self
}
/// Get the schema for this execution plan
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
// this is a leaf node and has no children
vec![]
}
/// Get the output partitioning of this plan
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(self.partitions.len())
}
fn with_new_children(
&self,
_: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Err(DataFusionError::Internal(format!(
"Children cannot be replaced in {:?}",
self
)))
}
async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
Ok(Box::pin(MemoryStream::try_new(
self.partitions[partition].clone(),
self.schema.clone(),
self.projection.clone(),
)?))
}
}
impl MemoryExec {
/// Create a new execution plan for reading in-memory record batches
pub fn try_new(
partitions: &[Vec<RecordBatch>],
schema: SchemaRef,
projection: Option<Vec<usize>>,
) -> Result<Self> {
Ok(Self {
partitions: partitions.to_vec(),
schema,
projection,
})
}
}
/// Iterator over batches
pub(crate) struct MemoryStream {
/// Vector of record batches
data: Vec<RecordBatch>,
/// Schema representing the data
schema: SchemaRef,
/// Optional projection for which columns to load
projection: Option<Vec<usize>>,
/// Index into the data
index: usize,
}
impl MemoryStream {
/// Create an iterator for a vector of record batches
pub fn try_new(
data: Vec<RecordBatch>,
schema: SchemaRef,
projection: Option<Vec<usize>>,
) -> Result<Self> {
Ok(Self {
data,
schema,
projection,
index: 0,
})
}
}
impl Stream for MemoryStream {
type Item = ArrowResult<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Poll::Ready(if self.index < self.data.len() {
self.index += 1;
let batch = &self.data[self.index - 1];
// apply projection
match &self.projection {
Some(columns) => Some(RecordBatch::try_new(
self.schema.clone(),
columns.iter().map(|i| batch.column(*i).clone()).collect(),
)),
None => Some(Ok(batch.clone())),
}
} else {
None
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.data.len(), Some(self.data.len()))
}
}
impl RecordBatchStream for MemoryStream {
/// Get the schema
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
}
| 29.017647 | 87 | 0.610582 |
1af6a5beb7a8eeb195f89c4ede52c1b3d2cbdd73
| 7,191 |
mod sensitive;
use crate::{Config, HoustonProblem};
use sensitive::Sensitive;
use serde::{Deserialize, Serialize};
use camino::Utf8PathBuf as PathBuf;
use std::{fmt, fs, io};
/// Collects configuration related to a profile.
#[derive(Debug, Serialize, Deserialize)]
pub struct Profile {
sensitive: Sensitive,
}
/// Represents all possible options in loading configuration
pub struct LoadOpts {
/// Should sensitive config be included in the load
pub sensitive: bool,
}
/// Represents all possible configuration options.
pub struct ProfileData {
/// Apollo API Key
pub api_key: Option<String>,
}
/// Struct containing info about an API Key
pub struct Credential {
/// Apollo API Key
pub api_key: String,
/// The origin of the credential
pub origin: CredentialOrigin,
}
/// Info about where the API key was retrieved
#[derive(Debug, Clone, PartialEq)]
pub enum CredentialOrigin {
/// The credential is from an environment variable
EnvVar,
/// The credential is from a profile
ConfigFile(String),
}
impl Profile {
fn base_dir(config: &Config) -> PathBuf {
config.home.join("profiles")
}
fn dir(name: &str, config: &Config) -> PathBuf {
Profile::base_dir(config).join(name)
}
/// Writes an api_key to the filesystem (`$APOLLO_CONFIG_HOME/profiles/<profile_name>/.sensitive`).
pub fn set_api_key(name: &str, config: &Config, api_key: &str) -> Result<(), HoustonProblem> {
let data = ProfileData {
api_key: Some(api_key.to_string()),
};
Profile::save(name, config, data)?;
Ok(())
}
/// Returns an API key for interacting with Apollo services.
///
/// Checks for the presence of an `APOLLO_KEY` env var, and returns its value
/// if it finds it. Otherwise looks for credentials on the file system.
///
/// Takes an optional `profile` argument. Defaults to `"default"`.
pub fn get_credential(name: &str, config: &Config) -> Result<Credential, HoustonProblem> {
let credential = match &config.override_api_key {
Some(api_key) => Credential {
api_key: api_key.to_string(),
origin: CredentialOrigin::EnvVar,
},
None => {
let opts = LoadOpts { sensitive: true };
let profile = Profile::load(name, config, opts)?;
Credential {
api_key: profile.sensitive.api_key,
origin: CredentialOrigin::ConfigFile(name.to_string()),
}
}
};
tracing::debug!("using API key {}", mask_key(&credential.api_key));
Ok(credential)
}
/// Saves configuration options for a specific profile to the file system,
/// splitting sensitive information into a separate file.
pub fn save(name: &str, config: &Config, data: ProfileData) -> Result<(), HoustonProblem> {
if let Some(api_key) = data.api_key {
Sensitive { api_key }.save(name, config)?;
}
Ok(())
}
/// Loads and deserializes configuration from the file system for a
/// specific profile.
fn load(
profile_name: &str,
config: &Config,
opts: LoadOpts,
) -> Result<Profile, HoustonProblem> {
if Profile::dir(profile_name, config).exists() {
if opts.sensitive {
let sensitive = Sensitive::load(profile_name, config)?;
return Ok(Profile { sensitive });
}
Err(HoustonProblem::NoNonSensitiveConfigFound(
profile_name.to_string(),
))
} else {
let profiles_base_dir = Profile::base_dir(config);
let mut base_dir_contents =
fs::read_dir(profiles_base_dir).map_err(|_| HoustonProblem::NoConfigProfiles)?;
if base_dir_contents.next().is_none() {
return Err(HoustonProblem::NoConfigProfiles);
}
Err(HoustonProblem::ProfileNotFound(profile_name.to_string()))
}
}
/// Deletes profile data from file system.
pub fn delete(name: &str, config: &Config) -> Result<(), HoustonProblem> {
let dir = Profile::dir(name, config);
tracing::debug!(dir = ?dir);
fs::remove_dir_all(dir).map_err(|e| match e.kind() {
io::ErrorKind::NotFound => HoustonProblem::ProfileNotFound(name.to_string()),
_ => HoustonProblem::IoError(e),
})
}
/// Lists profiles based on directories in `$APOLLO_CONFIG_HOME/profiles`
pub fn list(config: &Config) -> Result<Vec<String>, HoustonProblem> {
let profiles_dir = Profile::base_dir(config);
let mut profiles = vec![];
// if profiles dir doesn't exist return empty vec
let entries = fs::read_dir(profiles_dir);
if let Ok(entries) = entries {
for entry in entries {
let entry_path = entry?.path();
if entry_path.is_dir() {
let profile = entry_path.file_stem().unwrap();
tracing::debug!(?profile);
profiles.push(profile.to_string_lossy().into_owned());
}
}
}
Ok(profiles)
}
}
impl fmt::Display for Profile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.sensitive)
}
}
/// Masks all but the first 4 and last 4 chars of a key with a set number of *
/// valid keys are all at least 22 chars.
// We don't care if invalid keys
// are printed, so we don't need to worry about strings 8 chars or less,
// which this fn would just print back out
pub fn mask_key(key: &str) -> String {
let mut masked_key = "".to_string();
for (i, char) in key.chars().enumerate() {
if i <= 3 || i >= key.len() - 4 {
masked_key.push(char);
} else {
masked_key.push('*');
}
}
masked_key
}
#[cfg(test)]
mod tests {
use super::mask_key;
#[test]
fn it_can_mask_user_key() {
let input = "user:gh.foo:djru4788dhsg3657fhLOLO";
assert_eq!(
mask_key(input),
"user**************************LOLO".to_string()
);
}
#[test]
fn it_can_mask_long_user_key() {
let input = "user:veryveryveryveryveryveryveryveryveryveryveryverylong";
assert_eq!(
mask_key(input),
"user*************************************************long".to_string()
);
}
#[test]
fn it_can_mask_graph_key() {
let input = "service:foo:djru4788dhsg3657fhLOLO";
assert_eq!(
mask_key(input),
"serv**************************LOLO".to_string()
);
}
#[test]
fn it_can_mask_nonsense() {
let input = "some nonsense";
assert_eq!(mask_key(input), "some*****ense".to_string());
}
#[test]
fn it_can_mask_nothing() {
let input = "";
assert_eq!(mask_key(input), "".to_string());
}
#[test]
fn it_can_mask_short() {
let input = "short";
assert_eq!(mask_key(input), "short".to_string());
}
}
| 31.12987 | 103 | 0.578084 |
030bd12cbdfe15b4e67784e4b0b00e130650dc3c
| 6,467 |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// 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.
//! Macros for implementing Queriable FieldId enum methods (thus named qenum).
//!
//! This mod is mostly inspired by the strum_macros crate, particularly
//! EnumString (for EnumFromStr), strum_macros:ToString (for EnumToString), and
//! EnumIter (for EnumIter). However, this mod extends those macros by defining
//! special behaviors with enum variants that contains a single unnamed field.
//! These variants are mainly used by Queriable::FieldId to access fields of
//! sub-models, making the enum a mapping of the tree structure of its
//! corresponding Queriable.
use crate::helper::to_snakecase;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{spanned::Spanned, DeriveInput, LitStr};
fn get_variants(
ast: &DeriveInput,
) -> syn::Result<&syn::punctuated::Punctuated<syn::Variant, syn::Token![,]>> {
match &ast.data {
syn::Data::Enum(syn::DataEnum { variants, .. }) => Ok(variants),
_ => Err(syn::Error::new(
Span::call_site(),
"This macro only supports enum.",
)),
}
}
fn variant_constraint_error(span: Span) -> syn::Error {
syn::Error::new(
span,
"This macro only supports unit variant or variant with one unnamed field.",
)
}
pub fn enum_to_string_derive_impl(ast: &DeriveInput) -> syn::Result<TokenStream> {
let enum_name = &ast.ident;
let variant_to_string_arms = get_variants(ast)?
.iter()
.map(|variant| {
let variant_name = &variant.ident;
let snake = to_snakecase(variant_name);
let snake_str = LitStr::new(&snake.to_string(), snake.span());
match &variant.fields {
syn::Fields::Unnamed(unnamed) if unnamed.unnamed.len() == 1 => Ok(quote! {
Self::#variant_name(nested) => format!(
"{}.{}",
#snake_str,
nested.to_string()
),
}),
syn::Fields::Unit => Ok(quote! {
Self::#variant_name => #snake_str.to_owned(),
}),
_ => Err(variant_constraint_error(variant.span())),
}
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
impl ::std::string::ToString for #enum_name {
fn to_string(&self) -> ::std::string::String {
match self {
#(#variant_to_string_arms)*
}
}
}
})
}
pub fn enum_from_str_derive_impl(ast: &DeriveInput) -> syn::Result<TokenStream> {
let enum_name = &ast.ident;
let variant_from_str_arms = get_variants(ast)?
.iter()
.map(|variant| {
let variant_name = &variant.ident;
let snake = to_snakecase(variant_name);
let snake_str = LitStr::new(&snake.to_string(), snake.span());
match &variant.fields {
syn::Fields::Unnamed(unnamed) if unnamed.unnamed.len() == 1 => {
let nested_type = &unnamed.unnamed[0].ty;
Ok(quote! {
_ if s.starts_with(concat!(#snake_str, ".")) => {
#nested_type::from_str(unsafe {
s.get_unchecked(concat!(#snake_str, ".").len()..)
}).map(Self::#variant_name)
}
})
}
syn::Fields::Unit => Ok(quote! {
#snake_str => Ok(Self::#variant_name),
}),
_ => Err(variant_constraint_error(variant.span())),
}
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
impl ::std::str::FromStr for #enum_name {
type Err = ::anyhow::Error;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
match s {
#(#variant_from_str_arms)*
_ => Err(::anyhow::anyhow!(
"Unable to find a variant of the given enum matching string `{}`.",
s,
)),
}
}
}
})
}
pub fn enum_iter_derive_impl(ast: &DeriveInput) -> syn::Result<TokenStream> {
let enum_name = &ast.ident;
let variants = get_variants(ast)?;
let unit_variants = variants.iter().filter(|variant| match &variant.fields {
syn::Fields::Unit => true,
_ => false,
});
// Iterate over all enums by chaining them together. Unit variants are
// wrapped in std::iter::once. Basically a DFS over the enum tree.
let all_variant_iter_chain = variants
.iter()
.map(|variant| {
let variant_name = &variant.ident;
match &variant.fields {
syn::Fields::Unnamed(unnamed) if unnamed.unnamed.len() == 1 => {
let nested_type = &unnamed.unnamed[0].ty;
Ok(quote! {
.chain(#nested_type::all_variant_iter().map(Self::#variant_name))
})
}
syn::Fields::Unit => Ok(quote! {
.chain(::std::iter::once(Self::#variant_name))
}),
_ => Err(variant_constraint_error(variant.span())),
}
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
impl #enum_name {
pub fn unit_variant_iter() -> impl ::std::iter::Iterator<Item = Self> {
const UNIT_VARIANTS: &[#enum_name] = &[#(#enum_name::#unit_variants),*];
UNIT_VARIANTS.iter().cloned()
}
pub fn all_variant_iter() -> impl ::std::iter::Iterator<Item = Self> {
::std::iter::empty()
#(#all_variant_iter_chain)*
}
}
})
}
| 36.954286 | 91 | 0.535024 |
ff153b0bbe445a21035d94ed6b20cd2607b0154b
| 5,347 |
//! The `sigverify_stage` implements the signature verification stage of the TPU. It
//! receives a list of lists of packets and outputs the same list, but tags each
//! top-level list with a list of booleans, telling the next stage whether the
//! signature in that packet is valid. It assumes each packet contains one
//! transaction. All processing is done on the CPU by default and on a GPU
//! if perf-libs are available
use crate::sigverify;
use crossbeam_channel::{SendError, Sender as CrossbeamSender};
use solana_measure::measure::Measure;
use solana_metrics::datapoint_debug;
use solana_perf::packet::Packets;
use solana_perf::perf_libs;
use solana_sdk::timing;
use solana_streamer::streamer::{self, PacketReceiver, StreamerError};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::thread::{self, Builder, JoinHandle};
use thiserror::Error;
const RECV_BATCH_MAX_CPU: usize = 1_000;
const RECV_BATCH_MAX_GPU: usize = 5_000;
#[derive(Error, Debug)]
pub enum SigVerifyServiceError {
#[error("send packets batch error")]
SendError(#[from] SendError<Vec<Packets>>),
#[error("streamer error")]
StreamerError(#[from] StreamerError),
}
type Result<T> = std::result::Result<T, SigVerifyServiceError>;
pub struct SigVerifyStage {
thread_hdls: Vec<JoinHandle<()>>,
}
pub trait SigVerifier {
fn verify_batch(&self, batch: Vec<Packets>) -> Vec<Packets>;
}
#[derive(Default, Clone)]
pub struct DisabledSigVerifier {}
impl SigVerifier for DisabledSigVerifier {
fn verify_batch(&self, mut batch: Vec<Packets>) -> Vec<Packets> {
sigverify::ed25519_verify_disabled(&mut batch);
batch
}
}
impl SigVerifyStage {
#[allow(clippy::new_ret_no_self)]
pub fn new<T: SigVerifier + 'static + Send + Clone>(
packet_receiver: Receiver<Packets>,
verified_sender: CrossbeamSender<Vec<Packets>>,
verifier: T,
) -> Self {
let thread_hdls = Self::verifier_services(packet_receiver, verified_sender, verifier);
Self { thread_hdls }
}
fn verifier<T: SigVerifier>(
recvr: &Arc<Mutex<PacketReceiver>>,
sendr: &CrossbeamSender<Vec<Packets>>,
id: usize,
verifier: &T,
) -> Result<()> {
let (batch, len, recv_time) = streamer::recv_batch(
&recvr.lock().expect("'recvr' lock in fn verifier"),
if perf_libs::api().is_some() {
RECV_BATCH_MAX_GPU
} else {
RECV_BATCH_MAX_CPU
},
)?;
let mut verify_batch_time = Measure::start("sigverify_batch_time");
let batch_len = batch.len();
debug!(
"@{:?} verifier: verifying: {} id: {}",
timing::timestamp(),
len,
id
);
let verified_batch = verifier.verify_batch(batch);
for v in verified_batch {
sendr.send(vec![v])?;
}
verify_batch_time.stop();
debug!(
"@{:?} verifier: done. batches: {} total verify time: {:?} id: {} verified: {} v/s {}",
timing::timestamp(),
batch_len,
verify_batch_time.as_ms(),
id,
len,
(len as f32 / verify_batch_time.as_s())
);
datapoint_debug!(
"sigverify_stage-total_verify_time",
("num_batches", batch_len, i64),
("num_packets", len, i64),
("verify_time_ms", verify_batch_time.as_ms(), i64),
("recv_time", recv_time, i64),
);
Ok(())
}
fn verifier_service<T: SigVerifier + 'static + Send + Clone>(
packet_receiver: Arc<Mutex<PacketReceiver>>,
verified_sender: CrossbeamSender<Vec<Packets>>,
id: usize,
verifier: &T,
) -> JoinHandle<()> {
let verifier = verifier.clone();
Builder::new()
.name(format!("solana-verifier-{}", id))
.spawn(move || loop {
if let Err(e) = Self::verifier(&packet_receiver, &verified_sender, id, &verifier) {
match e {
SigVerifyServiceError::StreamerError(StreamerError::RecvTimeoutError(
RecvTimeoutError::Disconnected,
)) => break,
SigVerifyServiceError::StreamerError(StreamerError::RecvTimeoutError(
RecvTimeoutError::Timeout,
)) => (),
SigVerifyServiceError::SendError(_) => {
break;
}
_ => error!("{:?}", e),
}
}
})
.unwrap()
}
fn verifier_services<T: SigVerifier + 'static + Send + Clone>(
packet_receiver: PacketReceiver,
verified_sender: CrossbeamSender<Vec<Packets>>,
verifier: T,
) -> Vec<JoinHandle<()>> {
let receiver = Arc::new(Mutex::new(packet_receiver));
(0..4)
.map(|id| {
Self::verifier_service(receiver.clone(), verified_sender.clone(), id, &verifier)
})
.collect()
}
pub fn join(self) -> thread::Result<()> {
for thread_hdl in self.thread_hdls {
thread_hdl.join()?;
}
Ok(())
}
}
| 32.406061 | 99 | 0.572284 |
d50bbd66765d27b5c4ae42fa7e081e1040ebc5ac
| 276 |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
pub mod account;
pub mod association_capability;
pub mod balance;
pub mod currency_info;
pub use account::*;
pub use association_capability::*;
pub use balance::*;
pub use currency_info::*;
| 21.230769 | 44 | 0.757246 |
5b842e9a7505dbae1eb2d4ffa6022ff966cbed86
| 3,036 |
use crate::generator::generators::*;
use common::block::*;
use common::chunk::*;
use common::world_type::GeneratorType;
use std::i16;
use std::sync::Arc;
use super::ObjectPlacer;
use super::PregeneratedObject;
/// Generate complete columns of chunks of a given world type, based on a seed
pub struct ColumnGenerator {
hills_generator: HillsGenerator,
flat_generator: FlatGenerator,
water_generator: WaterWorldGenerator,
alien_generator: AlienGenerator,
poi_objects: ObjectPlacer,
tree_objects: ObjectPlacer,
}
impl ColumnGenerator {
pub fn new(
seed: u32,
poi_object_list: Arc<Vec<PregeneratedObject>>,
tree_object_list: Arc<Vec<PregeneratedObject>>,
) -> Self {
ColumnGenerator {
hills_generator: HillsGenerator::new(seed),
flat_generator: FlatGenerator::new(32, 36),
water_generator: WaterWorldGenerator::new(seed),
alien_generator: AlienGenerator::new(seed),
poi_objects: ObjectPlacer::new(seed, poi_object_list, 32, 1, 0.2, false, false),
tree_objects: ObjectPlacer::new(seed, tree_object_list, 13, 0, 0.35, true, true),
}
}
pub fn generate_column(
&mut self,
world_type: GeneratorType,
col: ChunkColumnPos,
) -> Vec<Chunk> {
let cwx = col.x * CHUNK_SIZE as i16;
let cwy = col.y * CHUNK_SIZE as i16;
// Create empty column first
let mut column = Vec::new();
for z in 0..WORLD_HEIGHT_CHUNKS {
column.push(Chunk::new_solid(
ChunkPos::new(col.x, col.y, z as i16),
Block::empty_block(),
));
}
// Generate the column in 1x1 columns of world height
for rel_x in 0..CHUNK_SIZE {
for rel_y in 0..CHUNK_SIZE {
let x = rel_x as i16 + cwx;
let y = rel_y as i16 + cwy;
// Generate the terrain
let generator: &mut dyn Generator = match world_type {
GeneratorType::Flat => &mut self.flat_generator,
GeneratorType::Water => &mut self.water_generator,
GeneratorType::Alien => &mut self.alien_generator,
GeneratorType::Default => &mut self.hills_generator,
};
let mut blocks = generator.generate(x, y);
// Place trees and points of interest
self.tree_objects.place(x, y, &mut blocks, generator);
self.poi_objects.place(x, y, &mut blocks, generator);
// Copy the results into the chunk column
for cz in 0..WORLD_HEIGHT_CHUNKS {
let chunk = column.get_mut(cz).unwrap();
let chunk_bottom_z = cz * CHUNK_SIZE;
for rel_z in 0..CHUNK_SIZE {
chunk.set_block(rel_x, rel_y, rel_z, blocks[chunk_bottom_z + rel_z]);
}
}
}
}
column
}
}
| 37.02439 | 93 | 0.572464 |
8a300a1647df0861dcbdd99db6f3032148c16cc8
| 10,876 |
// The Gecko Bridge service.
use super::state::*;
use crate::generated::common::*;
use crate::generated::{self, service::*};
use common::core::BaseMessage;
use common::traits::{
OriginAttributes, Service, SessionSupport, Shared, SharedSessionContext, TrackerId,
};
use contacts_service::generated::common::SimContactInfo;
use contacts_service::service::ContactsService;
use log::{error, info};
use parking_lot::Mutex;
use std::collections::HashSet;
use std::sync::Arc;
use std::thread;
lazy_static! {
pub(crate) static ref PROXY_TRACKER: Arc<Mutex<GeckoBridgeProxyTracker>> =
Arc::new(Mutex::new(GeckoBridgeProxyTracker::default()));
}
macro_rules! getDelegateWrapper {
($struct_name: ident, $fn_name: ident, $delegate: ident, $ret_type: ty) => {
impl $struct_name {
fn $fn_name(&mut self, delegate: ObjectRef) -> Option<$ret_type> {
match self.get_proxy_tracker().lock().get(&delegate) {
Some(GeckoBridgeProxy::$delegate(delegate)) => Some(delegate.clone()),
_ => None,
}
}
}
};
}
pub struct GeckoBridgeService {
id: TrackerId,
state: Shared<GeckoBridgeState>,
only_register_token: bool,
}
getDelegateWrapper!(
GeckoBridgeService,
get_app_service_delegate,
AppsServiceDelegate,
AppsServiceDelegateProxy
);
getDelegateWrapper!(
GeckoBridgeService,
get_power_manager_delegate,
PowerManagerDelegate,
PowerManagerDelegateProxy
);
getDelegateWrapper!(
GeckoBridgeService,
get_mobile_manager_delegate,
MobileManagerDelegate,
MobileManagerDelegateProxy
);
getDelegateWrapper!(
GeckoBridgeService,
get_network_manager_delegate,
NetworkManagerDelegate,
NetworkManagerDelegateProxy
);
getDelegateWrapper!(
GeckoBridgeService,
get_preference_delegate,
PreferenceDelegate,
PreferenceDelegateProxy
);
impl GeckoBridge for GeckoBridgeService {
fn get_proxy_tracker(&mut self) -> Arc<Mutex<GeckoBridgeProxyTracker>> {
let a = &*PROXY_TRACKER;
a.clone()
}
}
impl GeckoFeaturesMethods for GeckoBridgeService {
fn bool_pref_changed(
&mut self,
responder: &GeckoFeaturesBoolPrefChangedResponder,
pref_name: String,
value: bool,
) {
if self.only_register_token {
responder.reject();
return;
}
self.state.lock().set_bool_pref(pref_name, value);
responder.resolve();
}
fn char_pref_changed(
&mut self,
responder: &GeckoFeaturesCharPrefChangedResponder,
pref_name: String,
value: String,
) {
if self.only_register_token {
responder.reject();
return;
}
self.state.lock().set_char_pref(pref_name, value);
responder.resolve();
}
fn int_pref_changed(
&mut self,
responder: &GeckoFeaturesIntPrefChangedResponder,
pref_name: String,
value: i64,
) {
if self.only_register_token {
responder.reject();
return;
}
self.state.lock().set_int_pref(pref_name, value);
responder.resolve();
}
fn set_power_manager_delegate(
&mut self,
responder: &GeckoFeaturesSetPowerManagerDelegateResponder,
delegate: ObjectRef,
) {
if self.only_register_token {
responder.reject();
return;
}
// Get the proxy and update our state.
if let Some(power_delegate) = self.get_power_manager_delegate(delegate) {
self.state.lock().set_powermanager_delegate(power_delegate);
responder.resolve();
} else {
responder.reject();
}
}
fn set_apps_service_delegate(
&mut self,
responder: &GeckoFeaturesSetAppsServiceDelegateResponder,
delegate: ObjectRef,
) {
if self.only_register_token {
responder.reject();
return;
}
// Get the proxy and update our state.
if let Some(app_delegate) = self.get_app_service_delegate(delegate) {
self.state.lock().set_apps_service_delegate(app_delegate);
responder.resolve();
} else {
responder.reject();
}
}
fn set_mobile_manager_delegate(
&mut self,
responder: &GeckoFeaturesSetMobileManagerDelegateResponder,
delegate: ObjectRef,
) {
if self.only_register_token {
responder.reject();
return;
}
// Get the proxy and update our state.
if let Some(mobile_delegate) = self.get_mobile_manager_delegate(delegate) {
self.state
.lock()
.set_mobilemanager_delegate(mobile_delegate);
responder.resolve();
} else {
responder.reject();
}
}
fn set_network_manager_delegate(
&mut self,
responder: &GeckoFeaturesSetNetworkManagerDelegateResponder,
delegate: ObjectRef,
) {
if self.only_register_token {
responder.reject();
return;
}
// Get the proxy and update our state.
if let Some(network_delegate) = self.get_network_manager_delegate(delegate) {
self.state
.lock()
.set_networkmanager_delegate(network_delegate);
responder.resolve();
} else {
responder.reject();
}
}
fn set_preference_delegate(
&mut self,
responder: &GeckoFeaturesSetPreferenceDelegateResponder,
delegate: ObjectRef,
) {
if self.only_register_token {
responder.reject();
return;
}
// Get the proxy and update our state.
if let Some(pref_delegate) = self.get_preference_delegate(delegate) {
self.state.lock().set_preference_delegate(pref_delegate);
responder.resolve();
} else {
responder.reject();
}
}
fn register_token(
&mut self,
responder: &GeckoFeaturesRegisterTokenResponder,
token: String,
url: String,
permissions: Option<Vec<String>>,
) {
let permissions_set = match permissions {
Some(permissions) => {
// Turn the Vec<String> into a HashSet<String>
let mut set = HashSet::new();
for perm in permissions {
set.insert(perm);
}
set
}
None => HashSet::new(),
};
let origin_attributes = OriginAttributes::new(&url, permissions_set);
let shared_state = self.state.clone();
let res = responder.clone();
let _ = thread::Builder::new()
.name("register_token".to_string())
.spawn(move || {
if shared_state
.lock()
.register_token(&token, origin_attributes)
{
res.resolve();
} else {
res.reject();
}
});
}
fn import_sim_contacts(
&mut self,
responder: &GeckoFeaturesImportSimContactsResponder,
sim_contacts: Option<Vec<generated::common::SimContactInfo>>,
) {
if self.only_register_token {
responder.reject();
return;
}
let sim_contact_info = match sim_contacts {
Some(sim_contacts) => {
let sim_contact_info = sim_contacts
.iter()
.map(|x| SimContactInfo {
id: x.id.to_string(),
tel: x.tel.to_string(),
email: x.email.to_string(),
name: x.name.to_string(),
category: x.category.to_string(),
})
.collect();
sim_contact_info
}
None => Vec::new(),
};
let contact_state = ContactsService::shared_state();
let mut contacts = contact_state.lock();
match contacts.db.import_sim_contacts(&sim_contact_info) {
Ok(()) => responder.resolve(),
Err(err) => {
error!("import_sim_contact error is {}", err);
responder.reject()
}
}
}
}
impl Service<GeckoBridgeService> for GeckoBridgeService {
// Shared among instances.
type State = GeckoBridgeState;
fn shared_state() -> Shared<Self::State> {
let a = &*GECKO_BRIDGE_SHARED_STATE;
a.clone()
}
fn create(
attrs: &OriginAttributes,
_context: SharedSessionContext,
state: Shared<Self::State>,
helper: SessionSupport,
) -> Result<GeckoBridgeService, String> {
info!("GeckoBridgeService::create");
// Only connections from the UDS socket are permitted.
if attrs.identity() != "uds" {
error!("Only Gecko can get an instance of the GeckoBridge service!");
return Err("Non Gecko client".into());
}
// We only allow a single instance of this service to change delegates.
// Content processes that will connect afterwards can still use it
// to register tokens.
let only_register_token = state.lock().is_ready();
let service_id = helper.session_tracker_id().service();
Ok(GeckoBridgeService {
id: service_id,
state,
only_register_token,
})
}
// Returns a human readable version of the request.
fn format_request(&mut self, _transport: &SessionSupport, message: &BaseMessage) -> String {
let req: Result<GeckoBridgeFromClient, common::BincodeError> =
common::deserialize_bincode(&message.content);
match req {
Ok(req) => format!("SettingsService request: {:?}", req),
Err(err) => format!("Unable to format SettingsService request: {:?}", err),
}
}
// Processes a request coming from the Session.
fn on_request(&mut self, transport: &SessionSupport, message: &BaseMessage) {
self.dispatch_request(transport, message);
}
fn release_object(&mut self, object_id: u32) -> bool {
info!("releasing object {}", object_id);
self.get_proxy_tracker()
.lock()
.remove(&object_id.into())
.is_some()
}
}
impl Drop for GeckoBridgeService {
fn drop(&mut self) {
info!("Dropping GeckoBridge Service #{}", self.id);
// Reset the bridge state only if the instance exposing the
// delegates is dropped.
if !self.only_register_token {
self.state.lock().reset();
}
}
}
| 29.715847 | 96 | 0.578705 |
fe6a305c57ddbd757543f16a8d8fb4eda49f850c
| 5,377 |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{ensure, Result};
use bcs_ext::Sample;
use network_api::messages::{CompactBlockMessage, TransactionsMessage};
use serde::de::DeserializeOwned;
use serde::Serialize;
use starcoin_crypto::hash::PlainCryptoHash;
use starcoin_crypto::HashValue;
use starcoin_logger::prelude::*;
use starcoin_types::block::{Block, BlockHeader, BlockInfo};
use starcoin_types::cmpact_block::CompactBlock;
use starcoin_types::startup_info::ChainStatus;
use starcoin_vm_types::block_metadata::BlockMetadata;
use starcoin_vm_types::transaction::{
Module, Package, RawUserTransaction, Script, ScriptFunction, SignedUserTransaction,
TransactionInfo,
};
use std::any::type_name;
use std::path::PathBuf;
/// This test ensure all base type serialize and hash is compatible with previous version.
#[stest::test]
fn check_types() {
//Transaction
check_data::<Script>().unwrap();
check_data::<Module>().unwrap();
check_data::<ScriptFunction>().unwrap();
check_data_and_hash::<Package>().unwrap();
check_data_and_hash::<RawUserTransaction>().unwrap();
check_data_and_hash::<SignedUserTransaction>().unwrap();
check_data_and_hash::<BlockMetadata>().unwrap();
check_data_and_hash::<TransactionInfo>().unwrap();
//Block
check_data_and_hash::<BlockHeader>().unwrap();
check_data_and_hash::<Block>().unwrap();
check_data_and_hash::<BlockInfo>().unwrap();
//Network
check_data::<ChainStatus>().unwrap();
check_data::<CompactBlock>().unwrap();
check_data::<TransactionsMessage>().unwrap();
check_data::<CompactBlockMessage>().unwrap();
}
const DATA_DIR: &str = "data";
fn basic_path<T>() -> PathBuf {
let name = type_name::<T>().split("::").last().unwrap();
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(DATA_DIR);
path.push(name);
path
}
fn data_file<T>() -> PathBuf {
let mut path = basic_path::<T>();
path.push("data");
path
}
fn hash_file<T>() -> PathBuf {
let mut path = basic_path::<T>();
path.push("hash");
path
}
fn json_file<T>() -> PathBuf {
let mut path = basic_path::<T>();
path.push("json");
path
}
fn read_and_check_data<T: Serialize + DeserializeOwned + PartialEq>() -> Result<Option<T>> {
let data_path = data_file::<T>();
let json_path = json_file::<T>();
if data_path.exists() && json_path.exists() {
debug!("Read data from {:?}", data_path);
let data = hex::decode(std::fs::read_to_string(data_path)?.as_str())?;
let data_t = bcs_ext::from_bytes::<T>(data.as_slice())?;
let json_t = serde_json::from_str::<T>(std::fs::read_to_string(json_path)?.as_str())?;
ensure!(
data_t == json_t,
"{}'s bcs and json serialize data is not equals.",
type_name::<T>()
);
let new_data = bcs_ext::to_bytes(&data_t)?;
ensure!(
data == new_data,
"Check type {}'s serialize/deserialize fail, expect:{}, got: {}",
type_name::<T>(),
hex::encode(data),
hex::encode(new_data)
);
Ok(Some(data_t))
} else {
Ok(None)
}
}
fn write_data<T: Serialize>(t: &T) -> Result<()> {
let data_path = data_file::<T>();
let json_path = json_file::<T>();
debug!("Write data to {:?}", data_path);
let dir = data_path.parent().unwrap();
if !dir.exists() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(data_path, hex::encode(bcs_ext::to_bytes(t)?))?;
std::fs::write(json_path, serde_json::to_string_pretty(t)?)?;
Ok(())
}
fn read_hash<T>() -> Result<Option<HashValue>> {
let path = hash_file::<T>();
if path.exists() {
debug!("Read hash from {:?}", path);
let data = HashValue::from_slice(
hex::decode(std::fs::read_to_string(path)?.as_str())?.as_slice(),
)?;
Ok(Some(data))
} else {
Ok(None)
}
}
fn write_hash<T>(hash: HashValue) -> Result<()> {
let path = hash_file::<T>();
debug!("Write hash to {:?}", path);
let dir = path.parent().unwrap();
if !dir.exists() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(path, hex::encode(hash.to_vec()))?;
Ok(())
}
fn check_data_and_hash<T: Sample + Serialize + DeserializeOwned + PlainCryptoHash + PartialEq>(
) -> Result<()> {
let t = check_data::<T>()?;
check_hash(t)?;
Ok(())
}
fn check_hash<T: PlainCryptoHash>(t: T) -> Result<()> {
let type_name = type_name::<T>();
let new_hash = t.crypto_hash();
if let Some(hash) = read_hash::<T>()? {
ensure!(
hash == new_hash,
"Check type {}'s crypto hash fail, expect:{}, got: {}",
type_name,
hash,
new_hash
);
} else {
write_hash::<T>(new_hash)?;
}
Ok(())
}
fn check_data<T: Sample + Serialize + DeserializeOwned + PartialEq>() -> Result<T> {
let type_name = type_name::<T>();
ensure!(
T::sample() == T::sample(),
"Type {}'s sample return result is not stable.",
type_name
);
if let Some(t) = read_and_check_data::<T>()? {
info!("Check {} ok", type_name);
Ok(t)
} else {
let t = T::sample();
write_data(&t)?;
Ok(t)
}
}
| 29.543956 | 95 | 0.598103 |
4890617cd8c0d2a0f04919fca7f7520a6b79fb1a
| 1,155 |
use super::fourcc::{FourCC, ReadFourCC};
use byteorder::{ReadBytesExt, LittleEndian};
use std::io::{Cursor, Error, Read};
pub struct ListFormItem {
pub signature : FourCC,
pub contents : Vec<u8>
}
/// A helper that will accept a LIST chunk as a [u8]
/// and give you back each segment
///
pub fn collect_list_form(list_contents :& [u8]) -> Result<Vec<ListFormItem>, Error> {
let mut cursor = Cursor::new(list_contents);
let mut remain = list_contents.len();
let _ = cursor.read_fourcc()?; // skip signature
remain -= 4;
let mut retval : Vec<ListFormItem> = vec![];
while remain > 0 {
let this_sig = cursor.read_fourcc()?;
let this_size = cursor.read_u32::<LittleEndian>()? as usize;
remain -= 8;
let mut content_buf = vec![0u8; this_size];
cursor.read_exact(&mut content_buf)?;
remain -= this_size;
retval.push( ListFormItem { signature : this_sig, contents : content_buf } );
if this_size % 2 == 1 {
cursor.read_u8()?;
//panic!("Got this far!");
remain -= 1;
}
}
Ok( retval )
}
| 28.875 | 85 | 0.592208 |
11a5668473c03ae97832b82fe11ea1be8143890a
| 1,268 |
check_type!(Example => value : Option<Box<Inner>>);
check_type!(Example => value_null : Option<Box<Inner>>);
check_type!(Example => value_required : Box<Inner>);
check_type!(Example => create(&mut planus::Builder, Inner, Inner, Inner) : planus::Offset<Example>);
check_type!(+['a, 'b, 'c] Example => create(&mut planus::Builder, &'a Inner, &'b Inner, &'c Inner) : planus::Offset<Example>);
check_type!(Example => create(&mut planus::Builder, Box<Inner>, Box<Inner>, Box<Inner>) : planus::Offset<Example>);
check_type!(Example => create(&mut planus::Builder, Option<Box<Inner>>, Option<Box<Inner>>, Inner) : planus::Offset<Example>);
check_type!(Example => create(&mut planus::Builder, Option<Inner>, Option<Inner>, Inner) : planus::Offset<Example>);
check_type!(Example => create(&mut planus::Builder, (), (), Inner) : planus::Offset<Example>);
check_type!(+['a] ExampleRef<'a> => &self.value() : planus::Result<Option<InnerRef<'a>>>);
check_type!(+['a] ExampleRef<'a> => &self.value_null() : planus::Result<Option<InnerRef<'a>>>);
check_type!(+['a] ExampleRef<'a> => &self.value_required() : planus::Result<InnerRef<'a>>);
check_type!(+['a] ExampleRef<'a> => impl planus::ReadAsRoot<'a>);
assert_traits!(Example: !Copy + Clone + Debug + Eq + Ord + Hash + Default);
| 74.588235 | 126 | 0.681388 |
1d6c471032bd8efd9c03bc4dde82660bb361513d
| 19,019 |
//! Lookup hir elements using positions in the source code. This is a lossy
//! transformation: in general, a single source might correspond to several
//! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on
//! modules.
//!
//! So, this modules should not be used during hir construction, it exists
//! purely for "IDE needs".
use std::{iter::once, sync::Arc};
use hir_def::{
body::{
scope::{ExprScopes, ScopeId},
Body, BodySourceMap,
},
expr::{ExprId, Pat, PatId},
resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
AsMacroCall, DefWithBodyId, FieldId, LocalFieldId, VariantId,
};
use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
use hir_ty::{
expr::{record_literal_missing_fields, record_pattern_missing_fields},
InferenceResult, Substs, Ty,
};
use ra_syntax::{
ast::{self, AstNode},
SyntaxNode, TextRange, TextSize,
};
use crate::{
db::HirDatabase, semantics::PathResolution, Adt, Const, EnumVariant, Field, Function, Local,
MacroDef, ModPath, ModuleDef, Path, PathKind, Static, Struct, Trait, Type, TypeAlias,
TypeParam,
};
use ra_db::CrateId;
/// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
/// original source files. It should not be used inside the HIR itself.
#[derive(Debug)]
pub(crate) struct SourceAnalyzer {
file_id: HirFileId,
pub(crate) resolver: Resolver,
body: Option<Arc<Body>>,
body_source_map: Option<Arc<BodySourceMap>>,
infer: Option<Arc<InferenceResult>>,
scopes: Option<Arc<ExprScopes>>,
}
impl SourceAnalyzer {
pub(crate) fn new_for_body(
db: &dyn HirDatabase,
def: DefWithBodyId,
node: InFile<&SyntaxNode>,
offset: Option<TextSize>,
) -> SourceAnalyzer {
let (body, source_map) = db.body_with_source_map(def);
let scopes = db.expr_scopes(def);
let scope = match offset {
None => scope_for(&scopes, &source_map, node),
Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)),
};
let resolver = resolver_for_scope(db.upcast(), def, scope);
SourceAnalyzer {
resolver,
body: Some(body),
body_source_map: Some(source_map),
infer: Some(db.infer(def)),
scopes: Some(scopes),
file_id: node.file_id,
}
}
pub(crate) fn new_for_resolver(
resolver: Resolver,
node: InFile<&SyntaxNode>,
) -> SourceAnalyzer {
SourceAnalyzer {
resolver,
body: None,
body_source_map: None,
infer: None,
scopes: None,
file_id: node.file_id,
}
}
fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
let src = match expr {
ast::Expr::MacroCall(call) => {
self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
}
_ => InFile::new(self.file_id, expr.clone()),
};
let sm = self.body_source_map.as_ref()?;
sm.node_expr(src.as_ref())
}
fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
// FIXME: macros, see `expr_id`
let src = InFile { file_id: self.file_id, value: pat };
self.body_source_map.as_ref()?.node_pat(src)
}
fn expand_expr(
&self,
db: &dyn HirDatabase,
expr: InFile<ast::MacroCall>,
) -> Option<InFile<ast::Expr>> {
let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
let expanded = db.parse_or_expand(macro_file)?;
let res = match ast::MacroCall::cast(expanded.clone()) {
Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
_ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
};
Some(res)
}
pub(crate) fn type_of(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<Type> {
let expr_id = self.expr_id(db, expr)?;
let ty = self.infer.as_ref()?[expr_id].clone();
Type::new_with_resolver(db, &self.resolver, ty)
}
pub(crate) fn type_of_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> {
let pat_id = self.pat_id(pat)?;
let ty = self.infer.as_ref()?[pat_id].clone();
Type::new_with_resolver(db, &self.resolver, ty)
}
pub(crate) fn resolve_method_call(
&self,
db: &dyn HirDatabase,
call: &ast::MethodCallExpr,
) -> Option<Function> {
let expr_id = self.expr_id(db, &call.clone().into())?;
self.infer.as_ref()?.method_resolution(expr_id).map(Function::from)
}
pub(crate) fn resolve_field(
&self,
db: &dyn HirDatabase,
field: &ast::FieldExpr,
) -> Option<Field> {
let expr_id = self.expr_id(db, &field.clone().into())?;
self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
}
pub(crate) fn resolve_record_field(
&self,
db: &dyn HirDatabase,
field: &ast::RecordField,
) -> Option<(Field, Option<Local>)> {
let expr = field.expr()?;
let expr_id = self.expr_id(db, &expr)?;
let local = if field.name_ref().is_some() {
None
} else {
let local_name = field.field_name()?.as_name();
let path = ModPath::from_segments(PathKind::Plain, once(local_name));
match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
Some(ValueNs::LocalBinding(pat_id)) => {
Some(Local { pat_id, parent: self.resolver.body_owner()? })
}
_ => None,
}
};
let struct_field = self.infer.as_ref()?.record_field_resolution(expr_id)?;
Some((struct_field.into(), local))
}
pub(crate) fn resolve_record_field_pat(
&self,
_db: &dyn HirDatabase,
field: &ast::RecordFieldPat,
) -> Option<Field> {
let pat_id = self.pat_id(&field.pat()?)?;
let struct_field = self.infer.as_ref()?.record_field_pat_resolution(pat_id)?;
Some(struct_field.into())
}
pub(crate) fn resolve_macro_call(
&self,
db: &dyn HirDatabase,
macro_call: InFile<&ast::MacroCall>,
) -> Option<MacroDef> {
let hygiene = Hygiene::new(db.upcast(), macro_call.file_id);
let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
}
pub(crate) fn resolve_bind_pat_to_const(
&self,
db: &dyn HirDatabase,
pat: &ast::BindPat,
) -> Option<ModuleDef> {
let pat_id = self.pat_id(&pat.clone().into())?;
let body = self.body.as_ref()?;
let path = match &body[pat_id] {
Pat::Path(path) => path,
_ => return None,
};
let res = resolve_hir_path(db, &self.resolver, &path)?;
match res {
PathResolution::Def(def) => Some(def),
_ => None,
}
}
pub(crate) fn resolve_path(
&self,
db: &dyn HirDatabase,
path: &ast::Path,
) -> Option<PathResolution> {
if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
let expr_id = self.expr_id(db, &path_expr.into())?;
if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
return Some(PathResolution::AssocItem(assoc.into()));
}
if let Some(VariantId::EnumVariantId(variant)) =
self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
{
return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into())));
}
}
if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
let pat_id = self.pat_id(&path_pat.into())?;
if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
return Some(PathResolution::AssocItem(assoc.into()));
}
if let Some(VariantId::EnumVariantId(variant)) =
self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
{
return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into())));
}
}
if let Some(rec_lit) = path.syntax().parent().and_then(ast::RecordLit::cast) {
let expr_id = self.expr_id(db, &rec_lit.into())?;
if let Some(VariantId::EnumVariantId(variant)) =
self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
{
return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into())));
}
}
if let Some(rec_pat) = path.syntax().parent().and_then(ast::RecordPat::cast) {
let pat_id = self.pat_id(&rec_pat.into())?;
if let Some(VariantId::EnumVariantId(variant)) =
self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
{
return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into())));
}
}
// This must be a normal source file rather than macro file.
let hir_path =
crate::Path::from_src(path.clone(), &Hygiene::new(db.upcast(), self.file_id))?;
// Case where path is a qualifier of another path, e.g. foo::bar::Baz where we
// trying to resolve foo::bar.
if let Some(outer_path) = path.syntax().parent().and_then(ast::Path::cast) {
if let Some(qualifier) = outer_path.qualifier() {
if path == &qualifier {
return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
}
}
}
resolve_hir_path(db, &self.resolver, &hir_path)
}
pub(crate) fn record_literal_missing_fields(
&self,
db: &dyn HirDatabase,
literal: &ast::RecordLit,
) -> Option<Vec<(Field, Type)>> {
let krate = self.resolver.krate()?;
let body = self.body.as_ref()?;
let infer = self.infer.as_ref()?;
let expr_id = self.expr_id(db, &literal.clone().into())?;
let substs = match &infer.type_of_expr[expr_id] {
Ty::Apply(a_ty) => &a_ty.parameters,
_ => return None,
};
let (variant, missing_fields, _exhaustive) =
record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
let res = self.missing_fields(db, krate, substs, variant, missing_fields);
Some(res)
}
pub(crate) fn record_pattern_missing_fields(
&self,
db: &dyn HirDatabase,
pattern: &ast::RecordPat,
) -> Option<Vec<(Field, Type)>> {
let krate = self.resolver.krate()?;
let body = self.body.as_ref()?;
let infer = self.infer.as_ref()?;
let pat_id = self.pat_id(&pattern.clone().into())?;
let substs = match &infer.type_of_pat[pat_id] {
Ty::Apply(a_ty) => &a_ty.parameters,
_ => return None,
};
let (variant, missing_fields, _exhaustive) =
record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
let res = self.missing_fields(db, krate, substs, variant, missing_fields);
Some(res)
}
fn missing_fields(
&self,
db: &dyn HirDatabase,
krate: CrateId,
substs: &Substs,
variant: VariantId,
missing_fields: Vec<LocalFieldId>,
) -> Vec<(Field, Type)> {
let field_types = db.field_types(variant);
missing_fields
.into_iter()
.map(|local_id| {
let field = FieldId { parent: variant, local_id };
let ty = field_types[local_id].clone().subst(substs);
(field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
})
.collect()
}
pub(crate) fn expand(
&self,
db: &dyn HirDatabase,
macro_call: InFile<&ast::MacroCall>,
) -> Option<HirFileId> {
let krate = self.resolver.krate()?;
let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
self.resolver.resolve_path_as_macro(db.upcast(), &path)
})?;
Some(macro_call_id.as_file())
}
pub(crate) fn resolve_variant(
&self,
db: &dyn HirDatabase,
record_lit: ast::RecordLit,
) -> Option<VariantId> {
let infer = self.infer.as_ref()?;
let expr_id = self.expr_id(db, &record_lit.into())?;
infer.variant_resolution_for_expr(expr_id)
}
}
fn scope_for(
scopes: &ExprScopes,
source_map: &BodySourceMap,
node: InFile<&SyntaxNode>,
) -> Option<ScopeId> {
node.value
.ancestors()
.filter_map(ast::Expr::cast)
.filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
.find_map(|it| scopes.scope_for(it))
}
fn scope_for_offset(
db: &dyn HirDatabase,
scopes: &ExprScopes,
source_map: &BodySourceMap,
offset: InFile<TextSize>,
) -> Option<ScopeId> {
scopes
.scope_by_expr()
.iter()
.filter_map(|(id, scope)| {
let source = source_map.expr_syntax(*id).ok()?;
// FIXME: correctly handle macro expansion
if source.file_id != offset.file_id {
return None;
}
let root = source.file_syntax(db.upcast());
let node = source.value.to_node(&root);
Some((node.syntax().text_range(), scope))
})
// find containing scope
.min_by_key(|(expr_range, _scope)| {
(
!(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
expr_range.len(),
)
})
.map(|(expr_range, scope)| {
adjust(db, scopes, source_map, expr_range, offset.file_id, offset.value)
.unwrap_or(*scope)
})
}
// XXX: during completion, cursor might be outside of any particular
// expression. Try to figure out the correct scope...
fn adjust(
db: &dyn HirDatabase,
scopes: &ExprScopes,
source_map: &BodySourceMap,
expr_range: TextRange,
file_id: HirFileId,
offset: TextSize,
) -> Option<ScopeId> {
let child_scopes = scopes
.scope_by_expr()
.iter()
.filter_map(|(id, scope)| {
let source = source_map.expr_syntax(*id).ok()?;
// FIXME: correctly handle macro expansion
if source.file_id != file_id {
return None;
}
let root = source.file_syntax(db.upcast());
let node = source.value.to_node(&root);
Some((node.syntax().text_range(), scope))
})
.filter(|&(range, _)| {
range.start() <= offset && expr_range.contains_range(range) && range != expr_range
});
child_scopes
.max_by(|&(r1, _), &(r2, _)| {
if r1.contains_range(r2) {
std::cmp::Ordering::Greater
} else if r2.contains_range(r1) {
std::cmp::Ordering::Less
} else {
r1.start().cmp(&r2.start())
}
})
.map(|(_ptr, scope)| *scope)
}
pub(crate) fn resolve_hir_path(
db: &dyn HirDatabase,
resolver: &Resolver,
path: &crate::Path,
) -> Option<PathResolution> {
let types =
resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
PathResolution::Def(Adt::from(it).into())
}
TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
});
let body_owner = resolver.body_owner();
let values =
resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
let res = match val {
ValueNs::LocalBinding(pat_id) => {
let var = Local { parent: body_owner?.into(), pat_id };
PathResolution::Local(var)
}
ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
};
Some(res)
});
let items = resolver
.resolve_module_path_in_items(db.upcast(), path.mod_path())
.take_types()
.map(|it| PathResolution::Def(it.into()));
types.or(values).or(items).or_else(|| {
resolver
.resolve_path_as_macro(db.upcast(), path.mod_path())
.map(|def| PathResolution::Macro(def.into()))
})
}
/// Resolves a path where we know it is a qualifier of another path.
///
/// For example, if we have:
/// ```
/// mod my {
/// pub mod foo {
/// struct Bar;
/// }
///
/// pub fn foo() {}
/// }
/// ```
/// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
pub(crate) fn resolve_hir_path_qualifier(
db: &dyn HirDatabase,
resolver: &Resolver,
path: &crate::Path,
) -> Option<PathResolution> {
let items = resolver
.resolve_module_path_in_items(db.upcast(), path.mod_path())
.take_types()
.map(|it| PathResolution::Def(it.into()));
if items.is_some() {
return items;
}
resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
})
}
| 36.089184 | 97 | 0.574688 |
1448657e0b09a4033149ad6ebb4768e02bf820bd
| 22,354 |
use crate::{
backend::renderer::{utils::draw_surface_tree, ImportAll, Renderer},
desktop::{utils::*, PopupManager, Space},
utils::{user_data::UserDataMap, Logical, Point, Rectangle},
wayland::{
compositor::{with_states, with_surface_tree_downward, TraversalAction},
output::{Inner as OutputInner, Output},
shell::wlr_layer::{
Anchor, ExclusiveZone, KeyboardInteractivity, Layer as WlrLayer, LayerSurface as WlrLayerSurface,
LayerSurfaceCachedState,
},
},
};
use indexmap::IndexSet;
use wayland_server::protocol::wl_surface::WlSurface;
use std::{
cell::{RefCell, RefMut},
hash::{Hash, Hasher},
rc::Rc,
sync::{Arc, Mutex, Weak},
};
use super::WindowSurfaceType;
crate::utils::ids::id_gen!(next_layer_id, LAYER_ID, LAYER_IDS);
/// Map of [`LayerSurface`]s on an [`Output`]
#[derive(Debug)]
pub struct LayerMap {
layers: IndexSet<LayerSurface>,
output: Weak<(Mutex<OutputInner>, wayland_server::UserDataMap)>,
zone: Rectangle<i32, Logical>,
// surfaces for tracking enter and leave events
surfaces: Vec<WlSurface>,
logger: ::slog::Logger,
}
/// Retrieve a [`LayerMap`] for a given [`Output`].
///
/// If none existed before a new empty [`LayerMap`] is attached
/// to the output and returned on subsequent calls.
///
/// Note: This function internally uses a [`RefCell`] per
/// [`Output`] as exposed by its return type. Therefor
/// trying to hold on to multiple references of a [`LayerMap`]
/// of the same output using this function *will* result in a panic.
pub fn layer_map_for_output(o: &Output) -> RefMut<'_, LayerMap> {
let userdata = o.user_data();
let weak_output = Arc::downgrade(&o.inner);
userdata.insert_if_missing(|| {
RefCell::new(LayerMap {
layers: IndexSet::new(),
output: weak_output,
zone: Rectangle::from_loc_and_size(
(0, 0),
o.current_mode()
.map(|mode| mode.size.to_logical(o.current_scale()))
.unwrap_or_else(|| (0, 0).into()),
),
surfaces: Vec::new(),
logger: (*o.inner.0.lock().unwrap())
.log
.new(slog::o!("smithay_module" => "layer_map")),
})
});
userdata.get::<RefCell<LayerMap>>().unwrap().borrow_mut()
}
#[derive(Debug, thiserror::Error)]
pub enum LayerError {
#[error("Layer is already mapped to a different map")]
AlreadyMapped,
}
impl LayerMap {
/// Map a [`LayerSurface`] to this [`LayerMap`].
pub fn map_layer(&mut self, layer: &LayerSurface) -> Result<(), LayerError> {
if !self.layers.contains(layer) {
if layer
.0
.userdata
.get::<LayerUserdata>()
.map(|s| s.borrow().is_some())
.unwrap_or(false)
{
return Err(LayerError::AlreadyMapped);
}
self.layers.insert(layer.clone());
self.arrange();
}
Ok(())
}
/// Remove a [`LayerSurface`] from this [`LayerMap`].
pub fn unmap_layer(&mut self, layer: &LayerSurface) {
if self.layers.shift_remove(layer) {
let _ = layer.user_data().get::<LayerUserdata>().take();
self.arrange();
}
if let (Some(output), Some(surface)) = (self.output(), layer.get_surface()) {
with_surface_tree_downward(
surface,
(),
|_, _, _| TraversalAction::DoChildren(()),
|wl_surface, _, _| {
output_leave(&output, &mut self.surfaces, wl_surface, &self.logger);
},
|_, _, _| true,
);
for (popup, _) in PopupManager::popups_for_surface(surface)
.ok()
.into_iter()
.flatten()
{
if let Some(surface) = popup.get_surface() {
with_surface_tree_downward(
surface,
(),
|_, _, _| TraversalAction::DoChildren(()),
|wl_surface, _, _| {
output_leave(&output, &mut self.surfaces, wl_surface, &self.logger);
},
|_, _, _| true,
)
}
}
}
}
/// Return the area of this output, that is not exclusive to any [`LayerSurface`]s.
pub fn non_exclusive_zone(&self) -> Rectangle<i32, Logical> {
self.zone
}
/// Returns the geometry of a given mapped [`LayerSurface`].
///
/// If the surface was not previously mapped onto this layer map,
/// this function return `None`.
pub fn layer_geometry(&self, layer: &LayerSurface) -> Option<Rectangle<i32, Logical>> {
if !self.layers.contains(layer) {
return None;
}
let mut bbox = layer.bbox_with_popups();
let state = layer_state(layer);
bbox.loc += state.location;
Some(bbox)
}
/// Returns a [`LayerSurface`] under a given point and on a given layer, if any.
pub fn layer_under<P: Into<Point<f64, Logical>>>(
&self,
layer: WlrLayer,
point: P,
) -> Option<&LayerSurface> {
let point = point.into();
self.layers_on(layer).rev().find(|l| {
let bbox = self.layer_geometry(l).unwrap();
bbox.to_f64().contains(point)
})
}
/// Iterator over all [`LayerSurface`]s currently mapped.
pub fn layers(&self) -> impl DoubleEndedIterator<Item = &LayerSurface> {
self.layers.iter()
}
/// Iterator over all [`LayerSurface`]s currently mapped on a given layer.
pub fn layers_on(&self, layer: WlrLayer) -> impl DoubleEndedIterator<Item = &LayerSurface> {
self.layers
.iter()
.filter(move |l| l.layer().map(|l| l == layer).unwrap_or(false))
}
/// Returns the [`LayerSurface`] matching a given [`WlSurface`], if any.
pub fn layer_for_surface(&self, surface: &WlSurface) -> Option<&LayerSurface> {
if !surface.as_ref().is_alive() {
return None;
}
self.layers
.iter()
.find(|w| w.get_surface().map(|x| x == surface).unwrap_or(false))
}
/// Force re-arranging the layer surfaces, e.g. when the output size changes.
///
/// Note: Mapping or unmapping a layer surface will automatically cause a re-arrangement.
pub fn arrange(&mut self) {
if let Some(output) = self.output() {
let output_rect = Rectangle::from_loc_and_size(
(0, 0),
output
.current_mode()
.map(|mode| mode.size.to_logical(output.current_scale()))
.unwrap_or_else(|| (0, 0).into()),
);
let mut zone = output_rect;
slog::trace!(self.logger, "Arranging layers into {:?}", output_rect.size);
for layer in self.layers.iter() {
let surface = if let Some(surface) = layer.get_surface() {
surface
} else {
continue;
};
let logger_ref = &self.logger;
let surfaces_ref = &mut self.surfaces;
with_surface_tree_downward(
surface,
(),
|_, _, _| TraversalAction::DoChildren(()),
|wl_surface, _, _| {
output_enter(&output, surfaces_ref, wl_surface, logger_ref);
},
|_, _, _| true,
);
for (popup, _) in PopupManager::popups_for_surface(surface)
.ok()
.into_iter()
.flatten()
{
if let Some(surface) = popup.get_surface() {
with_surface_tree_downward(
surface,
(),
|_, _, _| TraversalAction::DoChildren(()),
|wl_surface, _, _| {
output_enter(&output, surfaces_ref, wl_surface, logger_ref);
},
|_, _, _| true,
)
}
}
let data = with_states(surface, |states| {
*states.cached_state.current::<LayerSurfaceCachedState>()
})
.unwrap();
let source = match data.exclusive_zone {
ExclusiveZone::Neutral | ExclusiveZone::Exclusive(_) => &zone,
ExclusiveZone::DontCare => &output_rect,
};
let mut size = data.size;
if size.w == 0 {
size.w = source.size.w / 2;
}
if size.h == 0 {
size.h = source.size.h / 2;
}
if data.anchor.anchored_horizontally() {
size.w = source.size.w;
}
if data.anchor.anchored_vertically() {
size.h = source.size.h;
}
let x = if data.anchor.contains(Anchor::LEFT) {
source.loc.x + data.margin.left
} else if data.anchor.contains(Anchor::RIGHT) {
source.loc.x + (source.size.w - size.w) - data.margin.right
} else {
source.loc.x + ((source.size.w / 2) - (size.w / 2))
};
let y = if data.anchor.contains(Anchor::TOP) {
source.loc.y + data.margin.top
} else if data.anchor.contains(Anchor::BOTTOM) {
source.loc.y + (source.size.h - size.h) - data.margin.bottom
} else {
source.loc.y + ((source.size.h / 2) - (size.h / 2))
};
let location: Point<i32, Logical> = (x, y).into();
if let ExclusiveZone::Exclusive(amount) = data.exclusive_zone {
match data.anchor {
x if x.contains(Anchor::LEFT) && !x.contains(Anchor::RIGHT) => {
zone.loc.x += amount as i32 + data.margin.left + data.margin.right
}
x if x.contains(Anchor::TOP) && !x.contains(Anchor::BOTTOM) => {
zone.loc.y += amount as i32 + data.margin.top + data.margin.bottom
}
x if x.contains(Anchor::RIGHT) && !x.contains(Anchor::LEFT) => {
zone.size.w -= amount as i32 + data.margin.left + data.margin.right
}
x if x.contains(Anchor::BOTTOM) && !x.contains(Anchor::TOP) => {
zone.size.h -= amount as i32 + data.margin.top + data.margin.top
}
_ => {}
}
}
slog::trace!(
self.logger,
"Setting layer to pos {:?} and size {:?}",
location,
size
);
let size_changed = layer
.0
.surface
.with_pending_state(|state| {
state.size.replace(size).map(|old| old != size).unwrap_or(true)
})
.unwrap();
if size_changed {
layer.0.surface.send_configure();
}
layer_state(layer).location = location;
}
slog::trace!(self.logger, "Remaining zone {:?}", zone);
self.zone = zone;
}
}
fn output(&self) -> Option<Output> {
self.output.upgrade().map(|inner| Output { inner })
}
/// Cleanup some internally used resources.
///
/// This function needs to be called periodically (though not necessarily frequently)
/// to be able cleanup internally used resources.
pub fn cleanup(&mut self) {
self.layers.retain(|layer| layer.alive());
self.surfaces.retain(|s| s.as_ref().is_alive());
}
/// Returns layers count
#[allow(clippy::len_without_is_empty)] //we don't need is_empty on that struct for now, mark as allow
pub fn len(&self) -> usize {
self.layers.len()
}
}
#[derive(Debug, Default)]
pub struct LayerState {
pub location: Point<i32, Logical>,
}
type LayerUserdata = RefCell<Option<LayerState>>;
pub fn layer_state(layer: &LayerSurface) -> RefMut<'_, LayerState> {
let userdata = layer.user_data();
userdata.insert_if_missing(LayerUserdata::default);
RefMut::map(userdata.get::<LayerUserdata>().unwrap().borrow_mut(), |opt| {
if opt.is_none() {
*opt = Some(LayerState::default());
}
opt.as_mut().unwrap()
})
}
/// A [`LayerSurface`] represents a single layer surface as given by the wlr-layer-shell protocol.
#[derive(Debug, Clone)]
pub struct LayerSurface(pub(crate) Rc<LayerSurfaceInner>);
impl PartialEq for LayerSurface {
fn eq(&self, other: &Self) -> bool {
self.0.id == other.0.id
}
}
impl Eq for LayerSurface {}
impl Hash for LayerSurface {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.id.hash(state);
}
}
#[derive(Debug)]
pub(crate) struct LayerSurfaceInner {
pub(crate) id: usize,
surface: WlrLayerSurface,
namespace: String,
userdata: UserDataMap,
}
impl Drop for LayerSurfaceInner {
fn drop(&mut self) {
LAYER_IDS.lock().unwrap().remove(&self.id);
}
}
impl LayerSurface {
/// Create a new [`LayerSurface`] from a given [`WlrLayerSurface`] and its namespace.
pub fn new(surface: WlrLayerSurface, namespace: String) -> LayerSurface {
LayerSurface(Rc::new(LayerSurfaceInner {
id: next_layer_id(),
surface,
namespace,
userdata: UserDataMap::new(),
}))
}
/// Checks if the surface is still alive
pub fn alive(&self) -> bool {
self.0.surface.alive()
}
/// Returns the underlying [`WlrLayerSurface`]
pub fn layer_surface(&self) -> &WlrLayerSurface {
&self.0.surface
}
/// Returns the underlying [`WlSurface`]
pub fn get_surface(&self) -> Option<&WlSurface> {
self.0.surface.get_surface()
}
/// Returns the cached protocol state
pub fn cached_state(&self) -> Option<LayerSurfaceCachedState> {
self.0.surface.get_surface().map(|surface| {
with_states(surface, |states| {
*states.cached_state.current::<LayerSurfaceCachedState>()
})
.unwrap()
})
}
/// Returns true, if the surface has indicated, that it is able to process keyboard events.
pub fn can_receive_keyboard_focus(&self) -> bool {
self.0
.surface
.get_surface()
.map(|surface| {
with_states(surface, |states| {
match states
.cached_state
.current::<LayerSurfaceCachedState>()
.keyboard_interactivity
{
KeyboardInteractivity::Exclusive | KeyboardInteractivity::OnDemand => true,
KeyboardInteractivity::None => false,
}
})
.unwrap()
})
.unwrap_or(false)
}
/// Returns the layer this surface resides on, if any yet.
pub fn layer(&self) -> Option<WlrLayer> {
self.0.surface.get_surface().map(|surface| {
with_states(surface, |states| {
states.cached_state.current::<LayerSurfaceCachedState>().layer
})
.unwrap()
})
}
/// Returns the namespace of this surface
pub fn namespace(&self) -> &str {
&self.0.namespace
}
/// Returns the bounding box over this layer surface and its subsurfaces.
pub fn bbox(&self) -> Rectangle<i32, Logical> {
if let Some(surface) = self.0.surface.get_surface() {
bbox_from_surface_tree(surface, (0, 0))
} else {
Rectangle::from_loc_and_size((0, 0), (0, 0))
}
}
/// Returns the bounding box over this layer surface, it subsurfaces as well as any popups.
///
/// Note: You need to use a [`PopupManager`] to track popups, otherwise the bounding box
/// will not include the popups.
pub fn bbox_with_popups(&self) -> Rectangle<i32, Logical> {
let mut bounding_box = self.bbox();
if let Some(surface) = self.0.surface.get_surface() {
for (popup, location) in PopupManager::popups_for_surface(surface)
.ok()
.into_iter()
.flatten()
{
if let Some(surface) = popup.get_surface() {
bounding_box = bounding_box.merge(bbox_from_surface_tree(surface, location));
}
}
}
bounding_box
}
/// Finds the topmost surface under this point if any and returns it together with the location of this
/// surface.
///
/// - `point` needs to be relative to (0,0) of the layer surface.
pub fn surface_under<P: Into<Point<f64, Logical>>>(
&self,
point: P,
surface_type: WindowSurfaceType,
) -> Option<(WlSurface, Point<i32, Logical>)> {
let point = point.into();
if let Some(surface) = self.get_surface() {
for (popup, location) in PopupManager::popups_for_surface(surface)
.ok()
.into_iter()
.flatten()
{
if let Some(result) = popup
.get_surface()
.and_then(|surface| under_from_surface_tree(surface, point, location, surface_type))
{
return Some(result);
}
}
under_from_surface_tree(surface, point, (0, 0), surface_type)
} else {
None
}
}
/// Returns the damage of all the surfaces of this layer surface.
///
/// If `for_values` is `Some(_)` it will only return the damage on the
/// first call for a given [`Space`] and [`Output`], if the buffer hasn't changed.
/// Subsequent calls will return an empty vector until the buffer is updated again.
pub(super) fn accumulated_damage(
&self,
for_values: Option<(&Space, &Output)>,
) -> Vec<Rectangle<i32, Logical>> {
let mut damage = Vec::new();
if let Some(surface) = self.get_surface() {
damage.extend(
damage_from_surface_tree(surface, (0, 0), for_values)
.into_iter()
.flat_map(|rect| rect.intersection(self.bbox())),
);
for (popup, location) in PopupManager::popups_for_surface(surface)
.ok()
.into_iter()
.flatten()
{
if let Some(surface) = popup.get_surface() {
let bbox = bbox_from_surface_tree(surface, location);
let popup_damage = damage_from_surface_tree(surface, location, for_values);
damage.extend(popup_damage.into_iter().flat_map(|rect| rect.intersection(bbox)));
}
}
}
damage
}
/// Sends the frame callback to all the subsurfaces in this
/// window that requested it
pub fn send_frame(&self, time: u32) {
if let Some(wl_surface) = self.0.surface.get_surface() {
send_frames_surface_tree(wl_surface, time);
for (popup, _) in PopupManager::popups_for_surface(wl_surface)
.ok()
.into_iter()
.flatten()
{
if let Some(surface) = popup.get_surface() {
send_frames_surface_tree(surface, time);
}
}
}
}
/// Returns a [`UserDataMap`] to allow associating arbitrary data with this surface.
pub fn user_data(&self) -> &UserDataMap {
&self.0.userdata
}
}
/// Renders a given [`LayerSurface`] using a provided renderer and frame.
///
/// - `scale` needs to be equivalent to the fractional scale the rendered result should have.
/// - `location` is the position the layer surface should be drawn at.
/// - `damage` is the set of regions of the layer surface that should be drawn.
///
/// Note: This function will render nothing, if you are not using
/// [`crate::backend::renderer::utils::on_commit_buffer_handler`]
/// to let smithay handle buffer management.
pub fn draw_layer_surface<R, P>(
renderer: &mut R,
frame: &mut <R as Renderer>::Frame,
layer: &LayerSurface,
scale: f64,
location: P,
damage: &[Rectangle<i32, Logical>],
log: &slog::Logger,
) -> Result<(), <R as Renderer>::Error>
where
R: Renderer + ImportAll,
<R as Renderer>::TextureId: 'static,
P: Into<Point<i32, Logical>>,
{
let location = location.into();
if let Some(surface) = layer.get_surface() {
draw_surface_tree(renderer, frame, surface, scale, location, damage, log)?;
for (popup, p_location) in PopupManager::popups_for_surface(surface)
.ok()
.into_iter()
.flatten()
{
if let Some(surface) = popup.get_surface() {
let damage = damage
.iter()
.cloned()
.map(|mut geo| {
geo.loc -= p_location;
geo
})
.collect::<Vec<_>>();
draw_surface_tree(
renderer,
frame,
surface,
scale,
location + p_location,
&damage,
log,
)?;
}
}
}
Ok(())
}
| 35.426307 | 109 | 0.517223 |
39a18e9cbbb13f051729917704b3f1179055e21f
| 13,765 |
use super::*;
use crate::havoc::components::{Counter, Lock};
use crate::havoc::model::name_of;
use crate::havoc::model::ActionResult::{Blocked, Joined, Ran};
use crate::havoc::model::Retention::Weak;
use rustc_hash::FxHashSet;
use std::cell::{Cell, RefCell};
use std::iter::FromIterator;
fn init_log() {
let _ = env_logger::builder()
.filter_level(log::LevelFilter::Trace)
.is_test(true)
.try_init();
}
fn default_config() -> Config {
Config::default().with_sublevel(Sublevel::Finest)
}
#[test]
fn sim_one_shot() {
init_log();
let run_count = Cell::new(0);
let model = Model::new(Counter::new)
.with_name(name_of(&sim_one_shot).into())
.with_action("action".into(), Strong, |_, _| {
run_count.set(run_count.get() + 1);
ActionResult::Joined
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(3));
assert_eq!(Pass, sim.check());
assert_eq!(3, run_count.get());
}
#[test]
fn sim_two_shots() {
init_log();
let run_count = Cell::new(0);
let model = Model::new(Counter::new)
.with_name(name_of(&sim_two_shots).into())
.with_action("test".into(), Strong, |s, c| {
run_count.set(run_count.get() + 1);
match s.inc(c.name().into()) {
2 => ActionResult::Joined,
_ => ActionResult::Ran,
}
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(3));
assert_eq!(Pass, sim.check());
assert_eq!(6, run_count.get());
}
#[test]
fn sim_two_actions() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_two_actions).into())
.with_action("a".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
})
.with_action("b".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(2));
let result = sim.check();
assert_eq!(Pass, result);
assert_eq!(2, total_runs.borrow().get("a"));
assert_eq!(2, total_runs.borrow().get("b"));
}
#[test]
fn sim_two_actions_conditional() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_two_actions_conditional).into())
.with_action("a".into(), Strong, |s, c| {
total_runs.borrow_mut().inc(c.name().into());
s.inc(c.name().into());
Joined
})
.with_action("b".into(), Strong, |s, c| {
if s.inc(c.name().into()) == 1 && s.get("a") == 0 {
return Blocked;
}
total_runs.borrow_mut().inc(c.name().into());
Joined
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(5));
let result = sim.check();
assert_eq!(Pass, result);
assert_eq!(5, total_runs.borrow().get("a"));
assert_eq!(5, total_runs.borrow().get("b"));
}
#[test]
fn sim_two_actions_by_two() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_two_actions_by_two).into())
.with_action("a".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
})
.with_action("b".into(), Strong, |s, c| {
total_runs.borrow_mut().inc(c.name().into());
match s.inc(c.name().into()) {
2 => Joined,
_ => Ran,
}
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(3));
let result = sim.check();
assert_eq!(Pass, result);
assert_eq!(3, total_runs.borrow().get("a"));
assert_eq!(6, total_runs.borrow().get("b"));
}
#[test]
fn sim_three_actions() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_three_actions).into())
.with_action("a".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
})
.with_action("b".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
})
.with_action("c".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(3));
let result = sim.check();
assert_eq!(Pass, result);
assert_eq!(3, total_runs.borrow().get("a"));
assert_eq!(3, total_runs.borrow().get("b"));
assert_eq!(3, total_runs.borrow().get("c"));
}
#[test]
fn sim_three_actions_by_two() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_three_actions_by_two).into())
.with_action("a".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
})
.with_action("b".into(), Strong, |_, c| {
total_runs.borrow_mut().inc(c.name().into());
Joined
})
.with_action("c".into(), Strong, |s, c| {
total_runs.borrow_mut().inc(c.name().into());
match s.inc(c.name().into()) {
2 => Joined,
_ => Ran,
}
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(3));
let result = sim.check();
assert_eq!(3, total_runs.borrow().get("a"));
assert_eq!(3, total_runs.borrow().get("b"));
assert_eq!(6, total_runs.borrow().get("c"));
assert_eq!(Pass, result);
}
#[test]
fn sim_one_shot_deadlock() {
init_log();
let run_count = Cell::new(0);
let model = Model::new(Counter::new)
.with_name(name_of(&sim_one_shot_deadlock).into())
.with_action("test".into(), Strong, |_, _| {
run_count.set(run_count.get() + 1);
ActionResult::Blocked
});
let sim = Sim::new(&model).with_config(default_config());
assert_eq!(Deadlock(DeadlockResult {
trace: Trace::of(&[]),
schedule: 0
}), sim.check());
assert_eq!(1, run_count.get());
}
#[test]
fn sim_two_actions_no_deadlock() {
init_log();
let mut model = Model::new(Lock::new).with_name(name_of(&sim_two_actions_no_deadlock).into());
for c in ["a", "b"] {
model.add_action(String::from("test-".to_owned() + c), Strong, |s, c| {
if s.held(c.name()) {
s.unlock();
Joined
} else if s.lock(c.name().into()) {
Ran
} else {
Blocked
}
});
}
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(10));
assert_eq!(Pass, sim.check());
}
impl SimResult {
fn ordinal(&self) -> usize {
match self {
Pass => 0,
Fail(_) => 1,
Deadlock(_) => 2
}
}
}
#[test]
fn sim_two_actions_deadlock() {
init_log();
let model = Model::new(|| [Lock::new(), Lock::new()])
.with_name(name_of(&sim_two_actions_deadlock).into())
.with_action("a".into(), Strong, |s, c| {
if s[0].held(c.name()) {
if s[1].held(c.name()) {
s[1].unlock();
s[0].unlock();
Joined
} else if s[1].lock(c.name().into()) {
Ran
} else {
Blocked
}
} else if s[0].lock(c.name().into()) {
Ran
} else {
Blocked
}
})
.with_action("b".into(), Strong, |s, c| {
if s[1].held(c.name()) {
if s[0].held(c.name()) {
s[0].unlock();
s[1].unlock();
Joined
} else if s[0].lock(c.name().into()) {
Ran
} else {
Blocked
}
} else if s[1].lock(c.name().into()) {
Ran
} else {
Blocked
}
});
let mut sim = Sim::new(&model).with_config(default_config());
let mut results = FxHashSet::default();
for seed in 0..999 {
sim.set_seed(seed);
let result = sim.check();
if let Deadlock(result) = &result {
assert_eq!(2, result.trace.calls.len());
}
results.insert(result.ordinal());
if results.len() == 2 {
break;
}
}
// some runs will result in a deadlock, while others will pass
assert_eq!(FxHashSet::from_iter([0, 2]), results);
}
#[test]
fn sim_two_actions_one_weak_blocked() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_two_actions_one_weak_blocked).into())
.with_action("a".into(), Strong, |s, c| {
total_runs.borrow_mut().inc(c.name().into());
s.inc(c.name().into());
Joined
})
.with_action("b".into(), Weak, |s, c| {
assert_eq!(0, s.get("a"), "b should not run after a's join");
total_runs.borrow_mut().inc(c.name().into());
Blocked
});
let mut sim = Sim::new(&model).with_config(default_config());
let mut run_counts = FxHashSet::default();
let mut seed = 0;
for _ in 0..999 {
sim.set_seed(seed);
seed += 1;
assert_eq!(Pass, sim.check());
let mut total_runs = total_runs.borrow_mut();
run_counts.insert(total_runs.get("b"));
total_runs.reset("b");
if run_counts.len() == 2 {
break;
}
}
assert_eq!(seed, total_runs.borrow().get("a") as u64);
assert_eq!(FxHashSet::from_iter([0, 1]), run_counts);
}
#[test]
fn sim_two_actions_one_weak_two_runs() {
init_log();
let total_runs = RefCell::new(Counter::new());
let model = Model::new(Counter::new)
.with_name(name_of(&sim_two_actions_one_weak_two_runs).into())
.with_action("a".into(), Strong, |s, c| {
total_runs.borrow_mut().inc(c.name().into());
s.inc(c.name().into());
Joined
})
.with_action("b".into(), Weak, |s, c| {
assert_eq!(0, s.get("a"), "b should not run after a's join");
total_runs.borrow_mut().inc(c.name().into());
match s.inc(c.name().into()) {
2 => Joined,
_ => Ran,
}
});
let mut sim = Sim::new(&model).with_config(default_config());
let mut run_counts = FxHashSet::default();
let mut seed = 0;
for _ in 0..999 {
sim.set_seed(seed);
seed += 1;
assert_eq!(Pass, sim.check());
let mut total_runs = total_runs.borrow_mut();
run_counts.insert(total_runs.get("b"));
total_runs.reset("b");
if run_counts.len() == 3 {
break;
}
}
assert_eq!(seed, total_runs.borrow().get("a") as u64);
assert_eq!(FxHashSet::from_iter([0, 1, 2]), run_counts);
}
#[test]
fn sim_rand() {
init_log();
let generated = RefCell::new(FxHashSet::default());
const NUM_RUNS: i64 = 3;
struct State {
counter: Counter,
rands: Vec<Vec<u64>>,
}
let model = Model::new(|| State {
counter: Counter::new(),
rands: vec![],
})
.with_name(name_of(&sim_rand).into())
.with_action("test".into(), Strong, |s, c| {
let current_rands = vec![c.rand(u64::MAX), c.rand(u64::MAX)];
for &rand in ¤t_rands {
generated.borrow_mut().insert(rand);
}
s.rands.push(current_rands);
let trace = c.trace();
let completed = s.counter.inc(c.name().into());
assert_eq!(completed, trace.calls.len() as i64);
let rands_from_trace: Vec<Vec<u64>> =
trace.calls.iter().map(|call| call.rands.clone()).collect();
assert_eq!(s.rands, rands_from_trace);
match completed {
NUM_RUNS => Joined,
_ => Ran,
}
});
assert_eq!(Pass, Sim::new(&model).with_config(default_config()).check());
assert_eq!(NUM_RUNS * 2, generated.borrow().len() as i64);
// repeat run should yield the same random numbers
assert_eq!(Pass, Sim::new(&model).with_config(default_config()).check());
assert_eq!(NUM_RUNS * 2, generated.borrow().len() as i64);
// differently seeded run will yield different random numbers
assert_eq!(Pass, Sim::new(&model).with_config(default_config()).with_seed(1).check());
assert_eq!(NUM_RUNS * 4, generated.borrow().len() as i64);
}
#[test]
fn sim_one_shot_breach() {
init_log();
let run_count = Cell::new(0);
let model = Model::new(Counter::new)
.with_name(name_of(&sim_one_shot_breach).into())
.with_action("action".into(), Strong, |_, _| {
run_count.set(run_count.get() + 1);
Breached("some invariant".into())
});
let sim = Sim::new(&model).with_config(default_config().with_max_schedules(3));
assert_eq!(
Fail(
FailResult {
error: "some invariant".to_string(),
trace: Trace::of(&[Call::of(0, &[])]),
schedule: 0
}
.into()
),
sim.check()
);
assert_eq!(1, run_count.get());
}
| 31.571101 | 98 | 0.531784 |
deec0c5813156d0c04954f8c7c6528a77efb2f23
| 7,702 |
use indy_api_types::{CommandHandle, ErrorCode, errors::prelude::*};
use indy_utils::ctypes;
use libc::c_char;
use crate::Locator;
use crate::services::CommandMetric;
/// Send coins to other account.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// from: address of sender coins
/// to: address of getter coins
/// amount: Amount of coins for sending
/// denom: Denomination of coins
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Success or error message.
#[no_mangle]
pub extern "C" fn indy_cheqd_ledger_bank_build_msg_send(
command_handle: CommandHandle,
from: *const c_char,
to: *const c_char,
amount: *const c_char,
denom: *const c_char,
cb: Option<
extern "C" fn(
command_handle_: CommandHandle,
err: ErrorCode,
msg_raw: *const u8,
msg_len: u32,
),
>,
) -> ErrorCode {
debug!(
"indy_cheqd_ledger_bank_build_msg_send > from {:?} to {:?} amount {:?} denom {:?}",
from, to, amount, denom
);
check_useful_c_str!(from, ErrorCode::CommonInvalidParam2);
check_useful_c_str!(to, ErrorCode::CommonInvalidParam3);
check_useful_c_str!(amount, ErrorCode::CommonInvalidParam4);
check_useful_c_str!(denom, ErrorCode::CommonInvalidParam5);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam6);
debug!(
"indy_cheqd_ledger_bank_build_msg_send > did {:?} creator {:?} verkey {:?} alias {:?}",
from, to, amount, denom
);
let locator = Locator::instance();
let action = async move {
let res = locator
.cheqd_ledger_controller
.bank_build_msg_send(&from, &to, &amount, &denom);
res
};
let cb = move |res: IndyResult<_>| {
let (err, msg) = prepare_result!(res, Vec::new());
debug!(
"indy_cheqd_ledger_bank_build_msg_send: signature: {:?}",
msg
);
let (msg_raw, msg_len) = ctypes::vec_to_pointer(&msg);
cb(command_handle, err, msg_raw, msg_len)
};
locator.executor.spawn_ok_instrumented(
CommandMetric::CheqdLedgerCommandBuildMsgSend,
action,
cb,
);
let res = ErrorCode::Success;
debug!("indy_cheqd_ledger_bank_build_msg_send < {:?}", res);
res
}
/// Parse response for send coins tx.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// commit_resp: response for send coins tx.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Success or error message.
#[no_mangle]
pub extern "C" fn indy_cheqd_ledger_bank_parse_msg_send_resp(
command_handle: CommandHandle,
commit_resp: *const c_char,
cb: Option<
extern "C" fn(command_handle_: CommandHandle, err: ErrorCode, msg_resp: *const c_char),
>,
) -> ErrorCode {
debug!(
"indy_cheqd_ledger_bank_parse_msg_send_resp > commit_resp {:?}",
commit_resp
);
check_useful_c_str!(commit_resp, ErrorCode::CommonInvalidParam2);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam3);
debug!(
"indy_cheqd_ledger_bank_parse_msg_send_resp > commit_resp {:?}",
commit_resp
);
let locator = Locator::instance();
let action = async move {
let res = locator
.cheqd_ledger_controller
.bank_parse_msg_send_resp(&commit_resp);
res
};
let cb = move |res: IndyResult<_>| {
let (err, msg_resp) = prepare_result!(res, String::new());
debug!(
"indy_cheqd_ledger_bank_parse_msg_send_resp: msg_resp: {:?}",
msg_resp
);
let msg_resp = ctypes::string_to_cstring(msg_resp);
cb(command_handle, err, msg_resp.as_ptr())
};
locator.executor.spawn_ok_instrumented(
CommandMetric::CheqdLedgerCommandParseMsgCreateNymResp,
action,
cb,
);
let res = ErrorCode::Success;
debug!("indy_cheqd_ledger_bank_parse_msg_send_resp < {:?}", res);
res
}
/// Get balance of account.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// address: address of account which need to get.
/// denom: currency of balance for getting.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Success or error message.
#[no_mangle]
pub extern "C" fn indy_cheqd_ledger_bank_build_query_balance(
command_handle: CommandHandle,
address: *const c_char,
denom: *const c_char,
cb: Option<
extern "C" fn(command_handle_: CommandHandle, err: ErrorCode, msg_resp: *const c_char),
>,
) -> ErrorCode {
debug!(
"indy_cheqd_ledger_bank_build_query_balance > address {:?} denom {:?}",
address, denom
);
check_useful_c_str!(address, ErrorCode::CommonInvalidParam2);
check_useful_c_str!(denom, ErrorCode::CommonInvalidParam3);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);
debug!(
"indy_cheqd_ledger_bank_build_query_balance > address {:?} denom {:?}",
address, denom
);
let locator = Locator::instance();
let action = async move {
let res = locator
.cheqd_ledger_controller
.bank_build_query_balance(address, denom);
res
};
let cb = move |res: IndyResult<_>| {
let (err, msg_resp) = prepare_result!(res, String::new());
debug!(
"indy_cheqd_ledger_bank_build_query_balance: signature: {:?}",
msg_resp
);
let msg_resp = ctypes::string_to_cstring(msg_resp);
cb(command_handle, err, msg_resp.as_ptr())
};
locator.executor.spawn_ok_instrumented(
CommandMetric::CheqdLedgerCommandBuildQueryBalance,
action,
cb,
);
let res = ErrorCode::Success;
debug!("indy_cheqd_ledger_bank_build_query_balance < {:?}", res);
res
}
/// Parse response for get balance tx.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// commit_resp: response for get balance tx.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Success or error message.
#[no_mangle]
pub extern "C" fn indy_cheqd_ledger_bank_parse_query_balance_resp(
command_handle: CommandHandle,
commit_resp: *const c_char,
cb: Option<
extern "C" fn(command_handle_: CommandHandle, err: ErrorCode, msg_resp: *const c_char),
>,
) -> ErrorCode {
debug!(
"indy_cheqd_ledger_bank_parse_query_balance_resp > commit_resp {:?}",
commit_resp
);
check_useful_c_str!(commit_resp, ErrorCode::CommonInvalidParam2);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam3);
debug!(
"indy_cheqd_ledger_bank_parse_query_balance_resp > commit_resp {:?}",
commit_resp
);
let locator = Locator::instance();
let action = async move {
let res = locator
.cheqd_ledger_controller
.bank_parse_query_balance_resp(&commit_resp);
res
};
let cb = move |res: IndyResult<_>| {
let (err, msg_resp) = prepare_result!(res, String::new());
debug!(
"indy_cheqd_ledger_bank_parse_query_balance_resp: msg_resp: {:?}",
msg_resp
);
let msg_resp = ctypes::string_to_cstring(msg_resp);
cb(command_handle, err, msg_resp.as_ptr())
};
locator.executor.spawn_ok_instrumented(
CommandMetric::CheqdLedgerCommandParseQueryBalanceResp,
action,
cb,
);
let res = ErrorCode::Success;
debug!("indy_cheqd_ledger_bank_parse_query_balance_resp < {:?}", res);
res
}
| 29.285171 | 95 | 0.647105 |
897b05bd3ae3e1918a71fa3d4e32c7f4bd57bcea
| 12,851 |
//! Collects default property values by generated a place file every kind of
//! instance in it, then uses Roblox Studio to re-save it with default property
//! information encoded in it.
use std::{
borrow::Cow,
collections::{HashSet, VecDeque},
fmt::{self, Write},
fs::{self, File},
io::BufReader,
process::Command,
sync::mpsc,
time::Duration,
};
use anyhow::Context;
#[cfg(target_os = "windows")]
use innerput::{Innerput, Key, Keyboard};
use notify::{DebouncedEvent, Watcher};
use rbx_dom_weak::types::VariantType;
use rbx_dom_weak::WeakDom;
use rbx_reflection::{PropertyDescriptor, PropertyKind, PropertySerialization, ReflectionDatabase};
use roblox_install::RobloxStudio;
use tempfile::tempdir;
use crate::plugin_injector::{PluginInjector, StudioInfo};
/// Use Roblox Studio to populate the reflection database with default values
/// for as many properties as possible.
pub fn measure_default_properties(database: &mut ReflectionDatabase) -> anyhow::Result<()> {
let fixture_place = generate_fixture_place(database);
let output = roundtrip_place_through_studio(&fixture_place)?;
database.version = output.info.version;
log::info!("Applying defaults from place file into reflection database...");
apply_defaults_from_fixture_place(database, &output.tree);
Ok(())
}
fn apply_defaults_from_fixture_place(database: &mut ReflectionDatabase, tree: &WeakDom) {
// Perform a breadth-first search to find the instance shallowest in the
// tree of each class.
let mut found_classes = HashSet::new();
let mut to_visit = VecDeque::new();
to_visit.extend(tree.root().children());
while let Some(referent) = to_visit.pop_front() {
let instance = tree.get_by_ref(referent).unwrap();
to_visit.extend(instance.children());
if found_classes.contains(&instance.class) {
continue;
}
found_classes.insert(instance.class.clone());
for (prop_name, prop_value) in &instance.properties {
let descriptors = match find_descriptors(database, &instance.class, prop_name) {
Some(descriptor) => descriptor,
None => {
log::warn!(
"Found unknown property {}.{}, which is of type {:?}",
instance.class,
prop_name,
prop_value.ty(),
);
continue;
}
};
match &descriptors.canonical.kind {
PropertyKind::Canonical { serialization } => match serialization {
PropertySerialization::Serializes => {
if &descriptors.canonical.name != prop_name {
log::error!("Property {}.{} is supposed to serialize as {}, but was actually serialized as {}",
instance.class,
descriptors.canonical.name,
descriptors.canonical.name,
prop_name);
}
}
PropertySerialization::DoesNotSerialize => {
log::error!(
"Property {}.{} (canonical name {}) found in default place but should not serialize",
instance.class,
prop_name,
descriptors.canonical.name,
);
}
PropertySerialization::SerializesAs(serialized_name) => {
if serialized_name != prop_name {
log::error!("Property {}.{} is supposed to serialize as {}, but was actually serialized as {}",
instance.class,
descriptors.canonical.name,
serialized_name,
prop_name);
}
}
unknown => {
log::error!(
"Unknown property serialization {:?} on property {}.{}",
unknown,
instance.class,
descriptors.canonical.name
);
}
},
_ => panic!(
"find_descriptors must not return a non-canonical descriptor as canonical"
),
}
let canonical_name = Cow::Owned(descriptors.canonical.name.clone().into_owned());
match prop_value.ty() {
// We don't support usefully emitting these types yet.
VariantType::Ref | VariantType::SharedString => {}
_ => {
let class_descriptor = match database.classes.get_mut(instance.class.as_str()) {
Some(descriptor) => descriptor,
None => {
log::warn!(
"Class {} found in default place but not API dump",
instance.class
);
continue;
}
};
class_descriptor
.default_properties
.insert(canonical_name, prop_value.clone());
}
}
}
}
}
struct Descriptors<'a> {
// This descriptor might be useful in the future, but is currently unused.
#[allow(unused)]
input: &'a PropertyDescriptor<'a>,
canonical: &'a PropertyDescriptor<'a>,
}
fn find_descriptors<'a>(
database: &'a ReflectionDatabase,
class_name: &str,
prop_name: &str,
) -> Option<Descriptors<'a>> {
let mut input_descriptor = None;
let mut next_class_name = Some(class_name);
while let Some(current_class_name) = next_class_name {
let class = database.classes.get(current_class_name).unwrap();
if let Some(prop) = class.properties.get(prop_name) {
if input_descriptor.is_none() {
input_descriptor = Some(prop);
}
match &prop.kind {
PropertyKind::Canonical { .. } => {
return Some(Descriptors {
input: input_descriptor.unwrap(),
canonical: prop,
});
}
PropertyKind::Alias { alias_for } => {
let aliased_prop = class.properties.get(alias_for).unwrap();
return Some(Descriptors {
input: input_descriptor.unwrap(),
canonical: aliased_prop,
});
}
unknown => {
log::warn!("Unknown property kind {:?}", unknown);
return None;
}
}
}
next_class_name = class.superclass.as_ref().map(|name| name.as_ref());
}
None
}
struct StudioOutput {
info: StudioInfo,
tree: WeakDom,
}
/// Generate a new fixture place from the given reflection database, open it in
/// Studio, coax Studio to re-save it, and reads back the resulting place.
fn roundtrip_place_through_studio(place_contents: &str) -> anyhow::Result<StudioOutput> {
let output_dir = tempdir()?;
let output_path = output_dir.path().join("GenerateReflectionRoundtrip.rbxlx");
log::info!("Generating place at {}", output_path.display());
fs::write(&output_path, place_contents)?;
let studio_install = RobloxStudio::locate()?;
let injector = PluginInjector::start(&studio_install);
log::info!("Starting Roblox Studio...");
let mut studio_process = Command::new(studio_install.application_path())
.arg(output_path.display().to_string())
.spawn()?;
let info = injector.receive_info();
let (tx, rx) = mpsc::channel();
let mut watcher = notify::watcher(tx, Duration::from_millis(300))?;
watcher.watch(&output_path, notify::RecursiveMode::NonRecursive)?;
log::info!("Waiting for Roblox Studio to re-save place...");
#[cfg(target_os = "windows")]
{
let did_send_chord =
Innerput::new().send_chord(&[Key::Control, Key::Char('s')], &studio_process);
match did_send_chord {
Ok(()) => (),
Err(err) => {
log::error!("{}", err);
println!(
"Failed to send key chord to Roblox Studio. Please save the opened place manually."
)
}
}
}
#[cfg(not(target_os = "windows"))]
println!("Please save the opened place in Roblox Studio (ctrl+s).");
loop {
if let DebouncedEvent::Write(_) = rx.recv()? {
break;
}
}
log::info!("Place saved, killing Studio...");
studio_process.kill()?;
log::info!("Reading back place file...");
let file = BufReader::new(File::open(&output_path)?);
let decode_options = rbx_xml::DecodeOptions::new()
.property_behavior(rbx_xml::DecodePropertyBehavior::NoReflection);
let tree = match rbx_xml::from_reader(file, decode_options) {
Ok(tree) => tree,
Err(err) => {
let _ = fs::copy(output_path, "defaults-place.rbxlx");
return Err(err).context(
"failed to decode defaults place; it has been copied to defaults-place.rbxlx",
);
}
};
Ok(StudioOutput { info, tree })
}
/// Create a place file that contains a copy of every Roblox class and no
/// properties defined.
///
/// When this place is re-saved by Roblox Studio, it'll contain default values
/// for every property.
fn generate_fixture_place(database: &ReflectionDatabase) -> String {
log::info!("Generating place with every instance...");
let mut output = String::new();
writeln!(&mut output, "<roblox version=\"4\">").unwrap();
for descriptor in database.classes.values() {
let mut instance = FixtureInstance::named(&descriptor.name);
match &*descriptor.name {
// These types can't be put into place files by default.
"DebuggerWatch" | "DebuggerBreakpoint" | "AdvancedDragger" | "Dragger"
| "ScriptDebugger" | "PackageLink" => continue,
// These types have specific parenting restrictions handled
// elsewhere.
"Terrain"
| "Attachment"
| "Animator"
| "StarterPlayerScripts"
| "StarterCharacterScripts"
| "Bone"
| "BaseWrap"
| "WrapLayer"
| "WrapTarget" => continue,
// WorldModel is not yet enabled.
"WorldModel" => continue,
"StarterPlayer" => {
instance.add_child(FixtureInstance::named("StarterPlayerScripts"));
instance.add_child(FixtureInstance::named("StarterCharacterScripts"));
}
"Workspace" => {
instance.add_child(FixtureInstance::named("Terrain"));
}
"Part" => {
instance.add_child(FixtureInstance::named("Attachment"));
instance.add_child(FixtureInstance::named("Bone"));
}
"Humanoid" => {
instance.add_child(FixtureInstance::named("Animator"));
}
"MeshPart" => {
// Without this special case, Studio will fail to open the
// resulting file, complaining about "BaseWrap".
instance.add_child(FixtureInstance::named("BaseWrap"));
instance.add_child(FixtureInstance::named("WrapLayer"));
instance.add_child(FixtureInstance::named("WrapTarget"));
}
_ => {}
}
write!(output, "{}", instance).unwrap();
}
writeln!(&mut output, "</roblox>").unwrap();
output
}
struct FixtureInstance<'a> {
name: &'a str,
children: Vec<FixtureInstance<'a>>,
}
impl<'a> FixtureInstance<'a> {
fn named(name: &'a str) -> Self {
Self {
name,
children: Vec::new(),
}
}
fn add_child(&mut self, child: FixtureInstance<'a>) {
self.children.push(child);
}
}
impl fmt::Display for FixtureInstance<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
writeln!(
formatter,
"<Item class=\"{}\" reference=\"{}\">",
&self.name, &self.name
)?;
for child in &self.children {
write!(formatter, "{}", child)?;
}
writeln!(formatter, "</Item>")?;
Ok(())
}
}
| 33.729659 | 123 | 0.5342 |
64101c19fc9e05ed445976b229ef4c307d135fa1
| 3,086 |
// Copyright 2016 Kyle Mayes
//
// 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.
//! Lexed pieces of source files.
use std::fmt;
use std::mem;
use clang_sys::{
clang_getTokenExtent, clang_getTokenKind, clang_getTokenLocation, clang_getTokenSpelling,
CXToken,
};
use super::source::SourceRange;
use super::TranslationUnit;
use crate::source::SourceLocation;
use crate::utility;
//================================================
// Enums
//================================================
// TokenKind _____________________________________
/// Indicates the categorization of a token.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum Kind {
/// A comment token.
Comment = 4,
/// An identifier token.
Identifier = 2,
/// A keyword token.
Keyword = 1,
/// A literal token.
Literal = 3,
/// A puncuation token.
Punctuation = 0,
}
//================================================
// Structs
//================================================
// Token _________________________________________
/// A lexed piece of a source file.
#[derive(Copy, Clone)]
pub struct Token<'tu> {
pub(crate) raw: CXToken,
tu: &'tu TranslationUnit<'tu>,
}
impl<'tu> Token<'tu> {
//- Constructors -----------------------------
#[doc(hidden)]
pub fn from_raw(raw: CXToken, tu: &'tu TranslationUnit<'tu>) -> Token<'tu> {
Token { raw, tu }
}
//- Accessors --------------------------------
/// Returns the categorization of this token.
pub fn get_kind(&self) -> Kind {
unsafe { mem::transmute(clang_getTokenKind(self.raw)) }
}
/// Returns the textual representation of this token.
pub fn get_spelling(&self) -> String {
unsafe { utility::to_string(clang_getTokenSpelling(self.tu.ptr, self.raw)) }
}
/// Returns the source location of this token.
pub fn get_location(&self) -> SourceLocation<'tu> {
unsafe { SourceLocation::from_raw(clang_getTokenLocation(self.tu.ptr, self.raw), self.tu) }
}
/// Returns the source range of this token.
pub fn get_range(&self) -> SourceRange<'tu> {
unsafe { SourceRange::from_raw(clang_getTokenExtent(self.tu.ptr, self.raw), self.tu) }
}
}
impl<'tu> fmt::Debug for Token<'tu> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_struct("Token")
.field("kind", &self.get_kind())
.field("spelling", &self.get_spelling())
.field("range", &self.get_range())
.finish()
}
}
| 29.113208 | 99 | 0.599806 |
18429da96f5157069b5e931ac27a85c3d6ea08dc
| 36,058 |
//! # subset-map
//!
//! ## Summary
//!
//! `subset-map` is a map like data structure where the keys are combinations
//! of elements the `SubsetMap` has been initialized with.
//!
//! The order of the elements is defined by the position of an element
//! within the elements the `SubsetMap` has been initialized with.
//!
//! `SubsetMap` clones the elements into the subsets. So you should
//! consider to only use element types where you would feel good to assign
//! them the `Copy` trait.
//!
//! Lookup is done linearly. Therefore `SubsetMap` should only be used
//! with not too big sets of elements.
//!
//! ### Example
//!
//! ```
//! use subset_map::*;
//! // Initialize the map where the payloads are basically the keys
//! let subset_map = SubsetMap::fill(&[1, 2, 3], |x| x.iter().cloned().collect::<Vec<_>>());
//!
//! assert_eq!(subset_map.get(&[1]), Some(&vec![1]));
//! assert_eq!(subset_map.get(&[2]), Some(&vec![2]));
//! assert_eq!(subset_map.get(&[3]), Some(&vec![3]));
//! assert_eq!(subset_map.get(&[1, 2]), Some(&vec![1, 2]));
//! assert_eq!(subset_map.get(&[2, 3]), Some(&vec![2, 3]));
//! assert_eq!(subset_map.get(&[1, 3]), Some(&vec![1, 3]));
//! assert_eq!(subset_map.get(&[1, 2, 3]), Some(&vec![1, 2, 3]));
//!
//! // No internal ordering is performed:
//! // The position in the original set is crucial:
//! assert_eq!(subset_map.get(&[2,1]), None);
//! ```
//!
//! ## Features
//!
//! The `serde` feature allows serialization and deserialization with `serde`.
//!
//! ## Recent Changes
//!
//! * 0.3.2
//! * Added more methods to iterate/walk
//! * 0.3.1
//! * Added methods to work with payloads
//! * 0.3.0
//! * [BREAKING CHANGES]: Changed API to be more consistent
//! * 0.2.2
//! * fixed `size` function
//! * 0.2.1
//! * Optimized `find` and `lookup` a bit
//! * Added `size` finction to return the number of combinations
//! * 0.2.0
//! * Renamed MatchQuality to `LookupResult`
//! * `LookupResult` also contains the no match case
//! * improved documentation
//!
//! ## License
//!
//! `subset-map` is distributed under the terms of both the MIT license and the Apache License (Version
//! 2.0).
//!
//! Copyright(2018) Christian Douven
//!
//! See LICENSE-APACHE and LICENSE-MIT for details.
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde;
type Nodes<I, P> = Vec<SubsetMapNode<I, P>>;
/// A map like data structure where the keys are subsets made of
/// combinations of the original sets.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SubsetMap<E, P> {
nodes: Nodes<E, P>,
}
impl<E, P> SubsetMap<E, P>
where
E: Clone,
{
/// Creates a new instance where the payloads are
/// initialized with a closure that is passed the
/// current subset of elements.
///
/// This function assigns values to those combinations where
/// the given closure `init` returns `Some`.
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::new(&[1, 2], |x| {
/// let sum = x.iter().sum::<i32>();
/// if sum == 1 {
/// None
/// } else {
/// Some(sum)
/// }
/// });
///
/// assert_eq!(subset_map.get(&[1]), None);
/// assert_eq!(subset_map.get(&[2]), Some(&2));
/// assert_eq!(subset_map.get(&[1, 2]), Some(&3));
/// assert_eq!(subset_map.get(&[]), None);
/// assert_eq!(subset_map.get(&[2, 1]), None);
/// assert_eq!(subset_map.get(&[0]), None);
/// assert_eq!(subset_map.get(&[0, 1]), None);
/// ```
pub fn new<F>(elements: &[E], mut init: F) -> SubsetMap<E, P>
where
F: FnMut(&[E]) -> Option<P>,
{
init_root::<_, _, _, ()>(elements, &mut |elements| Ok(init(elements))).unwrap()
}
/// Creates a new instance where the payloads are
/// initialized with a closure that is passed the
/// current subset of elements.
///
/// This fuction will assign an element to each subset.
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::fill(&[1, 2], |x| x.iter().sum::<i32>());
/// assert_eq!(subset_map.get(&[1]), Some(&1));
/// assert_eq!(subset_map.get(&[2]), Some(&2));
/// assert_eq!(subset_map.get(&[1, 2]), Some(&3));
/// assert_eq!(subset_map.get(&[]), None);
/// assert_eq!(subset_map.get(&[2, 1]), None);
/// assert_eq!(subset_map.get(&[0]), None);
/// assert_eq!(subset_map.get(&[0, 1]), None);
/// ```
pub fn fill<F>(elements: &[E], mut init: F) -> SubsetMap<E, P>
where
F: FnMut(&[E]) -> P,
{
init_root::<_, _, _, ()>(elements, &mut |elements| Ok(Some(init(elements)))).unwrap()
}
/// Initializes the `SubsetMap` with a closure that can fail.
/// This function initializes all those subsets with the returned payloads
/// where the `init` closure returned an `Result::Ok(Option::Some)`
/// given that all calls on the closure returned `Result::Ok`.
///
/// Failure of the `init` closure will result in a failure
/// of the whole initialization process.
///
/// # Example
///
/// The whole initialization process fails.
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::init(&[1, 2], |x| {
/// let sum = x.iter().sum::<i32>();
/// if sum == 1 {
/// Ok(Some(sum))
/// } else if sum == 2 {
/// Ok(None)
/// } else {
/// Err("bang!")
/// }
/// });
///
/// assert_eq!(subset_map, Err("bang!"));
/// ```
pub fn init<F, X>(elements: &[E], mut init: F) -> Result<SubsetMap<E, P>, X>
where
F: FnMut(&[E]) -> Result<Option<P>, X>,
{
init_root(elements, &mut init)
}
/// Initializes the `SubsetMap` with a closure that can fail.
/// This function initializes all subsets with the returned payloads
/// given that all calls on the closure returned `Result::Ok`.
///
/// Failure of the `init` closure will result in a failure
/// of the whole initialization process.
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::init_filled(&[1, 2], |x| {
/// let sum = x.iter().sum::<i32>();
/// if sum != 3 {
/// Ok(sum)
/// } else {
/// Err("bang!")
/// }
/// });
///
/// assert_eq!(subset_map, Err("bang!"));
/// ```
pub fn init_filled<F, X>(elements: &[E], mut init: F) -> Result<SubsetMap<E, P>, X>
where
F: FnMut(&[E]) -> Result<P, X>,
{
init_root::<_, _, _, X>(elements, &mut |elements| init(elements).map(Some))
}
/// Creates a new instance where the payloads are all initialized
/// with the same value.
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::with_value(&[1, 2], || 42);
/// assert_eq!(subset_map.get(&[1]), Some(&42));
/// assert_eq!(subset_map.get(&[2]), Some(&42));
/// assert_eq!(subset_map.get(&[1, 2]), Some(&42));
/// assert_eq!(subset_map.get(&[]), None);
/// assert_eq!(subset_map.get(&[2, 1]), None);
/// assert_eq!(subset_map.get(&[0]), None);
/// assert_eq!(subset_map.get(&[0, 1]), None);
/// ```
pub fn with_value<F>(elements: &[E], mut init: F) -> SubsetMap<E, P>
where
F: FnMut() -> P,
{
init_root::<_, _, _, ()>(elements, &mut |_| Ok(Some(init()))).unwrap()
}
/// Creates a new instance where the payloads are all initialized
/// with the `Default::default()` value of the payload type.
/// Creates a new instance where the payloads are all initialized
/// with the same value.
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::with_default(&[1, 2]);
/// assert_eq!(subset_map.get(&[1]), Some(&0));
/// assert_eq!(subset_map.get(&[2]), Some(&0));
/// assert_eq!(subset_map.get(&[1, 2]), Some(&0));
/// assert_eq!(subset_map.get(&[]), None);
/// assert_eq!(subset_map.get(&[2, 1]), None);
/// assert_eq!(subset_map.get(&[0]), None);
/// assert_eq!(subset_map.get(&[0, 1]), None);
/// ```
pub fn with_default(elements: &[E]) -> SubsetMap<E, P>
where
P: Default,
{
init_root::<_, _, _, ()>(elements, &mut |_| Ok(Some(P::default()))).unwrap()
}
/// Gets a payload by the given subset.
///
/// Only "perfect" matches on `subset` are returned.
///
/// The function returns `None` regardless of whether
/// `subset` was part of the map or there was no payload
/// assigned to the given subset.
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::new(&[1, 2, 3], |x| {
/// let payload = x.iter().cloned().collect::<Vec<_>>();
/// if payload.len() == 1 {
/// None
/// } else {
/// Some(payload)
/// }
/// });
/// assert_eq!(subset_map.get(&[1]), None);
/// assert_eq!(subset_map.get(&[2]), None);
/// assert_eq!(subset_map.get(&[3]), None);
/// assert_eq!(subset_map.get(&[1, 2]), Some(&vec![1, 2]));
/// assert_eq!(subset_map.get(&[2, 3]), Some(&vec![2, 3]));
/// assert_eq!(subset_map.get(&[1, 3]), Some(&vec![1, 3]));
/// assert_eq!(subset_map.get(&[1, 2, 3]), Some(&vec![1, 2, 3]));
///
/// assert_eq!(subset_map.get(&[]), None);
/// assert_eq!(subset_map.get(&[7]), None);
/// assert_eq!(subset_map.get(&[3, 2, 1]), None);
/// assert_eq!(subset_map.get(&[1, 3, 2]), None);
/// assert_eq!(subset_map.get(&[3, 2, 1]), None);
/// assert_eq!(subset_map.get(&[2, 1]), None);
/// ```
pub fn get<'a>(&'a self, subset: &[E]) -> Option<&'a P>
where
E: Eq,
{
get(subset, &self.nodes)
}
/// Looks up a payload by the given subset and returns the
/// corresponding owned value.
///
/// The function returns `None` regardless of wether
/// `subset` was part of the map or there was no payload
/// assigned to the given subset.
///
/// Only perfect matches on `subset` are returned. See `get`.
pub fn get_owned(&self, subset: &[E]) -> Option<P::Owned>
where
E: Eq,
P: ToOwned,
{
get(subset, &self.nodes).map(|p| p.to_owned())
}
/// Looks up a subset and maybe returns the assigned payload.
///
/// Elements in `subset` that are not part of the initial set are
/// skipped.
///
/// The returned `LookupResult` may still contain an optional
/// payload. None indicates that the subset was matched but
/// there was no payload for the given subset.
///
/// Use this method if you are interested whether there was
/// a matching subset and then process the maybe present payload.
/// Otherwise use `find` or `lookup`.
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::new(&[1u32, 2, 3], |x| {
/// if x == &[2] {
/// None
/// } else {
/// let payload = x.iter().cloned().collect::<Vec<_>>();
/// Some(payload)
/// }
/// });
///
/// let empty: &[u32] = &[];
///
/// // A perfect match with a payload:
/// let match_result = subset_map.lookup(&[1]);
/// assert_eq!(match_result.payload(), Some(&vec![1]));
/// assert_eq!(match_result.excluded_elements(), empty);
/// assert_eq!(match_result.is_match(), true);
/// assert_eq!(match_result.is_perfect(), true);
/// assert_eq!(match_result.is_excluded(), false);
///
/// // A perfect match that has no payload:
/// let match_result = subset_map.lookup(&[2]);
/// assert_eq!(match_result.payload(), None);
/// assert_eq!(match_result.excluded_elements(), empty);
/// assert_eq!(match_result.is_match(), true);
/// assert_eq!(match_result.is_perfect(), true);
/// assert_eq!(match_result.is_excluded(), false);
///
/// // There is no answer at all:
/// let match_result = subset_map.lookup(&[42]);
/// assert_eq!(match_result.is_no_match(), true);
/// assert_eq!(match_result.is_perfect(), false);
/// assert_eq!(match_result.is_excluded(), false);
/// assert_eq!(match_result.excluded_elements(), empty);
///
/// // A nearby match but that has a payload:
/// let match_result = subset_map.lookup(&[3,1]);
/// assert_eq!(match_result.payload(), Some(&vec![3]));
/// assert_eq!(match_result.excluded_elements(), &[1]);
/// assert_eq!(match_result.is_perfect(), false);
/// assert_eq!(match_result.is_excluded(), true);
/// assert_eq!(match_result.is_match(), true);
///
/// ```
pub fn lookup<'a>(&'a self, subset: &[E]) -> LookupResult<'a, E, P>
where
E: Eq,
{
lookup(subset, &self.nodes)
}
/// Finds a payload by the given subset.
///
/// Elements in `subset` that are not part of the initial set are
/// skipped.
///
/// If there was no match or no payload for the given subset
/// `FindResult::NotFound` is returned.
///
/// Use this function if you are mostly interested in
/// payloads and how they were matched. Otherwise
/// use `lookup` or `get`
///
/// # Example
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::new(&[1u32, 2, 3], |x| {
/// if x == &[2] {
/// None
/// } else {
/// let payload = x.iter().cloned().collect::<Vec<_>>();
/// Some(payload)
/// }
/// });
///
/// let empty: &[u32] = &[];
///
/// // A perfect match with a payload:
/// let match_result = subset_map.find(&[1]);
///
/// assert_eq!(match_result.payload(), Some(&vec![1]));
/// assert_eq!(match_result.is_found(), true);
/// assert_eq!(match_result.is_found_and_perfect(), true);
/// assert_eq!(match_result.is_found_and_excluded(), false);
/// assert_eq!(match_result.excluded_elements(), empty);
///
/// // A perfect match that has no payload:
/// let match_result = subset_map.find(&[2]);
///
/// assert_eq!(match_result.payload(), None);
/// assert_eq!(match_result.is_found(), false);
/// assert_eq!(match_result.is_found_and_perfect(), false);
/// assert_eq!(match_result.is_found_and_excluded(), false);
/// assert_eq!(match_result.excluded_elements(), empty);
///
/// // There is no answer at all:
/// let match_result = subset_map.find(&[42]);
///
/// assert_eq!(match_result.payload(), None);
/// assert_eq!(match_result.is_not_found(), true);
/// assert_eq!(match_result.is_found_and_perfect(), false);
/// assert_eq!(match_result.is_found_and_excluded(), false);
/// assert_eq!(match_result.excluded_elements(), empty);
///
/// // A nearby match but that has a payload:
/// let match_result = subset_map.find(&[3,1]);
///
/// assert_eq!(match_result.is_found_and_perfect(), false);
/// assert_eq!(match_result.is_found_and_excluded(), true);
/// assert_eq!(match_result.is_found(), true);
/// assert_eq!(match_result.payload(), Some(&vec![3]));
/// assert_eq!(match_result.excluded_elements(), &[1]);
/// ```
pub fn find<'a>(&'a self, subset: &[E]) -> FindResult<'a, E, P>
where
E: Eq,
{
match self.lookup(subset) {
LookupResult::Perfect(Some(p)) => FindResult::Perfect(p),
LookupResult::Perfect(None) => FindResult::NotFound,
LookupResult::Excluded(Some(p), e) => FindResult::Excluded(p, e),
LookupResult::Excluded(None, _) => FindResult::NotFound,
LookupResult::NoMatch => FindResult::NotFound,
}
}
/// Sets the payload of all subsets to `None`
/// where the given payload does not fulfill the `predicate`
pub fn filter_values<F>(&mut self, mut predicate: F)
where
F: FnMut(&P) -> bool,
{
self.nodes
.iter_mut()
.for_each(|n| n.filter_values(&mut predicate))
}
/// Executes the given mutable closure `f`
/// on the value of each node.
pub fn walk_values<F>(&self, mut f: F)
where
F: FnMut(&P),
{
self.nodes.iter().for_each(|n| n.walk_values(&mut f))
}
/// Executes the given mutable closure `f`
/// on the value of each node until the
/// first closure returns false.
pub fn walk_values_until<F>(&self, mut f: F)
where
F: FnMut(&P) -> bool,
{
for node in &self.nodes {
if !node.walk_values_until(&mut f) {
return;
}
}
}
/// Executes the given mutable closure `f`
/// on the payload of each node
pub fn walk_payloads<F>(&self, mut f: F)
where
F: FnMut(Option<&P>),
{
self.nodes.iter().for_each(|n| n.walk_payloads(&mut f))
}
/// Executes the given mutable closure `f`
/// on the payload of each node until the
/// first closure returns false.
pub fn walk_payloads_until<F>(&self, mut f: F)
where
F: FnMut(Option<&P>) -> bool,
{
for node in &self.nodes {
if !node.walk_payloads_until(&mut f) {
return;
}
}
}
/// Walk all elements with their payloads
pub fn walk<F>(&self, mut f: F)
where
F: FnMut(&[&E], Option<&P>),
{
self.nodes.iter().for_each(|n| n.walk(&mut f))
}
/// Executes the given mutable closure `f`
/// on the payload of each node
pub fn for_each_value<F>(&self, mut f: F)
where
F: FnMut(&P),
{
self.walk_values_until(|p| {
f(p);
true
})
}
/// Executes the given mutable closure `f`
/// on the payload of each node
pub fn for_each_payload<F>(&self, mut f: F)
where
F: FnMut(Option<&P>),
{
self.walk_payloads_until(|p| {
f(p);
true
})
}
/// Returns true if there are nodes and all
/// of these have a payload set.
pub fn all_subsets_have_values(&self) -> bool {
if self.is_empty() {
return false;
}
let mut all_set = true;
self.walk_payloads_until(|p| {
if p.is_none() {
all_set = false;
false
} else {
true
}
});
all_set
}
/// Returns true if there are no subsets or all
/// of these have no payload set.
///
/// # Example
///
/// An empty map has no values:
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::<u8, u8>::with_default(&[]);
///
/// assert_eq!(subset_map.no_subset_with_value(), true);
/// ```
///
/// An map with a set entry has values:
///
/// ```
/// use subset_map::*;
///
/// let subset_map = SubsetMap::<u8, u8>::with_default(&[1]);
///
/// assert_eq!(subset_map.no_subset_with_value(), false);
/// ```
///
/// An non empty map where at least one subset has a value:
///
/// ```
/// use subset_map::*;
///
/// let mut subset_map = SubsetMap::fill(&[1, 2], |c| c.len());
///
/// subset_map.filter_values(|p| *p == 2);
///
/// assert_eq!(subset_map.no_subset_with_value(), false);
/// ```
///
/// An non empty map where no subset has a value:
///
/// ```
/// use subset_map::*;
///
/// let mut subset_map = SubsetMap::<u8, u8>::with_default(&[1, 2]);
///
/// // Set all payloads to `None`
/// subset_map.filter_values(|p| false);
///
/// assert_eq!(subset_map.no_subset_with_value(), true);
/// ```
pub fn no_subset_with_value(&self) -> bool {
if self.is_empty() {
return true;
}
let mut no_value_set = true;
self.walk_payloads_until(|p| {
if p.is_some() {
no_value_set = false;
false
} else {
true
}
});
no_value_set
}
/// Returns true if the map is empty and contains no subsets.
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
/// The number of subsets in this map
pub fn size(&self) -> usize {
2usize.pow(self.nodes.len() as u32) - 1
}
}
impl<E, P> Default for SubsetMap<E, P> {
fn default() -> Self {
SubsetMap {
nodes: Default::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
struct SubsetMapNode<E, P> {
pub element: E,
pub payload: Option<P>,
pub nodes: Nodes<E, P>,
}
impl<E, P> SubsetMapNode<E, P> {
pub fn filter_values<F>(&mut self, predicate: &mut F)
where
F: FnMut(&P) -> bool,
{
let keep = self.payload.as_ref().map(|p| predicate(p)).unwrap_or(true);
if !keep {
self.payload = None;
}
self.nodes
.iter_mut()
.for_each(|n| n.filter_values(predicate))
}
pub fn walk_values<F>(&self, f: &mut F)
where
F: FnMut(&P),
{
if let Some(ref payload) = self.payload {
f(payload);
}
self.nodes.iter().for_each(|n| n.walk_values(f))
}
pub fn walk_payloads<F>(&self, f: &mut F)
where
F: FnMut(Option<&P>),
{
f(self.payload.as_ref());
self.nodes.iter().for_each(|n| n.walk_payloads(f))
}
pub fn walk_values_until<F>(&self, f: &mut F) -> bool
where
F: FnMut(&P) -> bool,
{
let go_on = if let Some(ref payload) = self.payload {
f(payload)
} else {
true
};
if go_on {
for node in &self.nodes {
if !node.walk_values_until(f) {
return false;
}
}
}
true
}
pub fn walk_payloads_until<F>(&self, f: &mut F) -> bool
where
F: FnMut(Option<&P>) -> bool,
{
if f(self.payload.as_ref()) {
for node in &self.nodes {
if !node.walk_payloads_until(f) {
return false;
}
}
true
} else {
false
}
}
pub fn walk<F>(&self, mut f: F)
where
F: FnMut(&[&E], Option<&P>),
{
let mut elements = Vec::new();
self.walk_internal(&mut elements, &mut f)
}
fn walk_internal<'a, F>(&'a self, elements: &mut Vec<&'a E>, f: &mut F)
where
F: FnMut(&[&E], Option<&P>),
{
elements.push(&self.element);
f(elements.as_slice(), self.payload.as_ref());
self.nodes.iter().for_each(|n| n.walk_internal(elements, f));
elements.pop();
}
}
/// The result of `SubsetMap::lookup`.
///
/// It can either be a perfect match on the subset
/// or a match where some elements of the input set
/// had to be excluded.
///
/// A value of `None` for the payload indicates
/// that there was a match for a given subset but
/// nevertheless there was no payload stored for
/// that subset.
#[derive(Debug)]
pub enum LookupResult<'a, E, P: 'a> {
/// The input set exactly matched a combination
/// of the original set.
Perfect(Option<&'a P>),
/// There were some elements in the input set that had
/// to be excluded to match a subset of the original set
///
/// The excluded elements are returned.
Excluded(Option<&'a P>, Vec<E>),
/// There was no match at all for the given subset
NoMatch,
}
impl<'a, E, P> LookupResult<'a, E, P> {
pub fn payload(&self) -> Option<&P> {
match *self {
LookupResult::Perfect(p) => p,
LookupResult::Excluded(p, _) => p,
LookupResult::NoMatch => None,
}
}
/// Returns the excluded elements if there was
/// a match at all.
///
/// If there was no match the returned slice
/// is also empty.
pub fn excluded_elements(&self) -> &[E] {
match *self {
LookupResult::Perfect(_) => &[],
LookupResult::Excluded(_, ref skipped) => &*skipped,
LookupResult::NoMatch => &[],
}
}
/// Returns `true` if there was a perfect match
pub fn is_perfect(&self) -> bool {
match *self {
LookupResult::Perfect(_) => true,
_ => false,
}
}
/// Returns `true` if there was a match
/// but some elements had to be excluded
pub fn is_excluded(&self) -> bool {
match *self {
LookupResult::Excluded(_, _) => true,
_ => false,
}
}
/// Returns `true` if there was no match at all
pub fn is_no_match(&self) -> bool {
!self.is_match()
}
/// Returns `true` if there was a match even
/// though some elements had to be excluded
pub fn is_match(&self) -> bool {
match *self {
LookupResult::NoMatch => false,
_ => true,
}
}
}
/// The result of `SubsetMap::find`.
///
/// It can either be a perfect match on the subset
/// or a match where some elements of the input set
/// had to be excluded.
///
/// For `FindResult::NotFound` no tracking of
/// excluded elements is done.
#[derive(Debug)]
pub enum FindResult<'a, E, P: 'a> {
/// The input set exactly matched a combination
/// of the original set and there was a payload.
Perfect(&'a P),
/// There were some elements in the input set that had
/// to be excluded to match a subset of the original set.
///
/// Still there was a payload at the given position.
///
/// The excluded elements are returned.
Excluded(&'a P, Vec<E>),
/// There was no match at all or the payload
/// for the matched subset was `None`
NotFound,
}
impl<'a, E, P> FindResult<'a, E, P> {
pub fn payload(&self) -> Option<&P> {
match *self {
FindResult::Perfect(p) => Some(p),
FindResult::Excluded(p, _) => Some(p),
FindResult::NotFound => None,
}
}
/// Returns the excluded elements if there was
/// a match at all.
///
/// If there was no match the returned slice
/// is also empty.
pub fn excluded_elements(&self) -> &[E] {
match *self {
FindResult::Perfect(_) => &[],
FindResult::Excluded(_, ref skipped) => &*skipped,
FindResult::NotFound => &[],
}
}
/// Returns `true` if there was a perfect match
pub fn is_found_and_perfect(&self) -> bool {
match *self {
FindResult::Perfect(_) => true,
_ => false,
}
}
/// Returns `true` if there was a match
/// but some elements had to be excluded
pub fn is_found_and_excluded(&self) -> bool {
match *self {
FindResult::Excluded(_, _) => true,
_ => false,
}
}
/// Returns `true` if there was no match
/// or if the payload for the matched subset was
/// `None`
pub fn is_not_found(&self) -> bool {
!self.is_found()
}
/// Returns `true` if there was a match even
/// though some elements had to be excluded
/// and if there was a payload for the matched
/// subset.
pub fn is_found(&self) -> bool {
match *self {
FindResult::NotFound => false,
_ => true,
}
}
}
fn init_root<E, P, F, X>(elements: &[E], init_with: &mut F) -> Result<SubsetMap<E, P>, X>
where
E: Clone,
F: FnMut(&[E]) -> Result<Option<P>, X>,
{
let mut stack = Vec::new();
let mut nodes = Vec::new();
for fixed in 0..elements.len() {
let element = elements[fixed].clone();
let payload = init_with(&elements[fixed..=fixed])?;
let mut node = SubsetMapNode {
element,
payload,
nodes: Vec::new(),
};
stack.clear();
stack.push(elements[fixed].clone());
init_node(elements, &mut stack, fixed, &mut node, init_with)?;
nodes.push(node)
}
Ok(SubsetMap { nodes })
}
fn init_node<E, P, F, X>(
elements: &[E],
stack: &mut Vec<E>,
fixed: usize,
into: &mut SubsetMapNode<E, P>,
init_with: &mut F,
) -> Result<(), X>
where
E: Clone,
F: FnMut(&[E]) -> Result<Option<P>, X>,
{
for fixed in fixed + 1..elements.len() {
stack.push(elements[fixed].clone());
let mut node = SubsetMapNode {
element: elements[fixed].clone(),
payload: init_with(&stack)?,
nodes: Vec::new(),
};
let _ = init_node(elements, stack, fixed, &mut node, init_with);
stack.pop();
into.nodes.push(node);
}
Ok(())
}
fn get<'a, 'b, E, P>(subset: &'b [E], nodes: &'a [SubsetMapNode<E, P>]) -> Option<&'a P>
where
E: Eq,
{
let mut nodes = nodes;
let mut result = None;
for element in subset {
if let Some(node) = nodes.iter().find(|n| n.element == *element) {
result = node.payload.as_ref();
nodes = &node.nodes;
} else {
return None;
}
}
result
}
fn lookup<'a, 'b, E, P>(subset: &'b [E], nodes: &'a [SubsetMapNode<E, P>]) -> LookupResult<'a, E, P>
where
E: Eq + Clone,
{
let mut excluded = Vec::new();
let mut nodes = nodes;
let mut result_node = None;
for element in subset {
if let Some(node) = nodes.iter().find(|n| n.element == *element) {
result_node = Some(node);
nodes = &node.nodes;
} else {
excluded.push(element.clone())
}
}
if let Some(result_node) = result_node {
if excluded.is_empty() {
LookupResult::Perfect(result_node.payload.as_ref())
} else {
LookupResult::Excluded(result_node.payload.as_ref(), excluded)
}
} else {
LookupResult::NoMatch
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_empty() {
let sample = SubsetMap::<u32, ()>::default();
assert!(sample.is_empty());
}
#[test]
fn one_element() {
let sample = SubsetMap::fill(&[1], |_| 1);
assert_eq!(sample.get(&[1]), Some(&1));
assert_eq!(sample.get(&[]), None);
assert_eq!(sample.get(&[2]), None);
}
#[test]
fn two_elements() {
let sample = SubsetMap::fill(&[1, 2], |x| x.iter().sum::<i32>());
assert_eq!(sample.get(&[1]), Some(&1));
assert_eq!(sample.get(&[2]), Some(&2));
assert_eq!(sample.get(&[1, 2]), Some(&3));
assert_eq!(sample.get(&[]), None);
assert_eq!(sample.get(&[2, 1]), None);
assert_eq!(sample.get(&[0]), None);
assert_eq!(sample.get(&[0, 1]), None);
}
#[test]
fn three_elements() {
let sample = SubsetMap::fill(&[1, 2, 3], |x| x.iter().sum::<i32>());
assert_eq!(sample.get(&[1]), Some(&1));
assert_eq!(sample.get(&[2]), Some(&2));
assert_eq!(sample.get(&[3]), Some(&3));
assert_eq!(sample.get(&[1, 2]), Some(&3));
assert_eq!(sample.get(&[2, 3]), Some(&5));
assert_eq!(sample.get(&[1, 3]), Some(&4));
assert_eq!(sample.get(&[1, 2, 3]), Some(&6));
assert_eq!(sample.get(&[]), None);
assert_eq!(sample.get(&[2, 1]), None);
assert_eq!(sample.get(&[0]), None);
assert_eq!(sample.get(&[0, 1]), None);
}
#[test]
fn three_elements_identity_vec() {
let sample = SubsetMap::fill(&[1, 2, 3], |x| x.to_vec());
assert_eq!(sample.get(&[1]), Some(&vec![1]));
assert_eq!(sample.get(&[2]), Some(&vec![2]));
assert_eq!(sample.get(&[3]), Some(&vec![3]));
assert_eq!(sample.get(&[1, 2]), Some(&vec![1, 2]));
assert_eq!(sample.get(&[2, 3]), Some(&vec![2, 3]));
assert_eq!(sample.get(&[1, 3]), Some(&vec![1, 3]));
assert_eq!(sample.get(&[1, 2, 3]), Some(&vec![1, 2, 3]));
}
#[test]
fn walk_5_elems_keeps_order() {
let elements: Vec<_> = (0..5).collect();
let mut n = 0;
let map = SubsetMap::fill(&elements, |_x| {
n += 1;
n
});
let mut n = 0;
map.walk(|_elements, payload| {
n += 1;
assert_eq!(payload, Some(&n));
})
}
#[test]
fn test_lookup_result() {
let subset_map = SubsetMap::new(&[1u32, 2, 3, 4], |x| {
if x == &[2, 3] {
None
} else {
let payload = x.iter().cloned().collect::<Vec<_>>();
Some(payload)
}
});
let empty: &[u32] = &[];
let match_result = subset_map.lookup(&[]);
assert_eq!(match_result.payload(), None);
assert_eq!(match_result.excluded_elements(), empty);
assert_eq!(match_result.is_match(), false);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), false);
let match_result = subset_map.lookup(&[1]);
assert_eq!(match_result.payload(), Some(&vec![1]));
assert_eq!(match_result.excluded_elements(), empty);
assert_eq!(match_result.is_match(), true);
assert_eq!(match_result.is_perfect(), true);
assert_eq!(match_result.is_excluded(), false);
let match_result = subset_map.lookup(&[2, 3]);
assert_eq!(match_result.payload(), None);
assert_eq!(match_result.excluded_elements(), empty);
assert_eq!(match_result.is_match(), true);
assert_eq!(match_result.is_perfect(), true);
assert_eq!(match_result.is_excluded(), false);
let match_result = subset_map.lookup(&[42]);
assert_eq!(match_result.is_no_match(), true);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), false);
assert_eq!(match_result.excluded_elements(), empty);
let match_result = subset_map.lookup(&[42, 3]);
assert_eq!(match_result.payload(), Some(&vec![3]));
assert_eq!(match_result.excluded_elements(), &[42]);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), true);
assert_eq!(match_result.is_match(), true);
let match_result = subset_map.lookup(&[3, 1]);
assert_eq!(match_result.payload(), Some(&vec![3]));
assert_eq!(match_result.excluded_elements(), &[1]);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), true);
assert_eq!(match_result.is_match(), true);
let match_result = subset_map.lookup(&[3, 1, 4, 2]);
assert_eq!(match_result.payload(), Some(&vec![3, 4]));
assert_eq!(match_result.excluded_elements(), &[1, 2]);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), true);
assert_eq!(match_result.is_match(), true);
let match_result = subset_map.lookup(&[4, 3, 2, 1]);
assert_eq!(match_result.payload(), Some(&vec![4]));
assert_eq!(match_result.excluded_elements(), &[3, 2, 1]);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), true);
assert_eq!(match_result.is_match(), true);
let match_result = subset_map.lookup(&[99, 2, 1, 77, 78, 3, 4, 2, 1, 2]);
assert_eq!(match_result.payload(), Some(&vec![2, 3, 4]));
assert_eq!(match_result.excluded_elements(), &[99, 1, 77, 78, 2, 1, 2]);
assert_eq!(match_result.is_perfect(), false);
assert_eq!(match_result.is_excluded(), true);
assert_eq!(match_result.is_match(), true);
}
}
| 30.818803 | 103 | 0.540324 |
db1d362fa86fc63cd2b9792c4493a165f734e270
| 1,135 |
use crate::{forward, forward_val, Context};
#[test]
fn call_symbol_and_check_return_type() {
let mut context = Context::new();
let init = r#"
var sym = Symbol();
"#;
eprintln!("{}", forward(&mut context, init));
let sym = forward_val(&mut context, "sym").unwrap();
assert!(sym.is_symbol());
}
#[test]
fn print_symbol_expect_description() {
let mut context = Context::new();
let init = r#"
var sym = Symbol("Hello");
"#;
eprintln!("{}", forward(&mut context, init));
let sym = forward_val(&mut context, "sym.toString()").unwrap();
assert_eq!(sym.display().to_string(), "\"Symbol(Hello)\"");
}
#[test]
fn symbol_access() {
let mut context = Context::new();
let init = r#"
var x = {};
var sym1 = Symbol("Hello");
var sym2 = Symbol("Hello");
x[sym1] = 10;
x[sym2] = 20;
"#;
forward_val(&mut context, init).unwrap();
assert_eq!(forward(&mut context, "x[sym1]"), "10");
assert_eq!(forward(&mut context, "x[sym2]"), "20");
assert_eq!(forward(&mut context, "x['Symbol(Hello)']"), "undefined");
}
| 28.375 | 73 | 0.56652 |
29c66d0d04daf12bdb20fef75eb86203bd7161a9
| 740 |
use keyberon::key_code::{KeyCode, KbHidReport};
use makbe_ff::reporter::Reporter;
use xiao_m0::UsbBus;
use usb_device::device::UsbDevice;
use keyberon::Class;
use keyberon::keyboard::Leds;
pub struct UsbReporter<'a, L: Leds> {
pub usb_class: Class<'a, UsbBus, L>,
pub usb_dev: UsbDevice<'a, UsbBus>
}
impl<L: Leds> Reporter for UsbReporter<'_, L> {
fn send_codes(&mut self, codes: &[KeyCode]) {
let mut report: KbHidReport = KbHidReport::default(); //codes.collect();
for kc in codes {
report.pressed(kc.clone());
}
if self.usb_class.device_mut().set_keyboard_report(report.clone()) {
while let Ok(0) = self.usb_class.write(report.as_bytes()) {}
}
}
}
| 26.428571 | 82 | 0.636486 |
e88257dcd4cf874490d6186b6a0deee09306681b
| 37,073 |
// 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.
#![allow(dead_code)] // FFI wrappers
use llvm;
use llvm::{AtomicBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
use llvm::{Opcode, IntPredicate, RealPredicate, False, OperandBundleDef};
use llvm::{ValueRef, BasicBlockRef, BuilderRef, ModuleRef};
use base;
use common::*;
use machine::llalign_of_pref;
use type_::Type;
use value::Value;
use util::nodemap::FnvHashMap;
use libc::{c_uint, c_char};
use std::ffi::CString;
use std::ptr;
use syntax_pos::Span;
pub struct Builder<'a, 'tcx: 'a> {
pub llbuilder: BuilderRef,
pub ccx: &'a CrateContext<'a, 'tcx>,
}
// This is a really awful way to get a zero-length c-string, but better (and a
// lot more efficient) than doing str::as_c_str("", ...) every time.
pub fn noname() -> *const c_char {
static CNULL: c_char = 0;
&CNULL
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
pub fn new(ccx: &'a CrateContext<'a, 'tcx>) -> Builder<'a, 'tcx> {
Builder {
llbuilder: ccx.raw_builder(),
ccx: ccx,
}
}
pub fn count_insn(&self, category: &str) {
if self.ccx.sess().trans_stats() {
self.ccx.stats().n_llvm_insns.set(self.ccx
.stats()
.n_llvm_insns
.get() + 1);
}
self.ccx.count_llvm_insn();
if self.ccx.sess().count_llvm_insns() {
base::with_insn_ctxt(|v| {
let mut h = self.ccx.stats().llvm_insns.borrow_mut();
// Build version of path with cycles removed.
// Pass 1: scan table mapping str -> rightmost pos.
let mut mm = FnvHashMap();
let len = v.len();
let mut i = 0;
while i < len {
mm.insert(v[i], i);
i += 1;
}
// Pass 2: concat strings for each elt, skipping
// forwards over any cycles by advancing to rightmost
// occurrence of each element in path.
let mut s = String::from(".");
i = 0;
while i < len {
i = mm[v[i]];
s.push('/');
s.push_str(v[i]);
i += 1;
}
s.push('/');
s.push_str(category);
let n = match h.get(&s) {
Some(&n) => n,
_ => 0
};
h.insert(s, n+1);
})
}
}
pub fn position_before(&self, insn: ValueRef) {
unsafe {
llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
}
}
pub fn position_at_end(&self, llbb: BasicBlockRef) {
unsafe {
llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
}
}
pub fn position_at_start(&self, llbb: BasicBlockRef) {
unsafe {
llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
}
}
pub fn ret_void(&self) {
self.count_insn("retvoid");
unsafe {
llvm::LLVMBuildRetVoid(self.llbuilder);
}
}
pub fn ret(&self, v: ValueRef) {
self.count_insn("ret");
unsafe {
llvm::LLVMBuildRet(self.llbuilder, v);
}
}
pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) {
unsafe {
llvm::LLVMBuildAggregateRet(self.llbuilder,
ret_vals.as_ptr(),
ret_vals.len() as c_uint);
}
}
pub fn br(&self, dest: BasicBlockRef) {
self.count_insn("br");
unsafe {
llvm::LLVMBuildBr(self.llbuilder, dest);
}
}
pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) {
self.count_insn("condbr");
unsafe {
llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
}
}
pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) -> ValueRef {
unsafe {
llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
}
}
pub fn indirect_br(&self, addr: ValueRef, num_dests: usize) {
self.count_insn("indirectbr");
unsafe {
llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
}
}
pub fn invoke(&self,
llfn: ValueRef,
args: &[ValueRef],
then: BasicBlockRef,
catch: BasicBlockRef,
bundle: Option<&OperandBundleDef>) -> ValueRef {
self.count_insn("invoke");
debug!("Invoke {:?} with args ({})",
Value(llfn),
args.iter()
.map(|&v| format!("{:?}", Value(v)))
.collect::<Vec<String>>()
.join(", "));
check_call("invoke", llfn, args);
let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut());
unsafe {
llvm::LLVMRustBuildInvoke(self.llbuilder,
llfn,
args.as_ptr(),
args.len() as c_uint,
then,
catch,
bundle,
noname())
}
}
pub fn unreachable(&self) {
self.count_insn("unreachable");
unsafe {
llvm::LLVMBuildUnreachable(self.llbuilder);
}
}
/* Arithmetic */
pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("add");
unsafe {
llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
}
}
pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("nswadd");
unsafe {
llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
}
}
pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("nuwadd");
unsafe {
llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fadd");
unsafe {
llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fadd");
unsafe {
let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
llvm::LLVMRustSetHasUnsafeAlgebra(instr);
instr
}
}
pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("sub");
unsafe {
llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
}
}
pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("nwsub");
unsafe {
llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
}
}
pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("nuwsub");
unsafe {
llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("sub");
unsafe {
llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("sub");
unsafe {
let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
llvm::LLVMRustSetHasUnsafeAlgebra(instr);
instr
}
}
pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("mul");
unsafe {
llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
}
}
pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("nswmul");
unsafe {
llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
}
}
pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("nuwmul");
unsafe {
llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fmul");
unsafe {
llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fmul");
unsafe {
let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
llvm::LLVMRustSetHasUnsafeAlgebra(instr);
instr
}
}
pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("udiv");
unsafe {
llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
}
}
pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("sdiv");
unsafe {
llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
}
}
pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("exactsdiv");
unsafe {
llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fdiv");
unsafe {
llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
}
}
pub fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fdiv");
unsafe {
let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
llvm::LLVMRustSetHasUnsafeAlgebra(instr);
instr
}
}
pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("urem");
unsafe {
llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
}
}
pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("srem");
unsafe {
llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
}
}
pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("frem");
unsafe {
llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
}
}
pub fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("frem");
unsafe {
let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
llvm::LLVMRustSetHasUnsafeAlgebra(instr);
instr
}
}
pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("shl");
unsafe {
llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
}
}
pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("lshr");
unsafe {
llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
}
}
pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("ashr");
unsafe {
llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
}
}
pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("and");
unsafe {
llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
}
}
pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("or");
unsafe {
llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
}
}
pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("xor");
unsafe {
llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
}
}
pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef)
-> ValueRef {
self.count_insn("binop");
unsafe {
llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
}
}
pub fn neg(&self, v: ValueRef) -> ValueRef {
self.count_insn("neg");
unsafe {
llvm::LLVMBuildNeg(self.llbuilder, v, noname())
}
}
pub fn nswneg(&self, v: ValueRef) -> ValueRef {
self.count_insn("nswneg");
unsafe {
llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
}
}
pub fn nuwneg(&self, v: ValueRef) -> ValueRef {
self.count_insn("nuwneg");
unsafe {
llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
}
}
pub fn fneg(&self, v: ValueRef) -> ValueRef {
self.count_insn("fneg");
unsafe {
llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
}
}
pub fn not(&self, v: ValueRef) -> ValueRef {
self.count_insn("not");
unsafe {
llvm::LLVMBuildNot(self.llbuilder, v, noname())
}
}
pub fn alloca(&self, ty: Type, name: &str) -> ValueRef {
self.count_insn("alloca");
unsafe {
if name.is_empty() {
llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname())
} else {
let name = CString::new(name).unwrap();
llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(),
name.as_ptr())
}
}
}
pub fn free(&self, ptr: ValueRef) {
self.count_insn("free");
unsafe {
llvm::LLVMBuildFree(self.llbuilder, ptr);
}
}
pub fn load(&self, ptr: ValueRef) -> ValueRef {
self.count_insn("load");
unsafe {
llvm::LLVMBuildLoad(self.llbuilder, ptr, noname())
}
}
pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef {
self.count_insn("load.volatile");
unsafe {
let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
llvm::LLVMSetVolatile(insn, llvm::True);
insn
}
}
pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef {
self.count_insn("load.atomic");
unsafe {
let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
let align = llalign_of_pref(self.ccx, ty.element_type());
llvm::LLVMBuildAtomicLoad(self.llbuilder, ptr, noname(), order,
align as c_uint)
}
}
pub fn load_range_assert(&self, ptr: ValueRef, lo: u64,
hi: u64, signed: llvm::Bool) -> ValueRef {
let value = self.load(ptr);
unsafe {
let t = llvm::LLVMGetElementType(llvm::LLVMTypeOf(ptr));
let min = llvm::LLVMConstInt(t, lo, signed);
let max = llvm::LLVMConstInt(t, hi, signed);
let v = [min, max];
llvm::LLVMSetMetadata(value, llvm::MD_range as c_uint,
llvm::LLVMMDNodeInContext(self.ccx.llcx(),
v.as_ptr(),
v.len() as c_uint));
}
value
}
pub fn load_nonnull(&self, ptr: ValueRef) -> ValueRef {
let value = self.load(ptr);
unsafe {
llvm::LLVMSetMetadata(value, llvm::MD_nonnull as c_uint,
llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0));
}
value
}
pub fn store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef {
debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
assert!(!self.llbuilder.is_null());
self.count_insn("store");
unsafe {
llvm::LLVMBuildStore(self.llbuilder, val, ptr)
}
}
pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef {
debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
assert!(!self.llbuilder.is_null());
self.count_insn("store.volatile");
unsafe {
let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
llvm::LLVMSetVolatile(insn, llvm::True);
insn
}
}
pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) {
debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
self.count_insn("store.atomic");
unsafe {
let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
let align = llalign_of_pref(self.ccx, ty.element_type());
llvm::LLVMBuildAtomicStore(self.llbuilder, val, ptr, order, align as c_uint);
}
}
pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
self.count_insn("gep");
unsafe {
llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
indices.len() as c_uint, noname())
}
}
// Simple wrapper around GEP that takes an array of ints and wraps them
// in C_i32()
#[inline]
pub fn gepi(&self, base: ValueRef, ixs: &[usize]) -> ValueRef {
// Small vector optimization. This should catch 100% of the cases that
// we care about.
if ixs.len() < 16 {
let mut small_vec = [ C_i32(self.ccx, 0); 16 ];
for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs) {
*small_vec_e = C_i32(self.ccx, ix as i32);
}
self.inbounds_gep(base, &small_vec[..ixs.len()])
} else {
let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>();
self.count_insn("gepi");
self.inbounds_gep(base, &v[..])
}
}
pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
self.count_insn("inboundsgep");
unsafe {
llvm::LLVMBuildInBoundsGEP(
self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
}
}
pub fn struct_gep(&self, ptr: ValueRef, idx: usize) -> ValueRef {
self.count_insn("structgep");
unsafe {
llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
}
}
pub fn global_string(&self, _str: *const c_char) -> ValueRef {
self.count_insn("globalstring");
unsafe {
llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
}
}
pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
self.count_insn("globalstringptr");
unsafe {
llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
}
}
/* Casts */
pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("trunc");
unsafe {
llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("zext");
unsafe {
llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("sext");
unsafe {
llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("fptoui");
unsafe {
llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("fptosi");
unsafe {
llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
}
}
pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("uitofp");
unsafe {
llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("sitofp");
unsafe {
llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("fptrunc");
unsafe {
llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("fpext");
unsafe {
llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("ptrtoint");
unsafe {
llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("inttoptr");
unsafe {
llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("bitcast");
unsafe {
llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("zextorbitcast");
unsafe {
llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("sextorbitcast");
unsafe {
llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("truncorbitcast");
unsafe {
llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("cast");
unsafe {
llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
}
}
pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("pointercast");
unsafe {
llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn intcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("intcast");
unsafe {
llvm::LLVMBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
self.count_insn("fpcast");
unsafe {
llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
}
}
/* Comparisons */
pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("icmp");
unsafe {
llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
}
}
pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("fcmp");
unsafe {
llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
}
}
/* Miscellaneous instructions */
pub fn empty_phi(&self, ty: Type) -> ValueRef {
self.count_insn("emptyphi");
unsafe {
llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
}
}
pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
assert_eq!(vals.len(), bbs.len());
let phi = self.empty_phi(ty);
self.count_insn("addincoming");
unsafe {
llvm::LLVMAddIncoming(phi, vals.as_ptr(),
bbs.as_ptr(),
vals.len() as c_uint);
phi
}
}
pub fn add_span_comment(&self, sp: Span, text: &str) {
if self.ccx.sess().asm_comments() {
let s = format!("{} ({})",
text,
self.ccx.sess().codemap().span_to_string(sp));
debug!("{}", &s[..]);
self.add_comment(&s[..]);
}
}
pub fn add_comment(&self, text: &str) {
if self.ccx.sess().asm_comments() {
let sanitized = text.replace("$", "");
let comment_text = format!("{} {}", "#",
sanitized.replace("\n", "\n\t# "));
self.count_insn("inlineasm");
let comment_text = CString::new(comment_text).unwrap();
let asm = unsafe {
llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.ccx)).to_ref(),
comment_text.as_ptr(), noname(), False,
False)
};
self.call(asm, &[], None);
}
}
pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
inputs: &[ValueRef], output: Type,
volatile: bool, alignstack: bool,
dia: AsmDialect) -> ValueRef {
self.count_insn("inlineasm");
let volatile = if volatile { llvm::True }
else { llvm::False };
let alignstack = if alignstack { llvm::True }
else { llvm::False };
let argtys = inputs.iter().map(|v| {
debug!("Asm Input Type: {:?}", Value(*v));
val_ty(*v)
}).collect::<Vec<_>>();
debug!("Asm Output Type: {:?}", output);
let fty = Type::func(&argtys[..], &output);
unsafe {
let v = llvm::LLVMInlineAsm(
fty.to_ref(), asm, cons, volatile, alignstack, dia as c_uint);
self.call(v, inputs, None)
}
}
pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
bundle: Option<&OperandBundleDef>) -> ValueRef {
self.count_insn("call");
debug!("Call {:?} with args ({})",
Value(llfn),
args.iter()
.map(|&v| format!("{:?}", Value(v)))
.collect::<Vec<String>>()
.join(", "));
check_call("call", llfn, args);
let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut());
unsafe {
llvm::LLVMRustBuildCall(self.llbuilder, llfn, args.as_ptr(),
args.len() as c_uint, bundle, noname())
}
}
pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
self.count_insn("select");
unsafe {
llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
}
}
pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
self.count_insn("vaarg");
unsafe {
llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
}
}
pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
self.count_insn("extractelement");
unsafe {
llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
}
}
pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
self.count_insn("insertelement");
unsafe {
llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
}
}
pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
self.count_insn("shufflevector");
unsafe {
llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
}
}
pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef {
unsafe {
let elt_ty = val_ty(elt);
let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0));
let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64);
self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
}
}
pub fn extract_value(&self, agg_val: ValueRef, idx: usize) -> ValueRef {
self.count_insn("extractvalue");
unsafe {
llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
}
}
pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
idx: usize) -> ValueRef {
self.count_insn("insertvalue");
unsafe {
llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
noname())
}
}
pub fn is_null(&self, val: ValueRef) -> ValueRef {
self.count_insn("isnull");
unsafe {
llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
}
}
pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
self.count_insn("isnotnull");
unsafe {
llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
}
}
pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
self.count_insn("ptrdiff");
unsafe {
llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
}
}
pub fn trap(&self) {
unsafe {
let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder);
let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb);
let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_);
let p = "llvm.trap\0".as_ptr();
let t: ValueRef = llvm::LLVMGetNamedFunction(m, p as *const _);
assert!((t as isize != 0));
let args: &[ValueRef] = &[];
self.count_insn("trap");
llvm::LLVMRustBuildCall(self.llbuilder, t,
args.as_ptr(), args.len() as c_uint,
ptr::null_mut(),
noname());
}
}
pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef,
num_clauses: usize,
llfn: ValueRef) -> ValueRef {
self.count_insn("landingpad");
unsafe {
llvm::LLVMRustBuildLandingPad(self.llbuilder, ty.to_ref(), pers_fn,
num_clauses as c_uint, noname(), llfn)
}
}
pub fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) {
unsafe {
llvm::LLVMAddClause(landing_pad, clause);
}
}
pub fn set_cleanup(&self, landing_pad: ValueRef) {
self.count_insn("setcleanup");
unsafe {
llvm::LLVMSetCleanup(landing_pad, llvm::True);
}
}
pub fn resume(&self, exn: ValueRef) -> ValueRef {
self.count_insn("resume");
unsafe {
llvm::LLVMBuildResume(self.llbuilder, exn)
}
}
pub fn cleanup_pad(&self,
parent: Option<ValueRef>,
args: &[ValueRef]) -> ValueRef {
self.count_insn("cleanuppad");
let parent = parent.unwrap_or(ptr::null_mut());
let name = CString::new("cleanuppad").unwrap();
let ret = unsafe {
llvm::LLVMRustBuildCleanupPad(self.llbuilder,
parent,
args.len() as c_uint,
args.as_ptr(),
name.as_ptr())
};
assert!(!ret.is_null(), "LLVM does not have support for cleanuppad");
return ret
}
pub fn cleanup_ret(&self, cleanup: ValueRef,
unwind: Option<BasicBlockRef>) -> ValueRef {
self.count_insn("cleanupret");
let unwind = unwind.unwrap_or(ptr::null_mut());
let ret = unsafe {
llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
};
assert!(!ret.is_null(), "LLVM does not have support for cleanupret");
return ret
}
pub fn catch_pad(&self,
parent: ValueRef,
args: &[ValueRef]) -> ValueRef {
self.count_insn("catchpad");
let name = CString::new("catchpad").unwrap();
let ret = unsafe {
llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
args.len() as c_uint, args.as_ptr(),
name.as_ptr())
};
assert!(!ret.is_null(), "LLVM does not have support for catchpad");
return ret
}
pub fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef {
self.count_insn("catchret");
let ret = unsafe {
llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
};
assert!(!ret.is_null(), "LLVM does not have support for catchret");
return ret
}
pub fn catch_switch(&self,
parent: Option<ValueRef>,
unwind: Option<BasicBlockRef>,
num_handlers: usize) -> ValueRef {
self.count_insn("catchswitch");
let parent = parent.unwrap_or(ptr::null_mut());
let unwind = unwind.unwrap_or(ptr::null_mut());
let name = CString::new("catchswitch").unwrap();
let ret = unsafe {
llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
num_handlers as c_uint,
name.as_ptr())
};
assert!(!ret.is_null(), "LLVM does not have support for catchswitch");
return ret
}
pub fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) {
unsafe {
llvm::LLVMRustAddHandler(catch_switch, handler);
}
}
pub fn set_personality_fn(&self, personality: ValueRef) {
unsafe {
llvm::LLVMRustSetPersonalityFn(self.llbuilder, personality);
}
}
// Atomic Operations
pub fn atomic_cmpxchg(&self, dst: ValueRef,
cmp: ValueRef, src: ValueRef,
order: AtomicOrdering,
failure_order: AtomicOrdering,
weak: llvm::Bool) -> ValueRef {
unsafe {
llvm::LLVMBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
order, failure_order, weak)
}
}
pub fn atomic_rmw(&self, op: AtomicBinOp,
dst: ValueRef, src: ValueRef,
order: AtomicOrdering) -> ValueRef {
unsafe {
llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
}
}
pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
unsafe {
llvm::LLVMBuildAtomicFence(self.llbuilder, order, scope);
}
}
}
fn check_call(typ: &str, llfn: ValueRef, args: &[ValueRef]) {
if cfg!(debug_assertions) {
let mut fn_ty = val_ty(llfn);
// Strip off pointers
while fn_ty.kind() == llvm::TypeKind::Pointer {
fn_ty = fn_ty.element_type();
}
assert!(fn_ty.kind() == llvm::TypeKind::Function,
"builder::{} not passed a function", typ);
let param_tys = fn_ty.func_params();
let iter = param_tys.into_iter()
.zip(args.iter().map(|&v| val_ty(v)));
for (i, (expected_ty, actual_ty)) in iter.enumerate() {
if expected_ty != actual_ty {
bug!("Type mismatch in function call of {:?}. \
Expected {:?} for param {}, got {:?}",
Value(llfn),
expected_ty, i, actual_ty);
}
}
}
}
| 32.778957 | 95 | 0.52286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.