file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
revaultd.rs | bitcoin::{
secp256k1,
util::bip32::{ChildNumber, ExtendedPubKey},
Address, BlockHash, PublicKey as BitcoinPublicKey, Script, TxOut,
},
miniscript::descriptor::{DescriptorPublicKey, DescriptorTrait},
scripts::{
CpfpDescriptor, DepositDescriptor, DerivedCpfpDescriptor, DerivedDepositDescriptor,
DerivedUnvaultDescriptor, EmergencyAddress, UnvaultDescriptor,
},
transactions::{
CancelTransaction, DepositTransaction, EmergencyTransaction, UnvaultEmergencyTransaction,
UnvaultTransaction,
},
};
/// The status of a [Vault], depends both on the block chain and the set of pre-signed
/// transactions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VaultStatus {
/// The deposit transaction has less than 6 confirmations
Unconfirmed,
/// The deposit transaction has more than 6 confirmations
Funded,
/// The revocation transactions are signed by us
Securing,
/// The revocation transactions are signed by everyone
Secured,
/// The unvault transaction is signed (implies that the second emergency and the
/// cancel transaction are signed).
Activating,
/// The unvault transaction is signed (implies that the second emergency and the
/// cancel transaction are signed).
Active,
/// The unvault transaction has been broadcast
Unvaulting,
/// The unvault transaction is confirmed
Unvaulted,
/// The cancel transaction has been broadcast
Canceling,
/// The cancel transaction is confirmed
Canceled,
/// The first emergency transactions has been broadcast
EmergencyVaulting,
/// The first emergency transactions is confirmed
EmergencyVaulted,
/// The unvault emergency transactions has been broadcast
UnvaultEmergencyVaulting,
/// The unvault emergency transactions is confirmed
UnvaultEmergencyVaulted,
/// The spend transaction has been broadcast
Spending,
// TODO: At what depth do we forget it?
/// The spend transaction is confirmed
Spent,
}
impl TryFrom<u32> for VaultStatus {
type Error = ();
fn try_from(n: u32) -> Result<Self, Self::Error> {
match n {
0 => Ok(Self::Unconfirmed),
1 => Ok(Self::Funded),
2 => Ok(Self::Securing),
3 => Ok(Self::Secured),
4 => Ok(Self::Activating),
5 => Ok(Self::Active),
6 => Ok(Self::Unvaulting),
7 => Ok(Self::Unvaulted),
8 => Ok(Self::Canceling),
9 => Ok(Self::Canceled),
10 => Ok(Self::EmergencyVaulting),
11 => Ok(Self::EmergencyVaulted),
12 => Ok(Self::UnvaultEmergencyVaulting),
13 => Ok(Self::UnvaultEmergencyVaulted),
14 => Ok(Self::Spending),
15 => Ok(Self::Spent),
_ => Err(()),
}
}
}
impl FromStr for VaultStatus {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"unconfirmed" => Ok(Self::Unconfirmed),
"funded" => Ok(Self::Funded),
"securing" => Ok(Self::Securing),
"secured" => Ok(Self::Secured),
"activating" => Ok(Self::Activating),
"active" => Ok(Self::Active),
"unvaulting" => Ok(Self::Unvaulting),
"unvaulted" => Ok(Self::Unvaulted),
"canceling" => Ok(Self::Canceling),
"canceled" => Ok(Self::Canceled),
"emergencyvaulting" => Ok(Self::EmergencyVaulting),
"emergencyvaulted" => Ok(Self::EmergencyVaulted),
"unvaultemergencyvaulting" => Ok(Self::UnvaultEmergencyVaulting),
"unvaultemergencyvaulted" => Ok(Self::UnvaultEmergencyVaulted),
"spending" => Ok(Self::Spending),
"spent" => Ok(Self::Spent),
_ => Err(()),
}
}
}
impl fmt::Display for VaultStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match *self {
Self::Unconfirmed => "unconfirmed",
Self::Funded => "funded",
Self::Securing => "securing",
Self::Secured => "secured",
Self::Activating => "activating",
Self::Active => "active",
Self::Unvaulting => "unvaulting",
Self::Unvaulted => "unvaulted",
Self::Canceling => "canceling",
Self::Canceled => "canceled",
Self::EmergencyVaulting => "emergencyvaulting",
Self::EmergencyVaulted => "emergencyvaulted",
Self::UnvaultEmergencyVaulting => "unvaultemergencyvaulting",
Self::UnvaultEmergencyVaulted => "unvaultemergencyvaulted",
Self::Spending => "spending",
Self::Spent => "spent",
}
)
}
}
// An error related to the initialization of communication keys
#[derive(Debug)]
enum KeyError {
ReadingKey(io::Error),
WritingKey(io::Error),
}
impl fmt::Display for KeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::ReadingKey(e) => write!(f, "Error reading Noise key: '{}'", e),
Self::WritingKey(e) => write!(f, "Error writing Noise key: '{}'", e),
}
}
}
impl std::error::Error for KeyError {}
// The communication keys are (for now) hot, so we just create it ourselves on first run.
fn read_or_create_noise_key(secret_file: PathBuf) -> Result<NoisePrivKey, KeyError> {
let mut noise_secret = NoisePrivKey([0; 32]);
if!secret_file.as_path().exists() {
log::info!(
"No Noise private key at '{:?}', generating a new one",
secret_file
);
noise_secret = sodiumoxide::crypto::box_::gen_keypair().1;
// We create it in read-only but open it in write only.
let mut options = fs::OpenOptions::new();
options = options.write(true).create_new(true).clone();
// FIXME: handle Windows ACLs
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options = options.mode(0o400).clone();
}
let mut fd = options.open(secret_file).map_err(KeyError::WritingKey)?;
fd.write_all(&noise_secret.as_ref())
.map_err(KeyError::WritingKey)?;
} else {
let mut noise_secret_fd = fs::File::open(secret_file).map_err(KeyError::ReadingKey)?;
noise_secret_fd
.read_exact(&mut noise_secret.0)
.map_err(KeyError::ReadingKey)?;
}
// TODO: have a decent memory management and mlock() the key
assert!(noise_secret.0!= [0; 32]);
Ok(noise_secret)
}
/// A vault is defined as a confirmed utxo paying to the Vault Descriptor for which
/// we have a set of pre-signed transaction (emergency, cancel, unvault).
/// Depending on its status we may not yet be in possession of part -or the entirety-
/// of the pre-signed transactions.
/// Likewise, depending on our role (manager or stakeholder), we may not have the
/// emergency transactions.
pub struct _Vault {
pub deposit_txo: TxOut,
pub status: VaultStatus,
pub vault_tx: Option<DepositTransaction>,
pub emergency_tx: Option<EmergencyTransaction>,
pub unvault_tx: Option<UnvaultTransaction>,
pub cancel_tx: Option<CancelTransaction>,
pub unvault_emergency_tx: Option<UnvaultEmergencyTransaction>,
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct BlockchainTip {
pub height: u32,
pub hash: BlockHash,
}
/// Our global state
pub struct RevaultD {
// Bitcoind stuff
/// Everything we need to know to talk to bitcoind
pub bitcoind_config: BitcoindConfig,
/// Last block we heard about
pub tip: Option<BlockchainTip>,
/// Minimum confirmations before considering a deposit as mature
pub min_conf: u32,
// Scripts stuff
/// Who am i, and where am i in all this mess?
pub our_stk_xpub: Option<ExtendedPubKey>,
pub our_man_xpub: Option<ExtendedPubKey>,
/// The miniscript descriptor of vault's outputs scripts
pub deposit_descriptor: DepositDescriptor,
/// The miniscript descriptor of unvault's outputs scripts
pub unvault_descriptor: UnvaultDescriptor,
/// The miniscript descriptor of CPFP output scripts (in unvault and spend transaction)
pub cpfp_descriptor: CpfpDescriptor,
/// The Emergency address, only available if we are a stakeholder
pub emergency_address: Option<EmergencyAddress>,
/// We don't make an enormous deal of address reuse (we cancel to the same keys),
/// however we at least try to generate new addresses once they're used.
// FIXME: think more about desync reconciliation..
pub current_unused_index: ChildNumber,
/// The secp context required by the xpub one.. We'll eventually use it to verify keys.
pub secp_ctx: secp256k1::Secp256k1<secp256k1::VerifyOnly>,
/// The locktime to use on all created transaction. Always 0 for now.
pub lock_time: u32,
// Network stuff
/// The static private key we use to establish connections to servers. We reuse it, but Trevor
/// said it's fine! https://github.com/noiseprotocol/noise_spec/blob/master/noise.md#14-security-considerations
pub noise_secret: NoisePrivKey,
/// The ip:port the coordinator is listening on. TODO: Tor
pub coordinator_host: SocketAddr,
/// The static public key to enact the Noise channel with the Coordinator
pub coordinator_noisekey: NoisePubKey,
pub coordinator_poll_interval: time::Duration,
/// The ip:port (TODO: Tor) and Noise public key of each cosigning server, only set if we are
/// a manager.
pub cosigs: Option<Vec<(SocketAddr, NoisePubKey)>>,
// 'Wallet' stuff
/// A map from a scriptPubKey to a derivation index. Used to retrieve the actual public
/// keys used to generate a script from bitcoind until we can pass it xpub-expressed
/// Miniscript descriptors.
pub derivation_index_map: HashMap<Script, ChildNumber>,
/// The id of the wallet used in the db
pub wallet_id: Option<u32>,
// Misc stuff
/// We store all our data in one place, that's here.
pub data_dir: PathBuf,
/// Should we run as a daemon? (Default: yes)
pub daemon: bool,
// TODO: servers connection stuff
}
fn create_datadir(datadir_path: &PathBuf) -> Result<(), std::io::Error> {
#[cfg(unix)]
return {
use fs::DirBuilder;
use std::os::unix::fs::DirBuilderExt;
let mut builder = DirBuilder::new();
builder.mode(0o700).recursive(true).create(datadir_path)
};
#[cfg(not(unix))]
return {
// FIXME: make Windows secure (again?)
fs::create_dir_all(datadir_path)
};
}
impl RevaultD {
/// Creates our global state by consuming the static configuration
pub fn from_config(config: Config) -> Result<RevaultD, Box<dyn std::error::Error>> {
let our_man_xpub = config.manager_config.as_ref().map(|x| x.xpub);
let our_stk_xpub = config.stakeholder_config.as_ref().map(|x| x.xpub);
// Config should have checked that!
assert!(our_man_xpub.is_some() || our_stk_xpub.is_some());
let deposit_descriptor = config.scripts_config.deposit_descriptor;
let unvault_descriptor = config.scripts_config.unvault_descriptor;
let cpfp_descriptor = config.scripts_config.cpfp_descriptor;
let emergency_address = config.stakeholder_config.map(|x| x.emergency_address);
let mut data_dir = config.data_dir.unwrap_or(config_folder_path()?);
data_dir.push(config.bitcoind_config.network.to_string());
if!data_dir.as_path().exists() {
if let Err(e) = create_datadir(&data_dir) {
return Err(Box::from(ConfigError(format!(
"Could not create data dir '{:?}': {}.",
data_dir,
e.to_string()
))));
}
}
data_dir = fs::canonicalize(data_dir)?;
let data_dir_str = data_dir
.to_str()
.expect("Impossible: the datadir path is valid unicode");
let noise_secret_file = [data_dir_str, "noise_secret"].iter().collect();
let noise_secret = read_or_create_noise_key(noise_secret_file)?;
// TODO: support hidden services
let coordinator_host = SocketAddr::from_str(&config.coordinator_host)?;
let coordinator_noisekey = config.coordinator_noise_key;
let coordinator_poll_interval = config.coordinator_poll_seconds;
let cosigs = config.manager_config.map(|config| {
config
.cosigners
.into_iter()
.map(|config| (config.host, config.noise_key))
.collect()
});
let daemon =!matches!(config.daemon, Some(false));
let secp_ctx = secp256k1::Secp256k1::verification_only();
Ok(RevaultD {
our_stk_xpub,
our_man_xpub,
deposit_descriptor,
unvault_descriptor,
cpfp_descriptor,
secp_ctx,
data_dir,
daemon,
emergency_address,
noise_secret,
coordinator_host,
coordinator_noisekey,
coordinator_poll_interval,
cosigs,
lock_time: 0,
min_conf: config.min_conf,
bitcoind_config: config.bitcoind_config,
tip: None,
// Will be updated by the database
current_unused_index: ChildNumber::from(0),
// FIXME: we don't need SipHash for those, use a faster alternative
derivation_index_map: HashMap::new(),
// Will be updated soon (:tm:)
wallet_id: None,
})
}
fn file_from_datadir(&self, file_name: &str) -> PathBuf |
/// Our Noise static public key
pub fn noise_pubkey(&self) -> NoisePubKey {
let scalar = curve25519::Scalar(self.noise_secret.0);
NoisePubKey(curve25519::scalarmult_base(&scalar).0)
}
pub fn vault_address(&self, child_number: ChildNumber) -> Address {
self.deposit_descriptor
.derive(child_number, &self.secp_ctx)
.inner()
.address(self.bitcoind_config.network)
.expect("deposit_descriptor is a wsh")
}
pub fn unvault_address(&self, child_number: ChildNumber) -> Address {
self.unvault_descriptor
.derive(child_number, &self.secp_ctx)
.inner()
.address(self.bitcoind_config.network)
.expect("unvault_descriptor is a wsh")
}
pub fn gap_limit(&self) -> u32 {
100
}
pub fn watchonly_wallet_name(&self) -> Option<String> {
self.wallet_id
.map(|ref id| format!("revaultd-watchonly-wallet-{}", id))
}
pub fn log_file(&self) -> PathBuf {
self.file_from_datadir("log")
}
pub fn pid_file(&self) -> PathBuf {
self.file_from_datadir("revaultd.pid")
}
pub fn db_file(&self) -> PathBuf {
self.file_from_datadir("revaultd.sqlite3")
}
pub fn watchonly_wallet_file(&self) -> Option<String> {
self.watchonly_wallet_name().map(|ref name| {
self.file_from_datadir(name)
.to_str()
.expect("Valid utf-8")
.to_string()
})
}
pub fn rpc_socket_file(&self) -> PathBuf {
self.file_from_datadir("revaultd_rpc")
}
pub fn is_stakeholder(&self) -> bool {
self.our_stk_xpub.is_some()
}
pub fn is_manager(&self) -> bool {
self.our_man_xpub.is_some()
}
pub fn deposit_address(&self) -> Address {
self.vault_address(self.current_unused_index)
}
pub fn last_deposit_address(&self) -> Address {
let raw_index: u32 = self.current_unused_index.into();
// FIXME: this should fail instead of creating a hardened index
self.vault_address(ChildNumber::from(raw_index + self.gap_limit()))
}
pub fn last_unvault_address(&self) -> Address {
let raw_index: u32 = self.current_unused_index.into();
// FIXME: this should fail instead of creating a hardened index
self.unvault_address(ChildNumber::from(raw_index + self.gap_limit()))
}
/// All deposit addresses as strings up to the gap limit (100)
pub fn all_deposit_addresses(&mut self) -> Vec<String> {
self.derivation_index_map
.keys()
.map(|s| {
Address::from_script(s, self.bitcoind_config.network)
.expect("Created from P2WSH address")
.to_string()
})
.collect()
}
/// All unvault addresses as strings up to the gap limit (100)
pub fn all_unvault_addresses(&mut self) -> Vec<String> {
let raw_index: u32 = self.current_unused_index.into();
(0..raw_index + self.gap_limit())
.map(|raw_index| {
// FIXME: this should fail instead of creating a hardened index
self.unvault_address(ChildNumber::from(raw_index))
.to_string()
})
.collect()
}
pub fn derived_deposit_descriptor(&self, index: ChildNumber) -> DerivedDepositDescriptor {
self.deposit_descriptor.derive(index, &self.secp_ctx)
}
pub fn derived_unvault_descriptor(&self, index: ChildNumber) -> DerivedUnvaultDescriptor {
self.unvault_descriptor.derive(index, &self.secp_ctx)
}
pub fn derived_cpfp_descriptor(&self, index: ChildNumber) -> DerivedCpfpDescriptor {
self.cpfp_descriptor.derive(index, &self.secp_ctx)
}
pub fn stakeholders_xpubs(&self) -> Vec<DescriptorPublicKey> {
self.deposit_descriptor.xpubs()
}
pub fn managers_xpubs(&self) -> Vec<DescriptorPublicKey> {
// The managers' xpubs are all the xpubs from the Unvault descriptor except the
// Stakehodlers' ones and the Cosigning Servers' ones.
let stk_xpubs = self.stakeholders_xpubs();
self.unvault_descriptor
.xpubs()
.into_iter()
.filter_map(|xpub| {
match xpub {
DescriptorPublicKey::SinglePub(_) => None, // Cosig
DescriptorPublicKey::XPub(_) => {
if stk_xpubs.contains(&xpub) {
None // Stakeholder
} else {
Some(xpub) // Manager
}
}
}
})
.collect()
}
pub fn stakeholders_xpubs_at(&self, index: ChildNumber) -> Vec<BitcoinPublicKey> {
self.deposit_descriptor
.xpubs()
.into_iter()
.map(|desc_xpub| {
desc_xpub
.derive(index.into())
.derive_public_key(&self.secp_ctx)
.expect("Is derived, and there is never any hardened path")
})
.collect()
}
pub fn our_stk_xpub_at(&self, index: ChildNumber) -> Option<BitcoinPublicKey> {
self.our_stk_xpub.map(|xpub| {
xpub.derive_pub(&self.secp_ctx, &[index])
.expect("The derivation index stored in the database is sane (unhardened)")
| {
let data_dir_str = self
.data_dir
.to_str()
.expect("Impossible: the datadir path is valid unicode");
[data_dir_str, file_name].iter().collect()
} | identifier_body |
page.rs | use serde::Deserialize;
use yew::format::{Json, Nothing};
use yew::prelude::*;
use yew::services::fetch::{FetchService, FetchTask, Request, Response};
use yew::services::ConsoleService;
use yew::Properties;
use super::entry::{Entry, EntryProps};
use super::modal::{is_media, MediaType, Modal, ModalProps};
use crate::{App, AppAnchor, AppRoute, SERVER_URL};
use anyhow::{anyhow, Error};
#[derive(Deserialize, Clone, PartialEq, Debug)]
pub struct Dir {
title: String,
base_path: String,
read_only: bool,
files: Vec<EntryProps>,
folders: Vec<EntryProps>,
}
#[derive(Debug)]
pub enum PageMsg {
Page(Dir),
File,
Error(Error),
Modal(String),
ModalNext,
ModalPrevious,
}
#[derive(Properties, Clone, PartialEq)]
pub struct PageProps {
pub path: String,
pub page: Option<Dir>,
}
pub struct Page {
link: ComponentLink<Self>,
props: PageProps,
modal: ModalProps,
task: Option<FetchTask>,
loaded: Option<String>,
error: Option<Error>,
show_loading: bool,
}
impl Component for Page {
type Message = PageMsg;
type Properties = PageProps;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
props,
modal: ModalProps::default(),
task: None,
loaded: None,
error: None,
show_loading: true,
}
}
fn | (&mut self, msg: Self::Message) -> ShouldRender {
match msg {
PageMsg::Page(page) => {
self.props.page = Some(page);
self.error = None;
self.show_loading = false;
true
}
// TODO: This means non-media (non-modal display) files
// end up loading twice. Once on request,
// and then again on popup. Parent directy also reloads.
// Not sure the best solution at the moment.
// (Start with HEAD request instead of GET?)
PageMsg::File => {
let url = format!("{}{}", *SERVER_URL, &self.props.path);
web_sys::window()
.unwrap()
.open_with_url_and_target(&url, "_new_file")
.unwrap();
self.show_loading = false;
self.error = None;
// Show containing dir by navigating to parent directory
if let Some(index) = &self.props.path.rfind('/') {
let path = &self.props.path[0..index + 1];
App::replace_route(path.to_string());
}
false
}
PageMsg::Error(error) => {
ConsoleService::error(format!("Invalid response: {:?}", error).as_str());
self.error = Some(error);
self.show_loading = false;
self.modal = ModalProps::default();
true
}
PageMsg::Modal(src) => {
ConsoleService::info(format!("Loading modal for: {:?}", src).as_str());
self.modal.src = src.to_string();
self.modal.media = MediaType::from_path(src.as_str());
self.show_loading = false;
true
}
PageMsg::ModalNext => {
let src = format!("/{}", self.next_file());
App::change_route(src);
true
}
PageMsg::ModalPrevious => {
let src = format!("/{}", self.prev_file());
App::change_route(src);
true
}
}
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props.path!= props.path {
ConsoleService::info(format!("Page Changed: {:?}", props.path).as_str());
if is_media(props.path.as_str()) {
// Trigger modal
self.link
.callback(PageMsg::Modal)
.emit(props.path.to_owned());
self.show_loading = true;
} else {
// Only re-fetch page if not already loaded
if self.loaded.is_none() || self.loaded.as_ref().unwrap()!= &props.path {
self.loaded = Some(props.path.to_owned());
self.task = self.fetch_page(props.path.as_str());
self.show_loading = true;
} else {
self.show_loading = false;
}
// Reset Modal
self.modal = ModalProps::default();
}
self.props.path = props.path;
true
} else {
false
}
}
fn rendered(&mut self, first_render: bool) {
// On page init, the path may be a dir or a file
// display modal if it's a file + load directory the file is in
if first_render {
let fetch_path: &str;
if is_media(&self.props.path.as_str()) {
// Trigger modal
self.link
.callback(PageMsg::Modal)
.emit(self.props.path.to_owned());
// Get dir of file
let index = self.props.path.rfind('/').unwrap();
fetch_path = &self.props.path[0..index + 1];
} else {
fetch_path = &self.props.path;
}
self.loaded = Some(fetch_path.to_string());
self.task = self.fetch_page(fetch_path);
}
if let Some(data) = &self.props.page {
if!data.title.is_empty() {
App::set_title(data.title.to_string());
}
}
}
fn view(&self) -> Html {
let mut title = "";
let mut base_path = "";
let content = if let Some(data) = &self.props.page {
title = data.title.as_str();
base_path = data.base_path.as_str();
let folders = data.folders.iter().map(|e| {
html! {
<Entry
name={ e.name.to_owned() }
path={ e.path.to_owned() }
size={ e.size.to_owned() }
date={ e.date.to_owned() }
date_string={ e.date_string.to_owned() }
thumb={ e.thumb.to_owned() }
ext={ e.ext.to_owned() }
etype="folder"
/>
}
});
let files = data.files.iter().map(|e| {
html! {
<Entry
name={ e.name.to_owned() }
path={ e.path.to_owned() }
size={ e.size.to_owned() }
date={ e.date.to_owned() }
date_string={ e.date_string.to_owned() }
thumb={ e.thumb.to_owned() }
ext={ e.ext.to_owned() }
etype="file"
/>
}
});
html! {
<div class="row gx-5">
{ for folders }
{ for files }
</div>
}
} else {
html! {}
};
// Convert title into links for each subdir
let combined = if title == String::from("") {
base_path.to_string()
} else {
format!("{}{}/", base_path, title)
};
let split = combined.split_inclusive('/').enumerate();
let clone = split.clone();
let html_title = split.map(|s| {
// Note: Not happy with a loop of "clone" calls
// but the strings have to be duplicated anyway.
// Current solution adds one extra "clone" than is ideally necessary
let link = clone
.clone()
.filter(|&(i, _)| i <= s.0)
.map(|(_, e)| e)
.collect::<String>();
let text = &s.1;
html! {
<AppAnchor route={ AppRoute::Entry(link) }>{ text }</AppAnchor>
}
});
let loading = if self.show_loading {
html! {<span class="loading"></span>}
} else {
html! {}
};
let error = if self.error.is_some() {
html! {<h2 class="text-danger">{ "Error: " }{ self.error.as_ref().unwrap() }</h2>}
} else {
html! {}
};
html! {
<>
<Modal src={ self.modal.src.to_owned() } media={ self.modal.media.to_owned() } />
<h1 id="title">
{ for html_title }
{ loading }
</h1>
{ error }
{ content }
</>
}
}
}
impl Page {
fn fetch_page(&self, path: &str) -> Option<FetchTask> {
// TODO: This results in double "//" in path.
// Not a major issue, but should be accounted for
let url = format!("{}{}", *SERVER_URL, path);
let request = Request::get(url.as_str())
.body(Nothing)
.expect("Could not load from API");
let callback = self
.link
.callback(|response: Response<Json<Result<Dir, Error>>>| {
let status = response.status();
if!status.is_success() {
let err = anyhow!(
"Error: {} ({})",
&status.canonical_reason().unwrap(),
&status.as_str()
);
return PageMsg::Error(err);
}
let content = response.headers().get("content-type");
if content.is_none() {
return PageMsg::Error(anyhow!("Invalid Content Type"));
} else if content.unwrap()!= &"application/json" {
return PageMsg::File;
}
let Json(data) = response.into_body();
match data {
Ok(dir) => PageMsg::Page(dir),
Err(err) => PageMsg::Error(err),
}
});
let task = FetchService::fetch(request, callback).expect("Could not load page");
Some(task)
}
// Determine the next file in modal sequence
fn next_file(&self) -> String {
let findex = &self.modal.src.rfind('/').expect("complete path");
let srcname = &self.modal.src[*findex + 1..];
let page = &self.props.page.as_ref().unwrap();
let files = &page.files;
let current = files.iter().position(|e| e.name == srcname);
if let Some(index) = current {
if index + 1 >= files.len() {
files.first().unwrap().path.to_owned()
} else {
files.get(index + 1).unwrap().path.to_owned()
}
} else {
"".to_string()
}
}
// Determine the prev file in modal sequence
fn prev_file(&self) -> String {
let findex = &self.modal.src.rfind('/').expect("complete path");
let srcname = &self.modal.src[*findex + 1..];
let page = &self.props.page.as_ref().unwrap();
let files = &page.files;
let current = files.iter().position(|e| e.name == srcname);
if let Some(index) = current {
if (index as i8) - 1 < 0 {
files.last().unwrap().path.to_owned()
} else {
files.get(index - 1).unwrap().path.to_owned()
}
} else {
"".to_string()
}
}
}
| update | identifier_name |
page.rs | use serde::Deserialize;
use yew::format::{Json, Nothing};
use yew::prelude::*;
use yew::services::fetch::{FetchService, FetchTask, Request, Response};
use yew::services::ConsoleService;
use yew::Properties;
use super::entry::{Entry, EntryProps};
use super::modal::{is_media, MediaType, Modal, ModalProps};
use crate::{App, AppAnchor, AppRoute, SERVER_URL};
use anyhow::{anyhow, Error};
#[derive(Deserialize, Clone, PartialEq, Debug)]
pub struct Dir {
title: String,
base_path: String,
read_only: bool,
files: Vec<EntryProps>,
folders: Vec<EntryProps>,
}
#[derive(Debug)]
pub enum PageMsg {
Page(Dir),
File,
Error(Error),
Modal(String),
ModalNext,
ModalPrevious,
}
#[derive(Properties, Clone, PartialEq)]
pub struct PageProps {
pub path: String,
pub page: Option<Dir>,
}
pub struct Page {
link: ComponentLink<Self>,
props: PageProps,
modal: ModalProps,
task: Option<FetchTask>,
loaded: Option<String>,
error: Option<Error>,
show_loading: bool,
}
impl Component for Page {
type Message = PageMsg;
type Properties = PageProps;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
props,
modal: ModalProps::default(),
task: None,
loaded: None,
error: None,
show_loading: true,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
PageMsg::Page(page) => {
self.props.page = Some(page);
self.error = None;
self.show_loading = false;
true
}
// TODO: This means non-media (non-modal display) files
// end up loading twice. Once on request,
// and then again on popup. Parent directy also reloads.
// Not sure the best solution at the moment.
// (Start with HEAD request instead of GET?)
PageMsg::File => {
let url = format!("{}{}", *SERVER_URL, &self.props.path);
web_sys::window()
.unwrap()
.open_with_url_and_target(&url, "_new_file")
.unwrap();
self.show_loading = false;
self.error = None;
// Show containing dir by navigating to parent directory
if let Some(index) = &self.props.path.rfind('/') {
let path = &self.props.path[0..index + 1];
App::replace_route(path.to_string());
}
false
}
PageMsg::Error(error) => {
ConsoleService::error(format!("Invalid response: {:?}", error).as_str());
self.error = Some(error);
self.show_loading = false;
self.modal = ModalProps::default();
true
}
PageMsg::Modal(src) => {
ConsoleService::info(format!("Loading modal for: {:?}", src).as_str());
self.modal.src = src.to_string();
self.modal.media = MediaType::from_path(src.as_str());
self.show_loading = false;
true
}
PageMsg::ModalNext => {
let src = format!("/{}", self.next_file());
App::change_route(src);
true
}
PageMsg::ModalPrevious => {
let src = format!("/{}", self.prev_file());
App::change_route(src);
true
}
}
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props.path!= props.path {
ConsoleService::info(format!("Page Changed: {:?}", props.path).as_str());
if is_media(props.path.as_str()) {
// Trigger modal
self.link
.callback(PageMsg::Modal)
.emit(props.path.to_owned());
self.show_loading = true;
} else {
// Only re-fetch page if not already loaded
if self.loaded.is_none() || self.loaded.as_ref().unwrap()!= &props.path {
self.loaded = Some(props.path.to_owned());
self.task = self.fetch_page(props.path.as_str());
self.show_loading = true;
} else {
self.show_loading = false;
}
// Reset Modal
self.modal = ModalProps::default();
}
self.props.path = props.path;
true
} else {
false
}
}
fn rendered(&mut self, first_render: bool) {
// On page init, the path may be a dir or a file
// display modal if it's a file + load directory the file is in
if first_render {
let fetch_path: &str;
if is_media(&self.props.path.as_str()) {
// Trigger modal
self.link
.callback(PageMsg::Modal)
.emit(self.props.path.to_owned());
// Get dir of file
let index = self.props.path.rfind('/').unwrap();
fetch_path = &self.props.path[0..index + 1];
} else {
fetch_path = &self.props.path;
}
self.loaded = Some(fetch_path.to_string());
self.task = self.fetch_page(fetch_path);
}
if let Some(data) = &self.props.page {
if!data.title.is_empty() {
App::set_title(data.title.to_string());
}
}
}
fn view(&self) -> Html {
let mut title = "";
let mut base_path = "";
let content = if let Some(data) = &self.props.page {
title = data.title.as_str();
base_path = data.base_path.as_str();
let folders = data.folders.iter().map(|e| {
html! {
<Entry
name={ e.name.to_owned() }
path={ e.path.to_owned() }
size={ e.size.to_owned() }
date={ e.date.to_owned() }
date_string={ e.date_string.to_owned() }
thumb={ e.thumb.to_owned() }
ext={ e.ext.to_owned() }
etype="folder"
/>
}
});
let files = data.files.iter().map(|e| {
html! {
<Entry
name={ e.name.to_owned() }
path={ e.path.to_owned() }
size={ e.size.to_owned() }
date={ e.date.to_owned() }
date_string={ e.date_string.to_owned() }
thumb={ e.thumb.to_owned() }
ext={ e.ext.to_owned() }
etype="file"
/>
}
});
html! {
<div class="row gx-5">
{ for folders }
{ for files }
</div>
}
} else {
html! {}
};
// Convert title into links for each subdir
let combined = if title == String::from("") {
base_path.to_string()
} else {
format!("{}{}/", base_path, title)
};
let split = combined.split_inclusive('/').enumerate();
let clone = split.clone();
let html_title = split.map(|s| {
// Note: Not happy with a loop of "clone" calls
// but the strings have to be duplicated anyway.
// Current solution adds one extra "clone" than is ideally necessary
let link = clone
.clone()
.filter(|&(i, _)| i <= s.0)
.map(|(_, e)| e)
.collect::<String>();
let text = &s.1;
html! {
<AppAnchor route={ AppRoute::Entry(link) }>{ text }</AppAnchor>
} | } else {
html! {}
};
let error = if self.error.is_some() {
html! {<h2 class="text-danger">{ "Error: " }{ self.error.as_ref().unwrap() }</h2>}
} else {
html! {}
};
html! {
<>
<Modal src={ self.modal.src.to_owned() } media={ self.modal.media.to_owned() } />
<h1 id="title">
{ for html_title }
{ loading }
</h1>
{ error }
{ content }
</>
}
}
}
impl Page {
fn fetch_page(&self, path: &str) -> Option<FetchTask> {
// TODO: This results in double "//" in path.
// Not a major issue, but should be accounted for
let url = format!("{}{}", *SERVER_URL, path);
let request = Request::get(url.as_str())
.body(Nothing)
.expect("Could not load from API");
let callback = self
.link
.callback(|response: Response<Json<Result<Dir, Error>>>| {
let status = response.status();
if!status.is_success() {
let err = anyhow!(
"Error: {} ({})",
&status.canonical_reason().unwrap(),
&status.as_str()
);
return PageMsg::Error(err);
}
let content = response.headers().get("content-type");
if content.is_none() {
return PageMsg::Error(anyhow!("Invalid Content Type"));
} else if content.unwrap()!= &"application/json" {
return PageMsg::File;
}
let Json(data) = response.into_body();
match data {
Ok(dir) => PageMsg::Page(dir),
Err(err) => PageMsg::Error(err),
}
});
let task = FetchService::fetch(request, callback).expect("Could not load page");
Some(task)
}
// Determine the next file in modal sequence
fn next_file(&self) -> String {
let findex = &self.modal.src.rfind('/').expect("complete path");
let srcname = &self.modal.src[*findex + 1..];
let page = &self.props.page.as_ref().unwrap();
let files = &page.files;
let current = files.iter().position(|e| e.name == srcname);
if let Some(index) = current {
if index + 1 >= files.len() {
files.first().unwrap().path.to_owned()
} else {
files.get(index + 1).unwrap().path.to_owned()
}
} else {
"".to_string()
}
}
// Determine the prev file in modal sequence
fn prev_file(&self) -> String {
let findex = &self.modal.src.rfind('/').expect("complete path");
let srcname = &self.modal.src[*findex + 1..];
let page = &self.props.page.as_ref().unwrap();
let files = &page.files;
let current = files.iter().position(|e| e.name == srcname);
if let Some(index) = current {
if (index as i8) - 1 < 0 {
files.last().unwrap().path.to_owned()
} else {
files.get(index - 1).unwrap().path.to_owned()
}
} else {
"".to_string()
}
}
} | });
let loading = if self.show_loading {
html! {<span class="loading"></span>} | random_line_split |
page.rs | use serde::Deserialize;
use yew::format::{Json, Nothing};
use yew::prelude::*;
use yew::services::fetch::{FetchService, FetchTask, Request, Response};
use yew::services::ConsoleService;
use yew::Properties;
use super::entry::{Entry, EntryProps};
use super::modal::{is_media, MediaType, Modal, ModalProps};
use crate::{App, AppAnchor, AppRoute, SERVER_URL};
use anyhow::{anyhow, Error};
#[derive(Deserialize, Clone, PartialEq, Debug)]
pub struct Dir {
title: String,
base_path: String,
read_only: bool,
files: Vec<EntryProps>,
folders: Vec<EntryProps>,
}
#[derive(Debug)]
pub enum PageMsg {
Page(Dir),
File,
Error(Error),
Modal(String),
ModalNext,
ModalPrevious,
}
#[derive(Properties, Clone, PartialEq)]
pub struct PageProps {
pub path: String,
pub page: Option<Dir>,
}
pub struct Page {
link: ComponentLink<Self>,
props: PageProps,
modal: ModalProps,
task: Option<FetchTask>,
loaded: Option<String>,
error: Option<Error>,
show_loading: bool,
}
impl Component for Page {
type Message = PageMsg;
type Properties = PageProps;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
props,
modal: ModalProps::default(),
task: None,
loaded: None,
error: None,
show_loading: true,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
PageMsg::Page(page) => {
self.props.page = Some(page);
self.error = None;
self.show_loading = false;
true
}
// TODO: This means non-media (non-modal display) files
// end up loading twice. Once on request,
// and then again on popup. Parent directy also reloads.
// Not sure the best solution at the moment.
// (Start with HEAD request instead of GET?)
PageMsg::File => {
let url = format!("{}{}", *SERVER_URL, &self.props.path);
web_sys::window()
.unwrap()
.open_with_url_and_target(&url, "_new_file")
.unwrap();
self.show_loading = false;
self.error = None;
// Show containing dir by navigating to parent directory
if let Some(index) = &self.props.path.rfind('/') {
let path = &self.props.path[0..index + 1];
App::replace_route(path.to_string());
}
false
}
PageMsg::Error(error) => {
ConsoleService::error(format!("Invalid response: {:?}", error).as_str());
self.error = Some(error);
self.show_loading = false;
self.modal = ModalProps::default();
true
}
PageMsg::Modal(src) => |
PageMsg::ModalNext => {
let src = format!("/{}", self.next_file());
App::change_route(src);
true
}
PageMsg::ModalPrevious => {
let src = format!("/{}", self.prev_file());
App::change_route(src);
true
}
}
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props.path!= props.path {
ConsoleService::info(format!("Page Changed: {:?}", props.path).as_str());
if is_media(props.path.as_str()) {
// Trigger modal
self.link
.callback(PageMsg::Modal)
.emit(props.path.to_owned());
self.show_loading = true;
} else {
// Only re-fetch page if not already loaded
if self.loaded.is_none() || self.loaded.as_ref().unwrap()!= &props.path {
self.loaded = Some(props.path.to_owned());
self.task = self.fetch_page(props.path.as_str());
self.show_loading = true;
} else {
self.show_loading = false;
}
// Reset Modal
self.modal = ModalProps::default();
}
self.props.path = props.path;
true
} else {
false
}
}
fn rendered(&mut self, first_render: bool) {
// On page init, the path may be a dir or a file
// display modal if it's a file + load directory the file is in
if first_render {
let fetch_path: &str;
if is_media(&self.props.path.as_str()) {
// Trigger modal
self.link
.callback(PageMsg::Modal)
.emit(self.props.path.to_owned());
// Get dir of file
let index = self.props.path.rfind('/').unwrap();
fetch_path = &self.props.path[0..index + 1];
} else {
fetch_path = &self.props.path;
}
self.loaded = Some(fetch_path.to_string());
self.task = self.fetch_page(fetch_path);
}
if let Some(data) = &self.props.page {
if!data.title.is_empty() {
App::set_title(data.title.to_string());
}
}
}
fn view(&self) -> Html {
let mut title = "";
let mut base_path = "";
let content = if let Some(data) = &self.props.page {
title = data.title.as_str();
base_path = data.base_path.as_str();
let folders = data.folders.iter().map(|e| {
html! {
<Entry
name={ e.name.to_owned() }
path={ e.path.to_owned() }
size={ e.size.to_owned() }
date={ e.date.to_owned() }
date_string={ e.date_string.to_owned() }
thumb={ e.thumb.to_owned() }
ext={ e.ext.to_owned() }
etype="folder"
/>
}
});
let files = data.files.iter().map(|e| {
html! {
<Entry
name={ e.name.to_owned() }
path={ e.path.to_owned() }
size={ e.size.to_owned() }
date={ e.date.to_owned() }
date_string={ e.date_string.to_owned() }
thumb={ e.thumb.to_owned() }
ext={ e.ext.to_owned() }
etype="file"
/>
}
});
html! {
<div class="row gx-5">
{ for folders }
{ for files }
</div>
}
} else {
html! {}
};
// Convert title into links for each subdir
let combined = if title == String::from("") {
base_path.to_string()
} else {
format!("{}{}/", base_path, title)
};
let split = combined.split_inclusive('/').enumerate();
let clone = split.clone();
let html_title = split.map(|s| {
// Note: Not happy with a loop of "clone" calls
// but the strings have to be duplicated anyway.
// Current solution adds one extra "clone" than is ideally necessary
let link = clone
.clone()
.filter(|&(i, _)| i <= s.0)
.map(|(_, e)| e)
.collect::<String>();
let text = &s.1;
html! {
<AppAnchor route={ AppRoute::Entry(link) }>{ text }</AppAnchor>
}
});
let loading = if self.show_loading {
html! {<span class="loading"></span>}
} else {
html! {}
};
let error = if self.error.is_some() {
html! {<h2 class="text-danger">{ "Error: " }{ self.error.as_ref().unwrap() }</h2>}
} else {
html! {}
};
html! {
<>
<Modal src={ self.modal.src.to_owned() } media={ self.modal.media.to_owned() } />
<h1 id="title">
{ for html_title }
{ loading }
</h1>
{ error }
{ content }
</>
}
}
}
impl Page {
fn fetch_page(&self, path: &str) -> Option<FetchTask> {
// TODO: This results in double "//" in path.
// Not a major issue, but should be accounted for
let url = format!("{}{}", *SERVER_URL, path);
let request = Request::get(url.as_str())
.body(Nothing)
.expect("Could not load from API");
let callback = self
.link
.callback(|response: Response<Json<Result<Dir, Error>>>| {
let status = response.status();
if!status.is_success() {
let err = anyhow!(
"Error: {} ({})",
&status.canonical_reason().unwrap(),
&status.as_str()
);
return PageMsg::Error(err);
}
let content = response.headers().get("content-type");
if content.is_none() {
return PageMsg::Error(anyhow!("Invalid Content Type"));
} else if content.unwrap()!= &"application/json" {
return PageMsg::File;
}
let Json(data) = response.into_body();
match data {
Ok(dir) => PageMsg::Page(dir),
Err(err) => PageMsg::Error(err),
}
});
let task = FetchService::fetch(request, callback).expect("Could not load page");
Some(task)
}
// Determine the next file in modal sequence
fn next_file(&self) -> String {
let findex = &self.modal.src.rfind('/').expect("complete path");
let srcname = &self.modal.src[*findex + 1..];
let page = &self.props.page.as_ref().unwrap();
let files = &page.files;
let current = files.iter().position(|e| e.name == srcname);
if let Some(index) = current {
if index + 1 >= files.len() {
files.first().unwrap().path.to_owned()
} else {
files.get(index + 1).unwrap().path.to_owned()
}
} else {
"".to_string()
}
}
// Determine the prev file in modal sequence
fn prev_file(&self) -> String {
let findex = &self.modal.src.rfind('/').expect("complete path");
let srcname = &self.modal.src[*findex + 1..];
let page = &self.props.page.as_ref().unwrap();
let files = &page.files;
let current = files.iter().position(|e| e.name == srcname);
if let Some(index) = current {
if (index as i8) - 1 < 0 {
files.last().unwrap().path.to_owned()
} else {
files.get(index - 1).unwrap().path.to_owned()
}
} else {
"".to_string()
}
}
}
| {
ConsoleService::info(format!("Loading modal for: {:?}", src).as_str());
self.modal.src = src.to_string();
self.modal.media = MediaType::from_path(src.as_str());
self.show_loading = false;
true
} | conditional_block |
lib.rs | use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::UnorderedMap;
use near_sdk::serde::{Deserialize, Serialize};
use near_contract_standards::non_fungible_token::metadata::{
NFTContractMetadata, NonFungibleTokenMetadataProvider, TokenMetadata, NFT_METADATA_SPEC,
};
use near_contract_standards::non_fungible_token::{Token, TokenId};
use near_contract_standards::non_fungible_token::NonFungibleToken;
use near_sdk::collections::LazyOption;
use near_sdk::json_types::ValidAccountId;
use near_sdk::{
setup_alloc, env, near_bindgen, AccountId, BorshStorageKey, Promise, PromiseOrValue,
};
#[derive(BorshSerialize, BorshStorageKey)]
enum StorageKey {
NonFungibleToken,
Metadata,
TokenMetadata,
Enumeration,
Approval,
}
setup_alloc!();
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct UserInfo {
pub name: String,
pub dob: String,
pub national_id: String,
pub from: Issuer,
pub owner: ValidAccountId
}
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct TokenSerialize {
pub token_id: String,
pub owner_id: String,
pub metadata: TokenMetadata,
pub tx: String,
}
#[derive(BorshDeserialize, BorshSerialize, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct CertInfo {
pub user_info: UserInfo,
pub is_first_approved: bool,
}
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct SmartCertificateContract{
owner: AccountId, //Owners of this contract, the only person can add more issuers
issuers: UnorderedMap<AccountId, Issuer>, //List of issuers, only issuers in this list can create a cert
need_user_approved: UnorderedMap<String, CertInfo>,
ready_deploy_nft: UnorderedMap<String, CertInfo>,
//NFT Define
nft_cert: UnorderedMap<String, TokenSerialize>,
nft_token: NonFungibleToken,
metadata: LazyOption<NFTContractMetadata>,
}
// #[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct Issuer {
pub name: String,
pub issuer_id: AccountId
}
impl Default for SmartCertificateContract {
fn default() -> Self |
}
const DATA_IMAGE_SVG_NEAR_ICON: &str = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 288 288'%3E%3Cg id='l' data-name='l'%3E%3Cpath d='M187.58,79.81l-30.1,44.69a3.2,3.2,0,0,0,4.75,4.2L191.86,103a1.2,1.2,0,0,1,2,.91v80.46a1.2,1.2,0,0,1-2.12.77L102.18,77.93A15.35,15.35,0,0,0,90.47,72.5H87.34A15.34,15.34,0,0,0,72,87.84V201.16A15.34,15.34,0,0,0,87.34,216.5h0a15.35,15.35,0,0,0,13.08-7.31l30.1-44.69a3.2,3.2,0,0,0-4.75-4.2L96.14,186a1.2,1.2,0,0,1-2-.91V104.61a1.2,1.2,0,0,1,2.12-.77l89.55,107.23a15.35,15.35,0,0,0,11.71,5.43h3.13A15.34,15.34,0,0,0,216,201.16V87.84A15.34,15.34,0,0,0,200.66,72.5h0A15.35,15.35,0,0,0,187.58,79.81Z'/%3E%3C/g%3E%3C/svg%3E";
#[near_bindgen]
impl SmartCertificateContract {
#[init]
pub fn new(nft_owner: ValidAccountId) -> Self {
assert!(!env::state_exists(), "The contract is already initialized");
assert!(
env::is_valid_account_id(env::predecessor_account_id().as_bytes()),
"The NEAR Foundation account ID is invalid"
);
let metadata = NFTContractMetadata {
spec: NFT_METADATA_SPEC.to_string(),
name: "Example NEAR non-fungible token".to_string(),
symbol: "EXAMPLE".to_string(),
icon: Some(DATA_IMAGE_SVG_NEAR_ICON.to_string()),
base_uri: None,
reference: None,
reference_hash: None,
};
SmartCertificateContract {
owner: env::predecessor_account_id(),
issuers: UnorderedMap::new(b"i".to_vec()),
need_user_approved: UnorderedMap::new(b"n".to_vec()),
ready_deploy_nft: UnorderedMap::new(b"r".to_vec()),
nft_cert: UnorderedMap::new(b"nft".to_vec()),
nft_token: NonFungibleToken::new(
StorageKey::NonFungibleToken,
nft_owner,
Some(StorageKey::TokenMetadata),
Some(StorageKey::Enumeration),
Some(StorageKey::Approval),
),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
}
}
pub fn add_issuer(&mut self, issuer_account: AccountId, name: String) -> bool {
assert!(
env::is_valid_account_id(issuer_account.as_bytes()),
"The given account ID is invalid"
);
self.assert_called_by_foundation();
if!self.issuers.get(&issuer_account).is_some() {
let new_issuer = Issuer {
name: name,
issuer_id: issuer_account.clone(),
};
self.issuers.insert(&issuer_account, &new_issuer);
return true;
}
return false;
}
pub fn create_cert(&mut self, user_account_id: ValidAccountId, name: String, dob: String, national_id: String) {
self.assert_called_by_issuers();
let issuer = self.issuers.get(&env::predecessor_account_id()).clone().unwrap();
let user = UserInfo {
name: name,
dob: dob,
national_id: national_id,
from: issuer.clone(),
owner: user_account_id.clone()
};
let cert_info = CertInfo {
user_info: user,
is_first_approved: false
};
let id = self.generate_cert_key(user_account_id.clone(), env::predecessor_account_id());
self.need_user_approved.insert(&id, &cert_info);
}
pub fn user_approved(&mut self, id: String) {
let cert = self.need_user_approved.get(&id).unwrap();
let new_cert = CertInfo {
user_info: cert.user_info.clone(),
is_first_approved: true
};
env::log(
format!(
"new cert @{}",
new_cert.user_info.owner
).as_bytes()
);
self.need_user_approved.remove(&id);
self.ready_deploy_nft.insert(&id, &new_cert);
}
#[payable]
pub fn nft_mint(
&mut self,
id: String,
) -> Token {
self.assert_called_by_foundation();
let cert = self.ready_deploy_nft.get(&id).unwrap();
let owner = cert.user_info.clone().owner;
let token = self.nft_token.mint((self.nft_cert.len() + 1).to_string(), owner, Some(self.create_meta_data(cert)));
let token_serialize = TokenSerialize {
token_id: token.token_id.clone(),
owner_id: token.owner_id.clone(),
metadata: token.metadata.clone().unwrap(),
tx: "".to_string()
};
self.nft_cert.insert(&id.clone(), &token_serialize);
return token;
}
pub fn finalize(&mut self, id: String, txid: String) {
let mut token = self.nft_cert.get(&id.clone()).unwrap();
token.tx = txid.clone();
self.ready_deploy_nft.remove(&id.clone());
self.nft_cert.remove(&id.clone());
self.nft_cert.insert(&txid.clone(), &token);
}
/*****************/
/* View Methods */
/*****************/
pub fn get_cert_info(&self, txid: String) -> TokenMetadata {
let cert = self.nft_cert.get(&txid.clone()).unwrap();
return cert.metadata;
}
pub fn get_issuers(&self) -> Vec<(AccountId, Issuer)> {
return self.issuers.to_vec();
}
pub fn get_certs(&self) -> Vec<(String, TokenSerialize)> {
return self
.nft_cert
.iter()
.collect();
}
pub fn get_un_approved_cert(&self, owner_id: String) -> Vec<(String, CertInfo)> {
return self.need_user_approved
.iter()
.filter(|(_k, v)| String::from(v.user_info.owner.clone()) == owner_id)
.collect();
}
pub fn get_ready_deploy_cert(&self) -> Vec<(String, CertInfo)> {
return self.ready_deploy_nft
.iter()
.collect();
}
/************/
/* Utils */
/************/
fn generate_cert_key(&self, user: ValidAccountId, issuer: AccountId) -> String {
return [String::from(user), issuer].join("_");
}
fn create_meta_data(&self, cert: CertInfo) -> TokenMetadata {
let description = cert.user_info.name + &String::from("'s Certificate issued by ") + &cert.user_info.from.name;
return TokenMetadata {
title: Some("Certificate".into()),
description: Some(description.into()),
media: None,
media_hash: None,
copies: Some(1u64),
issued_at: None,
expires_at: None,
starts_at: None,
updated_at: None,
extra: None,
reference: None,
reference_hash: None,
};
}
/************/
/* Internal */
/************/
fn assert_called_by_foundation(&self) {
assert_eq!(
&env::predecessor_account_id(),
&self.owner,
"Can only be called by NEAR Foundation"
);
}
fn assert_called_by_issuers(&self) {
assert!(
self.issuers.get(&env::predecessor_account_id()).is_some(),
"Only call by issuers"
);
}
}
near_contract_standards::impl_non_fungible_token_core!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_approval!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_enumeration!(SmartCertificateContract, nft_token);
#[near_bindgen]
impl NonFungibleTokenMetadataProvider for SmartCertificateContract {
fn nft_metadata(&self) -> NFTContractMetadata {
self.metadata.get().unwrap()
}
}
| {
env::panic(b"SmartCertificate contract should be initialized before usage")
} | identifier_body |
lib.rs | use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::UnorderedMap;
use near_sdk::serde::{Deserialize, Serialize};
use near_contract_standards::non_fungible_token::metadata::{
NFTContractMetadata, NonFungibleTokenMetadataProvider, TokenMetadata, NFT_METADATA_SPEC,
};
use near_contract_standards::non_fungible_token::{Token, TokenId};
use near_contract_standards::non_fungible_token::NonFungibleToken;
use near_sdk::collections::LazyOption;
use near_sdk::json_types::ValidAccountId;
use near_sdk::{
setup_alloc, env, near_bindgen, AccountId, BorshStorageKey, Promise, PromiseOrValue,
};
#[derive(BorshSerialize, BorshStorageKey)]
enum StorageKey {
NonFungibleToken,
Metadata,
TokenMetadata,
Enumeration,
Approval,
}
setup_alloc!();
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct UserInfo {
pub name: String,
pub dob: String,
pub national_id: String,
pub from: Issuer,
pub owner: ValidAccountId
}
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct TokenSerialize {
pub token_id: String,
pub owner_id: String,
pub metadata: TokenMetadata,
pub tx: String,
}
#[derive(BorshDeserialize, BorshSerialize, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct CertInfo {
pub user_info: UserInfo,
pub is_first_approved: bool,
}
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct SmartCertificateContract{
owner: AccountId, //Owners of this contract, the only person can add more issuers
issuers: UnorderedMap<AccountId, Issuer>, //List of issuers, only issuers in this list can create a cert
need_user_approved: UnorderedMap<String, CertInfo>,
ready_deploy_nft: UnorderedMap<String, CertInfo>,
//NFT Define
nft_cert: UnorderedMap<String, TokenSerialize>,
nft_token: NonFungibleToken,
metadata: LazyOption<NFTContractMetadata>,
}
// #[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct Issuer {
pub name: String,
pub issuer_id: AccountId
}
impl Default for SmartCertificateContract {
fn default() -> Self {
env::panic(b"SmartCertificate contract should be initialized before usage")
}
}
const DATA_IMAGE_SVG_NEAR_ICON: &str = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 288 288'%3E%3Cg id='l' data-name='l'%3E%3Cpath d='M187.58,79.81l-30.1,44.69a3.2,3.2,0,0,0,4.75,4.2L191.86,103a1.2,1.2,0,0,1,2,.91v80.46a1.2,1.2,0,0,1-2.12.77L102.18,77.93A15.35,15.35,0,0,0,90.47,72.5H87.34A15.34,15.34,0,0,0,72,87.84V201.16A15.34,15.34,0,0,0,87.34,216.5h0a15.35,15.35,0,0,0,13.08-7.31l30.1-44.69a3.2,3.2,0,0,0-4.75-4.2L96.14,186a1.2,1.2,0,0,1-2-.91V104.61a1.2,1.2,0,0,1,2.12-.77l89.55,107.23a15.35,15.35,0,0,0,11.71,5.43h3.13A15.34,15.34,0,0,0,216,201.16V87.84A15.34,15.34,0,0,0,200.66,72.5h0A15.35,15.35,0,0,0,187.58,79.81Z'/%3E%3C/g%3E%3C/svg%3E";
#[near_bindgen]
impl SmartCertificateContract {
#[init]
pub fn new(nft_owner: ValidAccountId) -> Self {
assert!(!env::state_exists(), "The contract is already initialized");
assert!(
env::is_valid_account_id(env::predecessor_account_id().as_bytes()),
"The NEAR Foundation account ID is invalid"
);
let metadata = NFTContractMetadata {
spec: NFT_METADATA_SPEC.to_string(),
name: "Example NEAR non-fungible token".to_string(),
symbol: "EXAMPLE".to_string(),
icon: Some(DATA_IMAGE_SVG_NEAR_ICON.to_string()),
base_uri: None,
reference: None,
reference_hash: None,
};
SmartCertificateContract {
owner: env::predecessor_account_id(),
issuers: UnorderedMap::new(b"i".to_vec()),
need_user_approved: UnorderedMap::new(b"n".to_vec()),
ready_deploy_nft: UnorderedMap::new(b"r".to_vec()),
nft_cert: UnorderedMap::new(b"nft".to_vec()),
nft_token: NonFungibleToken::new(
StorageKey::NonFungibleToken,
nft_owner,
Some(StorageKey::TokenMetadata),
Some(StorageKey::Enumeration),
Some(StorageKey::Approval),
),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
}
}
pub fn add_issuer(&mut self, issuer_account: AccountId, name: String) -> bool {
assert!(
env::is_valid_account_id(issuer_account.as_bytes()),
"The given account ID is invalid"
);
self.assert_called_by_foundation();
if!self.issuers.get(&issuer_account).is_some() |
return false;
}
pub fn create_cert(&mut self, user_account_id: ValidAccountId, name: String, dob: String, national_id: String) {
self.assert_called_by_issuers();
let issuer = self.issuers.get(&env::predecessor_account_id()).clone().unwrap();
let user = UserInfo {
name: name,
dob: dob,
national_id: national_id,
from: issuer.clone(),
owner: user_account_id.clone()
};
let cert_info = CertInfo {
user_info: user,
is_first_approved: false
};
let id = self.generate_cert_key(user_account_id.clone(), env::predecessor_account_id());
self.need_user_approved.insert(&id, &cert_info);
}
pub fn user_approved(&mut self, id: String) {
let cert = self.need_user_approved.get(&id).unwrap();
let new_cert = CertInfo {
user_info: cert.user_info.clone(),
is_first_approved: true
};
env::log(
format!(
"new cert @{}",
new_cert.user_info.owner
).as_bytes()
);
self.need_user_approved.remove(&id);
self.ready_deploy_nft.insert(&id, &new_cert);
}
#[payable]
pub fn nft_mint(
&mut self,
id: String,
) -> Token {
self.assert_called_by_foundation();
let cert = self.ready_deploy_nft.get(&id).unwrap();
let owner = cert.user_info.clone().owner;
let token = self.nft_token.mint((self.nft_cert.len() + 1).to_string(), owner, Some(self.create_meta_data(cert)));
let token_serialize = TokenSerialize {
token_id: token.token_id.clone(),
owner_id: token.owner_id.clone(),
metadata: token.metadata.clone().unwrap(),
tx: "".to_string()
};
self.nft_cert.insert(&id.clone(), &token_serialize);
return token;
}
pub fn finalize(&mut self, id: String, txid: String) {
let mut token = self.nft_cert.get(&id.clone()).unwrap();
token.tx = txid.clone();
self.ready_deploy_nft.remove(&id.clone());
self.nft_cert.remove(&id.clone());
self.nft_cert.insert(&txid.clone(), &token);
}
/*****************/
/* View Methods */
/*****************/
pub fn get_cert_info(&self, txid: String) -> TokenMetadata {
let cert = self.nft_cert.get(&txid.clone()).unwrap();
return cert.metadata;
}
pub fn get_issuers(&self) -> Vec<(AccountId, Issuer)> {
return self.issuers.to_vec();
}
pub fn get_certs(&self) -> Vec<(String, TokenSerialize)> {
return self
.nft_cert
.iter()
.collect();
}
pub fn get_un_approved_cert(&self, owner_id: String) -> Vec<(String, CertInfo)> {
return self.need_user_approved
.iter()
.filter(|(_k, v)| String::from(v.user_info.owner.clone()) == owner_id)
.collect();
}
pub fn get_ready_deploy_cert(&self) -> Vec<(String, CertInfo)> {
return self.ready_deploy_nft
.iter()
.collect();
}
/************/
/* Utils */
/************/
fn generate_cert_key(&self, user: ValidAccountId, issuer: AccountId) -> String {
return [String::from(user), issuer].join("_");
}
fn create_meta_data(&self, cert: CertInfo) -> TokenMetadata {
let description = cert.user_info.name + &String::from("'s Certificate issued by ") + &cert.user_info.from.name;
return TokenMetadata {
title: Some("Certificate".into()),
description: Some(description.into()),
media: None,
media_hash: None,
copies: Some(1u64),
issued_at: None,
expires_at: None,
starts_at: None,
updated_at: None,
extra: None,
reference: None,
reference_hash: None,
};
}
/************/
/* Internal */
/************/
fn assert_called_by_foundation(&self) {
assert_eq!(
&env::predecessor_account_id(),
&self.owner,
"Can only be called by NEAR Foundation"
);
}
fn assert_called_by_issuers(&self) {
assert!(
self.issuers.get(&env::predecessor_account_id()).is_some(),
"Only call by issuers"
);
}
}
near_contract_standards::impl_non_fungible_token_core!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_approval!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_enumeration!(SmartCertificateContract, nft_token);
#[near_bindgen]
impl NonFungibleTokenMetadataProvider for SmartCertificateContract {
fn nft_metadata(&self) -> NFTContractMetadata {
self.metadata.get().unwrap()
}
}
| {
let new_issuer = Issuer {
name: name,
issuer_id: issuer_account.clone(),
};
self.issuers.insert(&issuer_account, &new_issuer);
return true;
} | conditional_block |
lib.rs | use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::UnorderedMap;
use near_sdk::serde::{Deserialize, Serialize};
use near_contract_standards::non_fungible_token::metadata::{
NFTContractMetadata, NonFungibleTokenMetadataProvider, TokenMetadata, NFT_METADATA_SPEC,
};
use near_contract_standards::non_fungible_token::{Token, TokenId};
use near_contract_standards::non_fungible_token::NonFungibleToken;
use near_sdk::collections::LazyOption;
use near_sdk::json_types::ValidAccountId;
use near_sdk::{
setup_alloc, env, near_bindgen, AccountId, BorshStorageKey, Promise, PromiseOrValue,
};
#[derive(BorshSerialize, BorshStorageKey)]
enum StorageKey {
NonFungibleToken,
Metadata,
TokenMetadata,
Enumeration,
Approval,
}
setup_alloc!();
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct UserInfo {
pub name: String,
pub dob: String,
pub national_id: String,
pub from: Issuer,
pub owner: ValidAccountId
}
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct TokenSerialize {
pub token_id: String,
pub owner_id: String,
pub metadata: TokenMetadata,
pub tx: String,
}
#[derive(BorshDeserialize, BorshSerialize, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct CertInfo {
pub user_info: UserInfo,
pub is_first_approved: bool,
}
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct SmartCertificateContract{
owner: AccountId, //Owners of this contract, the only person can add more issuers
issuers: UnorderedMap<AccountId, Issuer>, //List of issuers, only issuers in this list can create a cert
need_user_approved: UnorderedMap<String, CertInfo>,
ready_deploy_nft: UnorderedMap<String, CertInfo>,
//NFT Define
nft_cert: UnorderedMap<String, TokenSerialize>,
nft_token: NonFungibleToken,
metadata: LazyOption<NFTContractMetadata>,
}
// #[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct Issuer {
pub name: String,
pub issuer_id: AccountId
}
impl Default for SmartCertificateContract {
fn default() -> Self {
env::panic(b"SmartCertificate contract should be initialized before usage")
}
}
const DATA_IMAGE_SVG_NEAR_ICON: &str = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 288 288'%3E%3Cg id='l' data-name='l'%3E%3Cpath d='M187.58,79.81l-30.1,44.69a3.2,3.2,0,0,0,4.75,4.2L191.86,103a1.2,1.2,0,0,1,2,.91v80.46a1.2,1.2,0,0,1-2.12.77L102.18,77.93A15.35,15.35,0,0,0,90.47,72.5H87.34A15.34,15.34,0,0,0,72,87.84V201.16A15.34,15.34,0,0,0,87.34,216.5h0a15.35,15.35,0,0,0,13.08-7.31l30.1-44.69a3.2,3.2,0,0,0-4.75-4.2L96.14,186a1.2,1.2,0,0,1-2-.91V104.61a1.2,1.2,0,0,1,2.12-.77l89.55,107.23a15.35,15.35,0,0,0,11.71,5.43h3.13A15.34,15.34,0,0,0,216,201.16V87.84A15.34,15.34,0,0,0,200.66,72.5h0A15.35,15.35,0,0,0,187.58,79.81Z'/%3E%3C/g%3E%3C/svg%3E";
#[near_bindgen]
impl SmartCertificateContract {
#[init]
pub fn new(nft_owner: ValidAccountId) -> Self {
assert!(!env::state_exists(), "The contract is already initialized");
assert!(
env::is_valid_account_id(env::predecessor_account_id().as_bytes()),
"The NEAR Foundation account ID is invalid"
);
let metadata = NFTContractMetadata {
spec: NFT_METADATA_SPEC.to_string(),
name: "Example NEAR non-fungible token".to_string(),
symbol: "EXAMPLE".to_string(),
icon: Some(DATA_IMAGE_SVG_NEAR_ICON.to_string()),
base_uri: None,
reference: None,
reference_hash: None,
};
SmartCertificateContract {
owner: env::predecessor_account_id(),
issuers: UnorderedMap::new(b"i".to_vec()),
need_user_approved: UnorderedMap::new(b"n".to_vec()),
ready_deploy_nft: UnorderedMap::new(b"r".to_vec()),
nft_cert: UnorderedMap::new(b"nft".to_vec()),
nft_token: NonFungibleToken::new(
StorageKey::NonFungibleToken,
nft_owner,
Some(StorageKey::TokenMetadata),
Some(StorageKey::Enumeration),
Some(StorageKey::Approval),
),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
}
}
| assert!(
env::is_valid_account_id(issuer_account.as_bytes()),
"The given account ID is invalid"
);
self.assert_called_by_foundation();
if!self.issuers.get(&issuer_account).is_some() {
let new_issuer = Issuer {
name: name,
issuer_id: issuer_account.clone(),
};
self.issuers.insert(&issuer_account, &new_issuer);
return true;
}
return false;
}
pub fn create_cert(&mut self, user_account_id: ValidAccountId, name: String, dob: String, national_id: String) {
self.assert_called_by_issuers();
let issuer = self.issuers.get(&env::predecessor_account_id()).clone().unwrap();
let user = UserInfo {
name: name,
dob: dob,
national_id: national_id,
from: issuer.clone(),
owner: user_account_id.clone()
};
let cert_info = CertInfo {
user_info: user,
is_first_approved: false
};
let id = self.generate_cert_key(user_account_id.clone(), env::predecessor_account_id());
self.need_user_approved.insert(&id, &cert_info);
}
pub fn user_approved(&mut self, id: String) {
let cert = self.need_user_approved.get(&id).unwrap();
let new_cert = CertInfo {
user_info: cert.user_info.clone(),
is_first_approved: true
};
env::log(
format!(
"new cert @{}",
new_cert.user_info.owner
).as_bytes()
);
self.need_user_approved.remove(&id);
self.ready_deploy_nft.insert(&id, &new_cert);
}
#[payable]
pub fn nft_mint(
&mut self,
id: String,
) -> Token {
self.assert_called_by_foundation();
let cert = self.ready_deploy_nft.get(&id).unwrap();
let owner = cert.user_info.clone().owner;
let token = self.nft_token.mint((self.nft_cert.len() + 1).to_string(), owner, Some(self.create_meta_data(cert)));
let token_serialize = TokenSerialize {
token_id: token.token_id.clone(),
owner_id: token.owner_id.clone(),
metadata: token.metadata.clone().unwrap(),
tx: "".to_string()
};
self.nft_cert.insert(&id.clone(), &token_serialize);
return token;
}
pub fn finalize(&mut self, id: String, txid: String) {
let mut token = self.nft_cert.get(&id.clone()).unwrap();
token.tx = txid.clone();
self.ready_deploy_nft.remove(&id.clone());
self.nft_cert.remove(&id.clone());
self.nft_cert.insert(&txid.clone(), &token);
}
/*****************/
/* View Methods */
/*****************/
pub fn get_cert_info(&self, txid: String) -> TokenMetadata {
let cert = self.nft_cert.get(&txid.clone()).unwrap();
return cert.metadata;
}
pub fn get_issuers(&self) -> Vec<(AccountId, Issuer)> {
return self.issuers.to_vec();
}
pub fn get_certs(&self) -> Vec<(String, TokenSerialize)> {
return self
.nft_cert
.iter()
.collect();
}
pub fn get_un_approved_cert(&self, owner_id: String) -> Vec<(String, CertInfo)> {
return self.need_user_approved
.iter()
.filter(|(_k, v)| String::from(v.user_info.owner.clone()) == owner_id)
.collect();
}
pub fn get_ready_deploy_cert(&self) -> Vec<(String, CertInfo)> {
return self.ready_deploy_nft
.iter()
.collect();
}
/************/
/* Utils */
/************/
fn generate_cert_key(&self, user: ValidAccountId, issuer: AccountId) -> String {
return [String::from(user), issuer].join("_");
}
fn create_meta_data(&self, cert: CertInfo) -> TokenMetadata {
let description = cert.user_info.name + &String::from("'s Certificate issued by ") + &cert.user_info.from.name;
return TokenMetadata {
title: Some("Certificate".into()),
description: Some(description.into()),
media: None,
media_hash: None,
copies: Some(1u64),
issued_at: None,
expires_at: None,
starts_at: None,
updated_at: None,
extra: None,
reference: None,
reference_hash: None,
};
}
/************/
/* Internal */
/************/
fn assert_called_by_foundation(&self) {
assert_eq!(
&env::predecessor_account_id(),
&self.owner,
"Can only be called by NEAR Foundation"
);
}
fn assert_called_by_issuers(&self) {
assert!(
self.issuers.get(&env::predecessor_account_id()).is_some(),
"Only call by issuers"
);
}
}
near_contract_standards::impl_non_fungible_token_core!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_approval!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_enumeration!(SmartCertificateContract, nft_token);
#[near_bindgen]
impl NonFungibleTokenMetadataProvider for SmartCertificateContract {
fn nft_metadata(&self) -> NFTContractMetadata {
self.metadata.get().unwrap()
}
} | pub fn add_issuer(&mut self, issuer_account: AccountId, name: String) -> bool { | random_line_split |
lib.rs | use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::UnorderedMap;
use near_sdk::serde::{Deserialize, Serialize};
use near_contract_standards::non_fungible_token::metadata::{
NFTContractMetadata, NonFungibleTokenMetadataProvider, TokenMetadata, NFT_METADATA_SPEC,
};
use near_contract_standards::non_fungible_token::{Token, TokenId};
use near_contract_standards::non_fungible_token::NonFungibleToken;
use near_sdk::collections::LazyOption;
use near_sdk::json_types::ValidAccountId;
use near_sdk::{
setup_alloc, env, near_bindgen, AccountId, BorshStorageKey, Promise, PromiseOrValue,
};
#[derive(BorshSerialize, BorshStorageKey)]
enum StorageKey {
NonFungibleToken,
Metadata,
TokenMetadata,
Enumeration,
Approval,
}
setup_alloc!();
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct UserInfo {
pub name: String,
pub dob: String,
pub national_id: String,
pub from: Issuer,
pub owner: ValidAccountId
}
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct TokenSerialize {
pub token_id: String,
pub owner_id: String,
pub metadata: TokenMetadata,
pub tx: String,
}
#[derive(BorshDeserialize, BorshSerialize, Serialize)]
#[serde(crate = "near_sdk::serde")]
pub struct CertInfo {
pub user_info: UserInfo,
pub is_first_approved: bool,
}
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct SmartCertificateContract{
owner: AccountId, //Owners of this contract, the only person can add more issuers
issuers: UnorderedMap<AccountId, Issuer>, //List of issuers, only issuers in this list can create a cert
need_user_approved: UnorderedMap<String, CertInfo>,
ready_deploy_nft: UnorderedMap<String, CertInfo>,
//NFT Define
nft_cert: UnorderedMap<String, TokenSerialize>,
nft_token: NonFungibleToken,
metadata: LazyOption<NFTContractMetadata>,
}
// #[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, Clone, Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct Issuer {
pub name: String,
pub issuer_id: AccountId
}
impl Default for SmartCertificateContract {
fn default() -> Self {
env::panic(b"SmartCertificate contract should be initialized before usage")
}
}
const DATA_IMAGE_SVG_NEAR_ICON: &str = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 288 288'%3E%3Cg id='l' data-name='l'%3E%3Cpath d='M187.58,79.81l-30.1,44.69a3.2,3.2,0,0,0,4.75,4.2L191.86,103a1.2,1.2,0,0,1,2,.91v80.46a1.2,1.2,0,0,1-2.12.77L102.18,77.93A15.35,15.35,0,0,0,90.47,72.5H87.34A15.34,15.34,0,0,0,72,87.84V201.16A15.34,15.34,0,0,0,87.34,216.5h0a15.35,15.35,0,0,0,13.08-7.31l30.1-44.69a3.2,3.2,0,0,0-4.75-4.2L96.14,186a1.2,1.2,0,0,1-2-.91V104.61a1.2,1.2,0,0,1,2.12-.77l89.55,107.23a15.35,15.35,0,0,0,11.71,5.43h3.13A15.34,15.34,0,0,0,216,201.16V87.84A15.34,15.34,0,0,0,200.66,72.5h0A15.35,15.35,0,0,0,187.58,79.81Z'/%3E%3C/g%3E%3C/svg%3E";
#[near_bindgen]
impl SmartCertificateContract {
#[init]
pub fn new(nft_owner: ValidAccountId) -> Self {
assert!(!env::state_exists(), "The contract is already initialized");
assert!(
env::is_valid_account_id(env::predecessor_account_id().as_bytes()),
"The NEAR Foundation account ID is invalid"
);
let metadata = NFTContractMetadata {
spec: NFT_METADATA_SPEC.to_string(),
name: "Example NEAR non-fungible token".to_string(),
symbol: "EXAMPLE".to_string(),
icon: Some(DATA_IMAGE_SVG_NEAR_ICON.to_string()),
base_uri: None,
reference: None,
reference_hash: None,
};
SmartCertificateContract {
owner: env::predecessor_account_id(),
issuers: UnorderedMap::new(b"i".to_vec()),
need_user_approved: UnorderedMap::new(b"n".to_vec()),
ready_deploy_nft: UnorderedMap::new(b"r".to_vec()),
nft_cert: UnorderedMap::new(b"nft".to_vec()),
nft_token: NonFungibleToken::new(
StorageKey::NonFungibleToken,
nft_owner,
Some(StorageKey::TokenMetadata),
Some(StorageKey::Enumeration),
Some(StorageKey::Approval),
),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
}
}
pub fn | (&mut self, issuer_account: AccountId, name: String) -> bool {
assert!(
env::is_valid_account_id(issuer_account.as_bytes()),
"The given account ID is invalid"
);
self.assert_called_by_foundation();
if!self.issuers.get(&issuer_account).is_some() {
let new_issuer = Issuer {
name: name,
issuer_id: issuer_account.clone(),
};
self.issuers.insert(&issuer_account, &new_issuer);
return true;
}
return false;
}
pub fn create_cert(&mut self, user_account_id: ValidAccountId, name: String, dob: String, national_id: String) {
self.assert_called_by_issuers();
let issuer = self.issuers.get(&env::predecessor_account_id()).clone().unwrap();
let user = UserInfo {
name: name,
dob: dob,
national_id: national_id,
from: issuer.clone(),
owner: user_account_id.clone()
};
let cert_info = CertInfo {
user_info: user,
is_first_approved: false
};
let id = self.generate_cert_key(user_account_id.clone(), env::predecessor_account_id());
self.need_user_approved.insert(&id, &cert_info);
}
pub fn user_approved(&mut self, id: String) {
let cert = self.need_user_approved.get(&id).unwrap();
let new_cert = CertInfo {
user_info: cert.user_info.clone(),
is_first_approved: true
};
env::log(
format!(
"new cert @{}",
new_cert.user_info.owner
).as_bytes()
);
self.need_user_approved.remove(&id);
self.ready_deploy_nft.insert(&id, &new_cert);
}
#[payable]
pub fn nft_mint(
&mut self,
id: String,
) -> Token {
self.assert_called_by_foundation();
let cert = self.ready_deploy_nft.get(&id).unwrap();
let owner = cert.user_info.clone().owner;
let token = self.nft_token.mint((self.nft_cert.len() + 1).to_string(), owner, Some(self.create_meta_data(cert)));
let token_serialize = TokenSerialize {
token_id: token.token_id.clone(),
owner_id: token.owner_id.clone(),
metadata: token.metadata.clone().unwrap(),
tx: "".to_string()
};
self.nft_cert.insert(&id.clone(), &token_serialize);
return token;
}
pub fn finalize(&mut self, id: String, txid: String) {
let mut token = self.nft_cert.get(&id.clone()).unwrap();
token.tx = txid.clone();
self.ready_deploy_nft.remove(&id.clone());
self.nft_cert.remove(&id.clone());
self.nft_cert.insert(&txid.clone(), &token);
}
/*****************/
/* View Methods */
/*****************/
pub fn get_cert_info(&self, txid: String) -> TokenMetadata {
let cert = self.nft_cert.get(&txid.clone()).unwrap();
return cert.metadata;
}
pub fn get_issuers(&self) -> Vec<(AccountId, Issuer)> {
return self.issuers.to_vec();
}
pub fn get_certs(&self) -> Vec<(String, TokenSerialize)> {
return self
.nft_cert
.iter()
.collect();
}
pub fn get_un_approved_cert(&self, owner_id: String) -> Vec<(String, CertInfo)> {
return self.need_user_approved
.iter()
.filter(|(_k, v)| String::from(v.user_info.owner.clone()) == owner_id)
.collect();
}
pub fn get_ready_deploy_cert(&self) -> Vec<(String, CertInfo)> {
return self.ready_deploy_nft
.iter()
.collect();
}
/************/
/* Utils */
/************/
fn generate_cert_key(&self, user: ValidAccountId, issuer: AccountId) -> String {
return [String::from(user), issuer].join("_");
}
fn create_meta_data(&self, cert: CertInfo) -> TokenMetadata {
let description = cert.user_info.name + &String::from("'s Certificate issued by ") + &cert.user_info.from.name;
return TokenMetadata {
title: Some("Certificate".into()),
description: Some(description.into()),
media: None,
media_hash: None,
copies: Some(1u64),
issued_at: None,
expires_at: None,
starts_at: None,
updated_at: None,
extra: None,
reference: None,
reference_hash: None,
};
}
/************/
/* Internal */
/************/
fn assert_called_by_foundation(&self) {
assert_eq!(
&env::predecessor_account_id(),
&self.owner,
"Can only be called by NEAR Foundation"
);
}
fn assert_called_by_issuers(&self) {
assert!(
self.issuers.get(&env::predecessor_account_id()).is_some(),
"Only call by issuers"
);
}
}
near_contract_standards::impl_non_fungible_token_core!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_approval!(SmartCertificateContract, nft_token);
near_contract_standards::impl_non_fungible_token_enumeration!(SmartCertificateContract, nft_token);
#[near_bindgen]
impl NonFungibleTokenMetadataProvider for SmartCertificateContract {
fn nft_metadata(&self) -> NFTContractMetadata {
self.metadata.get().unwrap()
}
}
| add_issuer | identifier_name |
args.rs | // Copyright 2016 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.
//! Global initialization and retrieval of command line arguments.
//!
//! On some platforms these are stored during runtime startup,
//! and on some they are retrieved from the system on demand.
#![allow(dead_code)] // runtime init functions not used during testing
use ffi::OsString;
use marker::PhantomData;
use vec;
/// One-time global initialization.
pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
/// One-time global cleanup.
pub unsafe fn cleanup() { imp::cleanup() }
/// Returns the command line arguments
pub fn args() -> Args {
imp::args()
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
}
mod imp {
use os::unix::prelude::*;
use mem;
use ffi::{CStr, OsString};
use marker::PhantomData;
use libc;
use super::Args;
use sys_common::mutex::Mutex;
static mut GLOBAL_ARGS_PTR: usize = 0;
static LOCK: Mutex = Mutex::new();
pub unsafe fn | (argc: isize, argv: *const *const u8) {
let args = (0..argc).map(|i| {
CStr::from_ptr(*argv.offset(i) as *const libc::c_char).to_bytes().to_vec()
}).collect();
LOCK.lock();
let ptr = get_global_ptr();
assert!((*ptr).is_none());
(*ptr) = Some(box args);
LOCK.unlock();
}
pub unsafe fn cleanup() {
LOCK.lock();
*get_global_ptr() = None;
LOCK.unlock();
}
pub fn args() -> Args {
let bytes = clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
}
fn clone() -> Option<Vec<Vec<u8>>> {
unsafe {
LOCK.lock();
let ptr = get_global_ptr();
let ret = (*ptr).as_ref().map(|s| (**s).clone());
LOCK.unlock();
return ret
}
}
fn get_global_ptr() -> *mut Option<Box<Vec<Vec<u8>>>> {
unsafe { mem::transmute(&GLOBAL_ARGS_PTR) }
}
}
| init | identifier_name |
args.rs | // Copyright 2016 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.
//! Global initialization and retrieval of command line arguments.
//!
//! On some platforms these are stored during runtime startup,
//! and on some they are retrieved from the system on demand.
#![allow(dead_code)] // runtime init functions not used during testing
use ffi::OsString;
use marker::PhantomData;
use vec;
/// One-time global initialization.
pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
/// One-time global cleanup.
pub unsafe fn cleanup() { imp::cleanup() }
/// Returns the command line arguments
pub fn args() -> Args {
imp::args()
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
| fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
}
mod imp {
use os::unix::prelude::*;
use mem;
use ffi::{CStr, OsString};
use marker::PhantomData;
use libc;
use super::Args;
use sys_common::mutex::Mutex;
static mut GLOBAL_ARGS_PTR: usize = 0;
static LOCK: Mutex = Mutex::new();
pub unsafe fn init(argc: isize, argv: *const *const u8) {
let args = (0..argc).map(|i| {
CStr::from_ptr(*argv.offset(i) as *const libc::c_char).to_bytes().to_vec()
}).collect();
LOCK.lock();
let ptr = get_global_ptr();
assert!((*ptr).is_none());
(*ptr) = Some(box args);
LOCK.unlock();
}
pub unsafe fn cleanup() {
LOCK.lock();
*get_global_ptr() = None;
LOCK.unlock();
}
pub fn args() -> Args {
let bytes = clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
}
fn clone() -> Option<Vec<Vec<u8>>> {
unsafe {
LOCK.lock();
let ptr = get_global_ptr();
let ret = (*ptr).as_ref().map(|s| (**s).clone());
LOCK.unlock();
return ret
}
}
fn get_global_ptr() -> *mut Option<Box<Vec<Vec<u8>>>> {
unsafe { mem::transmute(&GLOBAL_ARGS_PTR) }
}
} | impl DoubleEndedIterator for Args { | random_line_split |
args.rs | // Copyright 2016 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.
//! Global initialization and retrieval of command line arguments.
//!
//! On some platforms these are stored during runtime startup,
//! and on some they are retrieved from the system on demand.
#![allow(dead_code)] // runtime init functions not used during testing
use ffi::OsString;
use marker::PhantomData;
use vec;
/// One-time global initialization.
pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
/// One-time global cleanup.
pub unsafe fn cleanup() { imp::cleanup() }
/// Returns the command line arguments
pub fn args() -> Args {
imp::args()
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] |
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
impl DoubleEndedIterator for Args {
fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
}
mod imp {
use os::unix::prelude::*;
use mem;
use ffi::{CStr, OsString};
use marker::PhantomData;
use libc;
use super::Args;
use sys_common::mutex::Mutex;
static mut GLOBAL_ARGS_PTR: usize = 0;
static LOCK: Mutex = Mutex::new();
pub unsafe fn init(argc: isize, argv: *const *const u8) {
let args = (0..argc).map(|i| {
CStr::from_ptr(*argv.offset(i) as *const libc::c_char).to_bytes().to_vec()
}).collect();
LOCK.lock();
let ptr = get_global_ptr();
assert!((*ptr).is_none());
(*ptr) = Some(box args);
LOCK.unlock();
}
pub unsafe fn cleanup() {
LOCK.lock();
*get_global_ptr() = None;
LOCK.unlock();
}
pub fn args() -> Args {
let bytes = clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
}
fn clone() -> Option<Vec<Vec<u8>>> {
unsafe {
LOCK.lock();
let ptr = get_global_ptr();
let ret = (*ptr).as_ref().map(|s| (**s).clone());
LOCK.unlock();
return ret
}
}
fn get_global_ptr() -> *mut Option<Box<Vec<Vec<u8>>>> {
unsafe { mem::transmute(&GLOBAL_ARGS_PTR) }
}
}
| {
self.iter.as_slice()
} | identifier_body |
windows_1257.rs | // AUTOGENERATED FROM index-windows-1257.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-windows-1257.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
8364, 129, 8218, 131, 8222, 8230, 8224, 8225, 136, 8240, 138, 8249, 140,
168, 711, 184, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 152, 8482,
154, 8250, 156, 175, 731, 159, 160, 65535, 162, 163, 164, 65535, 166, 167,
216, 169, 342, 171, 172, 173, 174, 198, 176, 177, 178, 179, 180, 181, 182,
183, 248, 185, 343, 187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197,
280, 274, 268, 201, 377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332,
213, 214, 215, 370, 321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263,
228, 229, 281, 275, 269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326,
243, 333, 245, 246, 247, 371, 322, 347, 363, 252, 380, 382, 729,
];
#[inline]
pub fn forward(code: u8) -> u16 {
FORWARD_TABLE[(code - 0x80) as uint]
}
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 131, 0, 0, 0, 0, 136,
0, 138, 0, 140, 0, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0, 152, 0, 154, 0, 156, 0,
0, 159, 160, 0, 162, 163, 164, 0, 166, 167, 141, 169, 0, 171, 172, 173,
174, 157, 176, 177, 178, 179, 180, 181, 182, 183, 143, 185, 0, 187, 188,
189, 190, 0, 0, 0, 0, 0, 196, 197, 175, 0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0,
0, 211, 0, 213, 214, 215, 168, 0, 0, 0, 220, 0, 0, 223, 0, 0, 0, 0, 228,
229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0, 0, 0, 243, 0, 245, 246, 247, 184,
0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0, 192, 224, 195, 227, 0, 0, 0, 0, 200,
232, 0, 0, 0, 0, 199, 231, 0, 0, 203, 235, 198, 230, 0, 0, 0, 0, 0, 0, 0,
0, 204, 236, 0, 0, 0, 0, 0, 0, 206, 238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0,
205, 237, 0, 0, 0, 207, 239, 0, 0, 0, 0, 217, 249, 209, 241, 210, 242, 0,
0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0, 0, 0, 0, 170, 186, 0, 0, 218, 250, 0,
0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0, 0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216,
248, 0, 0, 0, 0, 0, 202, 234, 221, 253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0,
142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 158, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 150, 151, 0, 0, 0, 145, 146, 130, 0, 147, 148, 132, 0, 134, 135,
149, 0, 0, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 137, 0, 0, 0, 0, 0, 0, 0, 0,
139, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 384, 0, 448, 0, 512,
];
#[inline]
pub fn backward(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 133 | else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
| {BACKWARD_TABLE_UPPER[offset] as uint} | conditional_block |
windows_1257.rs | // AUTOGENERATED FROM index-windows-1257.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-windows-1257.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
8364, 129, 8218, 131, 8222, 8230, 8224, 8225, 136, 8240, 138, 8249, 140,
168, 711, 184, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 152, 8482,
154, 8250, 156, 175, 731, 159, 160, 65535, 162, 163, 164, 65535, 166, 167,
216, 169, 342, 171, 172, 173, 174, 198, 176, 177, 178, 179, 180, 181, 182,
183, 248, 185, 343, 187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197,
280, 274, 268, 201, 377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332,
213, 214, 215, 370, 321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263,
228, 229, 281, 275, 269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326,
243, 333, 245, 246, 247, 371, 322, 347, 363, 252, 380, 382, 729,
];
#[inline]
pub fn forward(code: u8) -> u16 |
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 131, 0, 0, 0, 0, 136,
0, 138, 0, 140, 0, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0, 152, 0, 154, 0, 156, 0,
0, 159, 160, 0, 162, 163, 164, 0, 166, 167, 141, 169, 0, 171, 172, 173,
174, 157, 176, 177, 178, 179, 180, 181, 182, 183, 143, 185, 0, 187, 188,
189, 190, 0, 0, 0, 0, 0, 196, 197, 175, 0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0,
0, 211, 0, 213, 214, 215, 168, 0, 0, 0, 220, 0, 0, 223, 0, 0, 0, 0, 228,
229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0, 0, 0, 243, 0, 245, 246, 247, 184,
0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0, 192, 224, 195, 227, 0, 0, 0, 0, 200,
232, 0, 0, 0, 0, 199, 231, 0, 0, 203, 235, 198, 230, 0, 0, 0, 0, 0, 0, 0,
0, 204, 236, 0, 0, 0, 0, 0, 0, 206, 238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0,
205, 237, 0, 0, 0, 207, 239, 0, 0, 0, 0, 217, 249, 209, 241, 210, 242, 0,
0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0, 0, 0, 0, 170, 186, 0, 0, 218, 250, 0,
0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0, 0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216,
248, 0, 0, 0, 0, 0, 202, 234, 221, 253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0,
142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 158, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 150, 151, 0, 0, 0, 145, 146, 130, 0, 147, 148, 132, 0, 134, 135,
149, 0, 0, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 137, 0, 0, 0, 0, 0, 0, 0, 0,
139, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 384, 0, 448, 0, 512,
];
#[inline]
pub fn backward(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 133 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
| {
FORWARD_TABLE[(code - 0x80) as uint]
} | identifier_body |
windows_1257.rs | // AUTOGENERATED FROM index-windows-1257.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-windows-1257.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
8364, 129, 8218, 131, 8222, 8230, 8224, 8225, 136, 8240, 138, 8249, 140,
168, 711, 184, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 152, 8482,
154, 8250, 156, 175, 731, 159, 160, 65535, 162, 163, 164, 65535, 166, 167,
216, 169, 342, 171, 172, 173, 174, 198, 176, 177, 178, 179, 180, 181, 182,
183, 248, 185, 343, 187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197,
280, 274, 268, 201, 377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332,
213, 214, 215, 370, 321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263,
228, 229, 281, 275, 269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326,
243, 333, 245, 246, 247, 371, 322, 347, 363, 252, 380, 382, 729,
];
#[inline]
pub fn forward(code: u8) -> u16 {
FORWARD_TABLE[(code - 0x80) as uint]
}
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 131, 0, 0, 0, 0, 136,
0, 138, 0, 140, 0, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0, 152, 0, 154, 0, 156, 0,
0, 159, 160, 0, 162, 163, 164, 0, 166, 167, 141, 169, 0, 171, 172, 173,
174, 157, 176, 177, 178, 179, 180, 181, 182, 183, 143, 185, 0, 187, 188,
189, 190, 0, 0, 0, 0, 0, 196, 197, 175, 0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0,
0, 211, 0, 213, 214, 215, 168, 0, 0, 0, 220, 0, 0, 223, 0, 0, 0, 0, 228,
229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0, 0, 0, 243, 0, 245, 246, 247, 184,
0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0, 192, 224, 195, 227, 0, 0, 0, 0, 200,
232, 0, 0, 0, 0, 199, 231, 0, 0, 203, 235, 198, 230, 0, 0, 0, 0, 0, 0, 0,
0, 204, 236, 0, 0, 0, 0, 0, 0, 206, 238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0,
205, 237, 0, 0, 0, 207, 239, 0, 0, 0, 0, 217, 249, 209, 241, 210, 242, 0,
0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0, 0, 0, 0, 170, 186, 0, 0, 218, 250, 0,
0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0, 0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216,
248, 0, 0, 0, 0, 0, 202, 234, 221, 253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0,
142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 158, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 150, 151, 0, 0, 0, 145, 146, 130, 0, 147, 148, 132, 0, 134, 135,
149, 0, 0, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 137, 0, 0, 0, 0, 0, 0, 0, 0,
139, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 384, 0, 448, 0, 512,
];
#[inline]
pub fn | (code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 133 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
| backward | identifier_name |
windows_1257.rs | // AUTOGENERATED FROM index-windows-1257.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-windows-1257.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
8364, 129, 8218, 131, 8222, 8230, 8224, 8225, 136, 8240, 138, 8249, 140,
168, 711, 184, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 152, 8482,
154, 8250, 156, 175, 731, 159, 160, 65535, 162, 163, 164, 65535, 166, 167,
216, 169, 342, 171, 172, 173, 174, 198, 176, 177, 178, 179, 180, 181, 182,
183, 248, 185, 343, 187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197,
280, 274, 268, 201, 377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332,
213, 214, 215, 370, 321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263,
228, 229, 281, 275, 269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326,
243, 333, 245, 246, 247, 371, 322, 347, 363, 252, 380, 382, 729,
];
#[inline]
pub fn forward(code: u8) -> u16 {
FORWARD_TABLE[(code - 0x80) as uint]
}
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 131, 0, 0, 0, 0, 136,
0, 138, 0, 140, 0, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0, 152, 0, 154, 0, 156, 0,
0, 159, 160, 0, 162, 163, 164, 0, 166, 167, 141, 169, 0, 171, 172, 173,
174, 157, 176, 177, 178, 179, 180, 181, 182, 183, 143, 185, 0, 187, 188,
189, 190, 0, 0, 0, 0, 0, 196, 197, 175, 0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0,
0, 211, 0, 213, 214, 215, 168, 0, 0, 0, 220, 0, 0, 223, 0, 0, 0, 0, 228,
229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0, 0, 0, 243, 0, 245, 246, 247, 184,
0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0, 192, 224, 195, 227, 0, 0, 0, 0, 200,
232, 0, 0, 0, 0, 199, 231, 0, 0, 203, 235, 198, 230, 0, 0, 0, 0, 0, 0, 0,
0, 204, 236, 0, 0, 0, 0, 0, 0, 206, 238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0,
205, 237, 0, 0, 0, 207, 239, 0, 0, 0, 0, 217, 249, 209, 241, 210, 242, 0,
0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0, 0, 0, 0, 170, 186, 0, 0, 218, 250, 0,
0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0, 0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216,
248, 0, 0, 0, 0, 0, 202, 234, 221, 253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0,
142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 158, 0, 0, | 149, 0, 0, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 137, 0, 0, 0, 0, 0, 0, 0, 0,
139, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 384, 0, 448, 0, 512,
];
#[inline]
pub fn backward(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 133 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!() | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 150, 151, 0, 0, 0, 145, 146, 130, 0, 147, 148, 132, 0, 134, 135, | random_line_split |
props.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use dbus::arg::IterAppend;
use dbus_tree::{MTSync, MethodErr, PropInfo};
use crate::{
dbus_api::{
filesystem::shared::{self, filesystem_operation},
types::TData,
},
engine::{Engine, Name, Pool},
};
/// Get a filesystem property and place it on the D-Bus. The property is
/// found by means of the getter method which takes a reference to a
/// Filesystem and obtains the property from the filesystem.
fn get_filesystem_property<F, R, E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
getter: F,
) -> Result<(), MethodErr>
where
F: Fn((Name, Name, &<E::Pool as Pool>::Filesystem)) -> Result<R, String>,
R: dbus::arg::Append,
E: Engine,
{
#[allow(clippy::redundant_closure)]
i.append(
filesystem_operation(p.tree, p.path.get_name(), getter)
.map_err(|ref e| MethodErr::failed(e))?,
);
Ok(())
}
/// Get the devnode for an object path.
pub fn get_filesystem_devnode<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(pool_name, fs_name, fs)| {
Ok(shared::fs_devnode_prop::<E>(fs, &pool_name, &fs_name))
})
}
| where
E: Engine,
{
get_filesystem_property(i, p, |(_, fs_name, _)| Ok(shared::fs_name_prop(&fs_name)))
}
/// Get the creation date and time in rfc3339 format.
pub fn get_filesystem_created<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_created_prop::<E>(fs)))
}
/// Get the size of the filesystem in bytes.
pub fn get_filesystem_size<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_size_prop(fs)))
}
/// Get the size of the used portion of the filesystem in bytes.
pub fn get_filesystem_used<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_used_prop::<E>(fs)))
} | pub fn get_filesystem_name<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr> | random_line_split |
props.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use dbus::arg::IterAppend;
use dbus_tree::{MTSync, MethodErr, PropInfo};
use crate::{
dbus_api::{
filesystem::shared::{self, filesystem_operation},
types::TData,
},
engine::{Engine, Name, Pool},
};
/// Get a filesystem property and place it on the D-Bus. The property is
/// found by means of the getter method which takes a reference to a
/// Filesystem and obtains the property from the filesystem.
fn get_filesystem_property<F, R, E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
getter: F,
) -> Result<(), MethodErr>
where
F: Fn((Name, Name, &<E::Pool as Pool>::Filesystem)) -> Result<R, String>,
R: dbus::arg::Append,
E: Engine,
{
#[allow(clippy::redundant_closure)]
i.append(
filesystem_operation(p.tree, p.path.get_name(), getter)
.map_err(|ref e| MethodErr::failed(e))?,
);
Ok(())
}
/// Get the devnode for an object path.
pub fn get_filesystem_devnode<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
|
pub fn get_filesystem_name<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, fs_name, _)| Ok(shared::fs_name_prop(&fs_name)))
}
/// Get the creation date and time in rfc3339 format.
pub fn get_filesystem_created<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_created_prop::<E>(fs)))
}
/// Get the size of the filesystem in bytes.
pub fn get_filesystem_size<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_size_prop(fs)))
}
/// Get the size of the used portion of the filesystem in bytes.
pub fn get_filesystem_used<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_used_prop::<E>(fs)))
}
| {
get_filesystem_property(i, p, |(pool_name, fs_name, fs)| {
Ok(shared::fs_devnode_prop::<E>(fs, &pool_name, &fs_name))
})
} | identifier_body |
props.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use dbus::arg::IterAppend;
use dbus_tree::{MTSync, MethodErr, PropInfo};
use crate::{
dbus_api::{
filesystem::shared::{self, filesystem_operation},
types::TData,
},
engine::{Engine, Name, Pool},
};
/// Get a filesystem property and place it on the D-Bus. The property is
/// found by means of the getter method which takes a reference to a
/// Filesystem and obtains the property from the filesystem.
fn | <F, R, E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
getter: F,
) -> Result<(), MethodErr>
where
F: Fn((Name, Name, &<E::Pool as Pool>::Filesystem)) -> Result<R, String>,
R: dbus::arg::Append,
E: Engine,
{
#[allow(clippy::redundant_closure)]
i.append(
filesystem_operation(p.tree, p.path.get_name(), getter)
.map_err(|ref e| MethodErr::failed(e))?,
);
Ok(())
}
/// Get the devnode for an object path.
pub fn get_filesystem_devnode<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(pool_name, fs_name, fs)| {
Ok(shared::fs_devnode_prop::<E>(fs, &pool_name, &fs_name))
})
}
pub fn get_filesystem_name<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, fs_name, _)| Ok(shared::fs_name_prop(&fs_name)))
}
/// Get the creation date and time in rfc3339 format.
pub fn get_filesystem_created<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_created_prop::<E>(fs)))
}
/// Get the size of the filesystem in bytes.
pub fn get_filesystem_size<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_size_prop(fs)))
}
/// Get the size of the used portion of the filesystem in bytes.
pub fn get_filesystem_used<E>(
i: &mut IterAppend<'_>,
p: &PropInfo<'_, MTSync<TData<E>>, TData<E>>,
) -> Result<(), MethodErr>
where
E: Engine,
{
get_filesystem_property(i, p, |(_, _, fs)| Ok(shared::fs_used_prop::<E>(fs)))
}
| get_filesystem_property | identifier_name |
engine.rs | //! A solver for dataflow problems.
use std::borrow::BorrowMut;
use std::ffi::OsString;
use std::path::PathBuf;
use rustc_ast as ast;
use rustc_data_structures::work_queue::WorkQueue;
use rustc_graphviz as dot;
use rustc_hir::def_id::DefId;
use rustc_index::bit_set::BitSet;
use rustc_index::vec::{Idx, IndexVec};
use rustc_middle::mir::{self, traversal, BasicBlock};
use rustc_middle::mir::{create_dump_file, dump_enabled};
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::{sym, Symbol};
use super::fmt::DebugWithContext;
use super::graphviz;
use super::{
visit_results, Analysis, Direction, GenKill, GenKillAnalysis, GenKillSet, JoinSemiLattice,
ResultsCursor, ResultsVisitor,
};
/// A dataflow analysis that has converged to fixpoint.
pub struct Results<'tcx, A>
where
A: Analysis<'tcx>,
{
pub analysis: A,
pub(super) entry_sets: IndexVec<BasicBlock, A::Domain>,
}
impl<A> Results<'tcx, A>
where
A: Analysis<'tcx>,
{
/// Creates a `ResultsCursor` that can inspect these `Results`.
pub fn into_results_cursor(self, body: &'mir mir::Body<'tcx>) -> ResultsCursor<'mir, 'tcx, A> {
ResultsCursor::new(body, self)
}
/// Gets the dataflow state for the given block.
pub fn entry_set_for_block(&self, block: BasicBlock) -> &A::Domain {
&self.entry_sets[block]
}
pub fn visit_with(
&self,
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = A::Domain>,
) {
visit_results(body, blocks, self, vis)
}
pub fn visit_reachable_with(
&self,
body: &'mir mir::Body<'tcx>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = A::Domain>,
) {
let blocks = mir::traversal::reachable(body);
visit_results(body, blocks.map(|(bb, _)| bb), self, vis)
}
}
/// A solver for dataflow problems.
pub struct Engine<'a, 'tcx, A>
where
A: Analysis<'tcx>,
{
tcx: TyCtxt<'tcx>,
body: &'a mir::Body<'tcx>,
dead_unwinds: Option<&'a BitSet<BasicBlock>>,
entry_sets: IndexVec<BasicBlock, A::Domain>,
pass_name: Option<&'static str>,
analysis: A,
/// Cached, cumulative transfer functions for each block.
//
// FIXME(ecstaticmorse): This boxed `Fn` trait object is invoked inside a tight loop for
// gen/kill problems on cyclic CFGs. This is not ideal, but it doesn't seem to degrade
// performance in practice. I've tried a few ways to avoid this, but they have downsides. See
// the message for the commit that added this FIXME for more information.
apply_trans_for_block: Option<Box<dyn Fn(BasicBlock, &mut A::Domain)>>,
}
impl<A, D, T> Engine<'a, 'tcx, A>
where
A: GenKillAnalysis<'tcx, Idx = T, Domain = D>,
D: Clone + JoinSemiLattice + GenKill<T> + BorrowMut<BitSet<T>>,
T: Idx,
{
/// Creates a new `Engine` to solve a gen-kill dataflow problem.
pub fn new_gen_kill(tcx: TyCtxt<'tcx>, body: &'a mir::Body<'tcx>, analysis: A) -> Self {
// If there are no back-edges in the control-flow graph, we only ever need to apply the
// transfer function for each block exactly once (assuming that we process blocks in RPO).
//
// In this case, there's no need to compute the block transfer functions ahead of time.
if!body.is_cfg_cyclic() {
return Self::new(tcx, body, analysis, None);
}
// Otherwise, compute and store the cumulative transfer function for each block.
let identity = GenKillSet::identity(analysis.bottom_value(body).borrow().domain_size());
let mut trans_for_block = IndexVec::from_elem(identity, body.basic_blocks());
for (block, block_data) in body.basic_blocks().iter_enumerated() {
let trans = &mut trans_for_block[block];
A::Direction::gen_kill_effects_in_block(&analysis, trans, block, block_data);
}
let apply_trans = Box::new(move |bb: BasicBlock, state: &mut A::Domain| {
trans_for_block[bb].apply(state.borrow_mut());
});
Self::new(tcx, body, analysis, Some(apply_trans as Box<_>))
}
}
impl<A, D> Engine<'a, 'tcx, A>
where
A: Analysis<'tcx, Domain = D>,
D: Clone + JoinSemiLattice,
{
/// Creates a new `Engine` to solve a dataflow problem with an arbitrary transfer
/// function.
///
/// Gen-kill problems should use `new_gen_kill`, which will coalesce transfer functions for
/// better performance.
pub fn new_generic(tcx: TyCtxt<'tcx>, body: &'a mir::Body<'tcx>, analysis: A) -> Self {
Self::new(tcx, body, analysis, None)
}
fn new(
tcx: TyCtxt<'tcx>,
body: &'a mir::Body<'tcx>,
analysis: A,
apply_trans_for_block: Option<Box<dyn Fn(BasicBlock, &mut A::Domain)>>,
) -> Self {
let bottom_value = analysis.bottom_value(body);
let mut entry_sets = IndexVec::from_elem(bottom_value.clone(), body.basic_blocks());
analysis.initialize_start_block(body, &mut entry_sets[mir::START_BLOCK]);
if A::Direction::is_backward() && entry_sets[mir::START_BLOCK]!= bottom_value {
bug!("`initialize_start_block` is not yet supported for backward dataflow analyses");
}
Engine {
analysis,
tcx,
body,
dead_unwinds: None,
pass_name: None,
entry_sets,
apply_trans_for_block,
}
}
/// Signals that we do not want dataflow state to propagate across unwind edges for these
/// `BasicBlock`s.
///
/// You must take care that `dead_unwinds` does not contain a `BasicBlock` that *can* actually
/// unwind during execution. Otherwise, your dataflow results will not be correct.
pub fn dead_unwinds(mut self, dead_unwinds: &'a BitSet<BasicBlock>) -> Self {
self.dead_unwinds = Some(dead_unwinds);
self
}
/// Adds an identifier to the graphviz output for this particular run of a dataflow analysis.
///
/// Some analyses are run multiple times in the compilation pipeline. Give them a `pass_name`
/// to differentiate them. Otherwise, only the results for the latest run will be saved.
pub fn pass_name(mut self, name: &'static str) -> Self |
/// Computes the fixpoint for this dataflow problem and returns it.
pub fn iterate_to_fixpoint(self) -> Results<'tcx, A>
where
A::Domain: DebugWithContext<A>,
{
let Engine {
analysis,
body,
dead_unwinds,
mut entry_sets,
tcx,
apply_trans_for_block,
pass_name,
..
} = self;
let mut dirty_queue: WorkQueue<BasicBlock> =
WorkQueue::with_none(body.basic_blocks().len());
if A::Direction::is_forward() {
for (bb, _) in traversal::reverse_postorder(body) {
dirty_queue.insert(bb);
}
} else {
// Reverse post-order on the reverse CFG may generate a better iteration order for
// backward dataflow analyses, but probably not enough to matter.
for (bb, _) in traversal::postorder(body) {
dirty_queue.insert(bb);
}
}
// `state` is not actually used between iterations;
// this is just an optimization to avoid reallocating
// every iteration.
let mut state = analysis.bottom_value(body);
while let Some(bb) = dirty_queue.pop() {
let bb_data = &body[bb];
// Set the state to the entry state of the block.
// This is equivalent to `state = entry_sets[bb].clone()`,
// but it saves an allocation, thus improving compile times.
state.clone_from(&entry_sets[bb]);
// Apply the block transfer function, using the cached one if it exists.
match &apply_trans_for_block {
Some(apply) => apply(bb, &mut state),
None => A::Direction::apply_effects_in_block(&analysis, &mut state, bb, bb_data),
}
A::Direction::join_state_into_successors_of(
&analysis,
tcx,
body,
dead_unwinds,
&mut state,
(bb, bb_data),
|target: BasicBlock, state: &A::Domain| {
let set_changed = entry_sets[target].join(state);
if set_changed {
dirty_queue.insert(target);
}
},
);
}
let results = Results { analysis, entry_sets };
let res = write_graphviz_results(tcx, &body, &results, pass_name);
if let Err(e) = res {
error!("Failed to write graphviz dataflow results: {}", e);
}
results
}
}
// Graphviz
/// Writes a DOT file containing the results of a dataflow analysis if the user requested it via
/// `rustc_mir` attributes.
fn write_graphviz_results<A>(
tcx: TyCtxt<'tcx>,
body: &mir::Body<'tcx>,
results: &Results<'tcx, A>,
pass_name: Option<&'static str>,
) -> std::io::Result<()>
where
A: Analysis<'tcx>,
A::Domain: DebugWithContext<A>,
{
use std::fs;
use std::io::{self, Write};
let def_id = body.source.def_id();
let attrs = match RustcMirAttrs::parse(tcx, def_id) {
Ok(attrs) => attrs,
// Invalid `rustc_mir` attrs are reported in `RustcMirAttrs::parse`
Err(()) => return Ok(()),
};
let mut file = match attrs.output_path(A::NAME) {
Some(path) => {
debug!("printing dataflow results for {:?} to {}", def_id, path.display());
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
io::BufWriter::new(fs::File::create(&path)?)
}
None if tcx.sess.opts.debugging_opts.dump_mir_dataflow
&& dump_enabled(tcx, A::NAME, def_id) =>
{
create_dump_file(
tcx,
".dot",
None,
A::NAME,
&pass_name.unwrap_or("-----"),
body.source,
)?
}
_ => return Ok(()),
};
let style = match attrs.formatter {
Some(sym::two_phase) => graphviz::OutputStyle::BeforeAndAfter,
_ => graphviz::OutputStyle::AfterOnly,
};
let mut buf = Vec::new();
let graphviz = graphviz::Formatter::new(body, results, style);
let mut render_opts =
vec![dot::RenderOption::Fontname(tcx.sess.opts.debugging_opts.graphviz_font.clone())];
if tcx.sess.opts.debugging_opts.graphviz_dark_mode {
render_opts.push(dot::RenderOption::DarkTheme);
}
dot::render_opts(&graphviz, &mut buf, &render_opts)?;
file.write_all(&buf)?;
Ok(())
}
#[derive(Default)]
struct RustcMirAttrs {
basename_and_suffix: Option<PathBuf>,
formatter: Option<Symbol>,
}
impl RustcMirAttrs {
fn parse(tcx: TyCtxt<'tcx>, def_id: DefId) -> Result<Self, ()> {
let attrs = tcx.get_attrs(def_id);
let mut result = Ok(());
let mut ret = RustcMirAttrs::default();
let rustc_mir_attrs = attrs
.iter()
.filter(|attr| attr.has_name(sym::rustc_mir))
.flat_map(|attr| attr.meta_item_list().into_iter().flat_map(|v| v.into_iter()));
for attr in rustc_mir_attrs {
let attr_result = if attr.has_name(sym::borrowck_graphviz_postflow) {
Self::set_field(&mut ret.basename_and_suffix, tcx, &attr, |s| {
let path = PathBuf::from(s.to_string());
match path.file_name() {
Some(_) => Ok(path),
None => {
tcx.sess.span_err(attr.span(), "path must end in a filename");
Err(())
}
}
})
} else if attr.has_name(sym::borrowck_graphviz_format) {
Self::set_field(&mut ret.formatter, tcx, &attr, |s| match s {
sym::gen_kill | sym::two_phase => Ok(s),
_ => {
tcx.sess.span_err(attr.span(), "unknown formatter");
Err(())
}
})
} else {
Ok(())
};
result = result.and(attr_result);
}
result.map(|()| ret)
}
fn set_field<T>(
field: &mut Option<T>,
tcx: TyCtxt<'tcx>,
attr: &ast::NestedMetaItem,
mapper: impl FnOnce(Symbol) -> Result<T, ()>,
) -> Result<(), ()> {
if field.is_some() {
tcx.sess
.span_err(attr.span(), &format!("duplicate values for `{}`", attr.name_or_empty()));
return Err(());
}
if let Some(s) = attr.value_str() {
*field = Some(mapper(s)?);
Ok(())
} else {
tcx.sess
.span_err(attr.span(), &format!("`{}` requires an argument", attr.name_or_empty()));
Err(())
}
}
/// Returns the path where dataflow results should be written, or `None`
/// `borrowck_graphviz_postflow` was not specified.
///
/// This performs the following transformation to the argument of `borrowck_graphviz_postflow`:
///
/// "path/suffix.dot" -> "path/analysis_name_suffix.dot"
fn output_path(&self, analysis_name: &str) -> Option<PathBuf> {
let mut ret = self.basename_and_suffix.as_ref().cloned()?;
let suffix = ret.file_name().unwrap(); // Checked when parsing attrs
let mut file_name: OsString = analysis_name.into();
file_name.push("_");
file_name.push(suffix);
ret.set_file_name(file_name);
Some(ret)
}
}
| {
self.pass_name = Some(name);
self
} | identifier_body |
engine.rs | //! A solver for dataflow problems.
use std::borrow::BorrowMut;
use std::ffi::OsString;
use std::path::PathBuf;
use rustc_ast as ast;
use rustc_data_structures::work_queue::WorkQueue;
use rustc_graphviz as dot;
use rustc_hir::def_id::DefId;
use rustc_index::bit_set::BitSet;
use rustc_index::vec::{Idx, IndexVec};
use rustc_middle::mir::{self, traversal, BasicBlock};
use rustc_middle::mir::{create_dump_file, dump_enabled};
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::{sym, Symbol};
use super::fmt::DebugWithContext;
use super::graphviz;
use super::{
visit_results, Analysis, Direction, GenKill, GenKillAnalysis, GenKillSet, JoinSemiLattice,
ResultsCursor, ResultsVisitor,
};
/// A dataflow analysis that has converged to fixpoint.
pub struct Results<'tcx, A>
where
A: Analysis<'tcx>,
{
pub analysis: A,
pub(super) entry_sets: IndexVec<BasicBlock, A::Domain>,
}
impl<A> Results<'tcx, A>
where
A: Analysis<'tcx>,
{
/// Creates a `ResultsCursor` that can inspect these `Results`.
pub fn into_results_cursor(self, body: &'mir mir::Body<'tcx>) -> ResultsCursor<'mir, 'tcx, A> {
ResultsCursor::new(body, self)
}
/// Gets the dataflow state for the given block.
pub fn entry_set_for_block(&self, block: BasicBlock) -> &A::Domain {
&self.entry_sets[block]
}
pub fn visit_with(
&self,
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = A::Domain>,
) {
visit_results(body, blocks, self, vis)
}
pub fn visit_reachable_with(
&self,
body: &'mir mir::Body<'tcx>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = A::Domain>,
) {
let blocks = mir::traversal::reachable(body);
visit_results(body, blocks.map(|(bb, _)| bb), self, vis)
}
}
/// A solver for dataflow problems.
pub struct Engine<'a, 'tcx, A>
where
A: Analysis<'tcx>,
{
tcx: TyCtxt<'tcx>,
body: &'a mir::Body<'tcx>,
dead_unwinds: Option<&'a BitSet<BasicBlock>>,
entry_sets: IndexVec<BasicBlock, A::Domain>,
pass_name: Option<&'static str>,
analysis: A,
/// Cached, cumulative transfer functions for each block.
//
// FIXME(ecstaticmorse): This boxed `Fn` trait object is invoked inside a tight loop for
// gen/kill problems on cyclic CFGs. This is not ideal, but it doesn't seem to degrade
// performance in practice. I've tried a few ways to avoid this, but they have downsides. See
// the message for the commit that added this FIXME for more information.
apply_trans_for_block: Option<Box<dyn Fn(BasicBlock, &mut A::Domain)>>,
}
impl<A, D, T> Engine<'a, 'tcx, A>
where
A: GenKillAnalysis<'tcx, Idx = T, Domain = D>,
D: Clone + JoinSemiLattice + GenKill<T> + BorrowMut<BitSet<T>>,
T: Idx,
{
/// Creates a new `Engine` to solve a gen-kill dataflow problem.
pub fn new_gen_kill(tcx: TyCtxt<'tcx>, body: &'a mir::Body<'tcx>, analysis: A) -> Self {
// If there are no back-edges in the control-flow graph, we only ever need to apply the
// transfer function for each block exactly once (assuming that we process blocks in RPO).
//
// In this case, there's no need to compute the block transfer functions ahead of time.
if!body.is_cfg_cyclic() {
return Self::new(tcx, body, analysis, None);
}
// Otherwise, compute and store the cumulative transfer function for each block.
let identity = GenKillSet::identity(analysis.bottom_value(body).borrow().domain_size());
let mut trans_for_block = IndexVec::from_elem(identity, body.basic_blocks());
for (block, block_data) in body.basic_blocks().iter_enumerated() {
let trans = &mut trans_for_block[block];
A::Direction::gen_kill_effects_in_block(&analysis, trans, block, block_data);
}
let apply_trans = Box::new(move |bb: BasicBlock, state: &mut A::Domain| {
trans_for_block[bb].apply(state.borrow_mut());
});
Self::new(tcx, body, analysis, Some(apply_trans as Box<_>))
}
}
impl<A, D> Engine<'a, 'tcx, A>
where
A: Analysis<'tcx, Domain = D>,
D: Clone + JoinSemiLattice,
{
/// Creates a new `Engine` to solve a dataflow problem with an arbitrary transfer
/// function.
///
/// Gen-kill problems should use `new_gen_kill`, which will coalesce transfer functions for
/// better performance.
pub fn new_generic(tcx: TyCtxt<'tcx>, body: &'a mir::Body<'tcx>, analysis: A) -> Self {
Self::new(tcx, body, analysis, None)
}
fn new(
tcx: TyCtxt<'tcx>,
body: &'a mir::Body<'tcx>,
analysis: A,
apply_trans_for_block: Option<Box<dyn Fn(BasicBlock, &mut A::Domain)>>,
) -> Self {
let bottom_value = analysis.bottom_value(body);
let mut entry_sets = IndexVec::from_elem(bottom_value.clone(), body.basic_blocks());
analysis.initialize_start_block(body, &mut entry_sets[mir::START_BLOCK]);
if A::Direction::is_backward() && entry_sets[mir::START_BLOCK]!= bottom_value {
bug!("`initialize_start_block` is not yet supported for backward dataflow analyses");
}
Engine {
analysis,
tcx,
body,
dead_unwinds: None,
pass_name: None,
entry_sets,
apply_trans_for_block,
}
}
/// Signals that we do not want dataflow state to propagate across unwind edges for these
/// `BasicBlock`s.
///
/// You must take care that `dead_unwinds` does not contain a `BasicBlock` that *can* actually
/// unwind during execution. Otherwise, your dataflow results will not be correct.
pub fn dead_unwinds(mut self, dead_unwinds: &'a BitSet<BasicBlock>) -> Self {
self.dead_unwinds = Some(dead_unwinds);
self
}
/// Adds an identifier to the graphviz output for this particular run of a dataflow analysis.
///
/// Some analyses are run multiple times in the compilation pipeline. Give them a `pass_name`
/// to differentiate them. Otherwise, only the results for the latest run will be saved.
pub fn pass_name(mut self, name: &'static str) -> Self {
self.pass_name = Some(name);
self
}
/// Computes the fixpoint for this dataflow problem and returns it.
pub fn | (self) -> Results<'tcx, A>
where
A::Domain: DebugWithContext<A>,
{
let Engine {
analysis,
body,
dead_unwinds,
mut entry_sets,
tcx,
apply_trans_for_block,
pass_name,
..
} = self;
let mut dirty_queue: WorkQueue<BasicBlock> =
WorkQueue::with_none(body.basic_blocks().len());
if A::Direction::is_forward() {
for (bb, _) in traversal::reverse_postorder(body) {
dirty_queue.insert(bb);
}
} else {
// Reverse post-order on the reverse CFG may generate a better iteration order for
// backward dataflow analyses, but probably not enough to matter.
for (bb, _) in traversal::postorder(body) {
dirty_queue.insert(bb);
}
}
// `state` is not actually used between iterations;
// this is just an optimization to avoid reallocating
// every iteration.
let mut state = analysis.bottom_value(body);
while let Some(bb) = dirty_queue.pop() {
let bb_data = &body[bb];
// Set the state to the entry state of the block.
// This is equivalent to `state = entry_sets[bb].clone()`,
// but it saves an allocation, thus improving compile times.
state.clone_from(&entry_sets[bb]);
// Apply the block transfer function, using the cached one if it exists.
match &apply_trans_for_block {
Some(apply) => apply(bb, &mut state),
None => A::Direction::apply_effects_in_block(&analysis, &mut state, bb, bb_data),
}
A::Direction::join_state_into_successors_of(
&analysis,
tcx,
body,
dead_unwinds,
&mut state,
(bb, bb_data),
|target: BasicBlock, state: &A::Domain| {
let set_changed = entry_sets[target].join(state);
if set_changed {
dirty_queue.insert(target);
}
},
);
}
let results = Results { analysis, entry_sets };
let res = write_graphviz_results(tcx, &body, &results, pass_name);
if let Err(e) = res {
error!("Failed to write graphviz dataflow results: {}", e);
}
results
}
}
// Graphviz
/// Writes a DOT file containing the results of a dataflow analysis if the user requested it via
/// `rustc_mir` attributes.
fn write_graphviz_results<A>(
tcx: TyCtxt<'tcx>,
body: &mir::Body<'tcx>,
results: &Results<'tcx, A>,
pass_name: Option<&'static str>,
) -> std::io::Result<()>
where
A: Analysis<'tcx>,
A::Domain: DebugWithContext<A>,
{
use std::fs;
use std::io::{self, Write};
let def_id = body.source.def_id();
let attrs = match RustcMirAttrs::parse(tcx, def_id) {
Ok(attrs) => attrs,
// Invalid `rustc_mir` attrs are reported in `RustcMirAttrs::parse`
Err(()) => return Ok(()),
};
let mut file = match attrs.output_path(A::NAME) {
Some(path) => {
debug!("printing dataflow results for {:?} to {}", def_id, path.display());
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
io::BufWriter::new(fs::File::create(&path)?)
}
None if tcx.sess.opts.debugging_opts.dump_mir_dataflow
&& dump_enabled(tcx, A::NAME, def_id) =>
{
create_dump_file(
tcx,
".dot",
None,
A::NAME,
&pass_name.unwrap_or("-----"),
body.source,
)?
}
_ => return Ok(()),
};
let style = match attrs.formatter {
Some(sym::two_phase) => graphviz::OutputStyle::BeforeAndAfter,
_ => graphviz::OutputStyle::AfterOnly,
};
let mut buf = Vec::new();
let graphviz = graphviz::Formatter::new(body, results, style);
let mut render_opts =
vec![dot::RenderOption::Fontname(tcx.sess.opts.debugging_opts.graphviz_font.clone())];
if tcx.sess.opts.debugging_opts.graphviz_dark_mode {
render_opts.push(dot::RenderOption::DarkTheme);
}
dot::render_opts(&graphviz, &mut buf, &render_opts)?;
file.write_all(&buf)?;
Ok(())
}
#[derive(Default)]
struct RustcMirAttrs {
basename_and_suffix: Option<PathBuf>,
formatter: Option<Symbol>,
}
impl RustcMirAttrs {
fn parse(tcx: TyCtxt<'tcx>, def_id: DefId) -> Result<Self, ()> {
let attrs = tcx.get_attrs(def_id);
let mut result = Ok(());
let mut ret = RustcMirAttrs::default();
let rustc_mir_attrs = attrs
.iter()
.filter(|attr| attr.has_name(sym::rustc_mir))
.flat_map(|attr| attr.meta_item_list().into_iter().flat_map(|v| v.into_iter()));
for attr in rustc_mir_attrs {
let attr_result = if attr.has_name(sym::borrowck_graphviz_postflow) {
Self::set_field(&mut ret.basename_and_suffix, tcx, &attr, |s| {
let path = PathBuf::from(s.to_string());
match path.file_name() {
Some(_) => Ok(path),
None => {
tcx.sess.span_err(attr.span(), "path must end in a filename");
Err(())
}
}
})
} else if attr.has_name(sym::borrowck_graphviz_format) {
Self::set_field(&mut ret.formatter, tcx, &attr, |s| match s {
sym::gen_kill | sym::two_phase => Ok(s),
_ => {
tcx.sess.span_err(attr.span(), "unknown formatter");
Err(())
}
})
} else {
Ok(())
};
result = result.and(attr_result);
}
result.map(|()| ret)
}
fn set_field<T>(
field: &mut Option<T>,
tcx: TyCtxt<'tcx>,
attr: &ast::NestedMetaItem,
mapper: impl FnOnce(Symbol) -> Result<T, ()>,
) -> Result<(), ()> {
if field.is_some() {
tcx.sess
.span_err(attr.span(), &format!("duplicate values for `{}`", attr.name_or_empty()));
return Err(());
}
if let Some(s) = attr.value_str() {
*field = Some(mapper(s)?);
Ok(())
} else {
tcx.sess
.span_err(attr.span(), &format!("`{}` requires an argument", attr.name_or_empty()));
Err(())
}
}
/// Returns the path where dataflow results should be written, or `None`
/// `borrowck_graphviz_postflow` was not specified.
///
/// This performs the following transformation to the argument of `borrowck_graphviz_postflow`:
///
/// "path/suffix.dot" -> "path/analysis_name_suffix.dot"
fn output_path(&self, analysis_name: &str) -> Option<PathBuf> {
let mut ret = self.basename_and_suffix.as_ref().cloned()?;
let suffix = ret.file_name().unwrap(); // Checked when parsing attrs
let mut file_name: OsString = analysis_name.into();
file_name.push("_");
file_name.push(suffix);
ret.set_file_name(file_name);
Some(ret)
}
}
| iterate_to_fixpoint | identifier_name |
engine.rs | //! A solver for dataflow problems.
use std::borrow::BorrowMut;
use std::ffi::OsString;
use std::path::PathBuf;
use rustc_ast as ast;
use rustc_data_structures::work_queue::WorkQueue;
use rustc_graphviz as dot;
use rustc_hir::def_id::DefId;
use rustc_index::bit_set::BitSet;
use rustc_index::vec::{Idx, IndexVec};
use rustc_middle::mir::{self, traversal, BasicBlock};
use rustc_middle::mir::{create_dump_file, dump_enabled};
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::{sym, Symbol};
use super::fmt::DebugWithContext;
use super::graphviz;
use super::{
visit_results, Analysis, Direction, GenKill, GenKillAnalysis, GenKillSet, JoinSemiLattice,
ResultsCursor, ResultsVisitor,
};
/// A dataflow analysis that has converged to fixpoint.
pub struct Results<'tcx, A>
where
A: Analysis<'tcx>,
{
pub analysis: A,
pub(super) entry_sets: IndexVec<BasicBlock, A::Domain>,
}
impl<A> Results<'tcx, A>
where
A: Analysis<'tcx>,
{
/// Creates a `ResultsCursor` that can inspect these `Results`.
pub fn into_results_cursor(self, body: &'mir mir::Body<'tcx>) -> ResultsCursor<'mir, 'tcx, A> {
ResultsCursor::new(body, self)
}
/// Gets the dataflow state for the given block.
pub fn entry_set_for_block(&self, block: BasicBlock) -> &A::Domain {
&self.entry_sets[block]
}
pub fn visit_with(
&self,
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = A::Domain>,
) {
visit_results(body, blocks, self, vis)
}
pub fn visit_reachable_with(
&self,
body: &'mir mir::Body<'tcx>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = A::Domain>,
) {
let blocks = mir::traversal::reachable(body);
visit_results(body, blocks.map(|(bb, _)| bb), self, vis)
}
}
/// A solver for dataflow problems.
pub struct Engine<'a, 'tcx, A>
where
A: Analysis<'tcx>,
{
tcx: TyCtxt<'tcx>,
body: &'a mir::Body<'tcx>,
dead_unwinds: Option<&'a BitSet<BasicBlock>>,
entry_sets: IndexVec<BasicBlock, A::Domain>,
pass_name: Option<&'static str>,
analysis: A,
/// Cached, cumulative transfer functions for each block.
//
// FIXME(ecstaticmorse): This boxed `Fn` trait object is invoked inside a tight loop for
// gen/kill problems on cyclic CFGs. This is not ideal, but it doesn't seem to degrade
// performance in practice. I've tried a few ways to avoid this, but they have downsides. See
// the message for the commit that added this FIXME for more information.
apply_trans_for_block: Option<Box<dyn Fn(BasicBlock, &mut A::Domain)>>,
}
impl<A, D, T> Engine<'a, 'tcx, A>
where
A: GenKillAnalysis<'tcx, Idx = T, Domain = D>,
D: Clone + JoinSemiLattice + GenKill<T> + BorrowMut<BitSet<T>>,
T: Idx,
{
/// Creates a new `Engine` to solve a gen-kill dataflow problem.
pub fn new_gen_kill(tcx: TyCtxt<'tcx>, body: &'a mir::Body<'tcx>, analysis: A) -> Self {
// If there are no back-edges in the control-flow graph, we only ever need to apply the
// transfer function for each block exactly once (assuming that we process blocks in RPO).
//
// In this case, there's no need to compute the block transfer functions ahead of time.
if!body.is_cfg_cyclic() {
return Self::new(tcx, body, analysis, None);
}
// Otherwise, compute and store the cumulative transfer function for each block.
let identity = GenKillSet::identity(analysis.bottom_value(body).borrow().domain_size());
let mut trans_for_block = IndexVec::from_elem(identity, body.basic_blocks());
for (block, block_data) in body.basic_blocks().iter_enumerated() {
let trans = &mut trans_for_block[block];
A::Direction::gen_kill_effects_in_block(&analysis, trans, block, block_data);
}
let apply_trans = Box::new(move |bb: BasicBlock, state: &mut A::Domain| {
trans_for_block[bb].apply(state.borrow_mut());
});
Self::new(tcx, body, analysis, Some(apply_trans as Box<_>))
}
}
impl<A, D> Engine<'a, 'tcx, A>
where
A: Analysis<'tcx, Domain = D>,
D: Clone + JoinSemiLattice,
{
/// Creates a new `Engine` to solve a dataflow problem with an arbitrary transfer
/// function.
///
/// Gen-kill problems should use `new_gen_kill`, which will coalesce transfer functions for
/// better performance.
pub fn new_generic(tcx: TyCtxt<'tcx>, body: &'a mir::Body<'tcx>, analysis: A) -> Self {
Self::new(tcx, body, analysis, None)
}
fn new(
tcx: TyCtxt<'tcx>,
body: &'a mir::Body<'tcx>,
analysis: A,
apply_trans_for_block: Option<Box<dyn Fn(BasicBlock, &mut A::Domain)>>,
) -> Self {
let bottom_value = analysis.bottom_value(body);
let mut entry_sets = IndexVec::from_elem(bottom_value.clone(), body.basic_blocks());
analysis.initialize_start_block(body, &mut entry_sets[mir::START_BLOCK]);
if A::Direction::is_backward() && entry_sets[mir::START_BLOCK]!= bottom_value {
bug!("`initialize_start_block` is not yet supported for backward dataflow analyses");
}
Engine {
analysis,
tcx,
body,
dead_unwinds: None,
pass_name: None,
entry_sets,
apply_trans_for_block,
}
}
/// Signals that we do not want dataflow state to propagate across unwind edges for these
/// `BasicBlock`s.
///
/// You must take care that `dead_unwinds` does not contain a `BasicBlock` that *can* actually
/// unwind during execution. Otherwise, your dataflow results will not be correct.
pub fn dead_unwinds(mut self, dead_unwinds: &'a BitSet<BasicBlock>) -> Self {
self.dead_unwinds = Some(dead_unwinds);
self
}
/// Adds an identifier to the graphviz output for this particular run of a dataflow analysis.
///
/// Some analyses are run multiple times in the compilation pipeline. Give them a `pass_name`
/// to differentiate them. Otherwise, only the results for the latest run will be saved.
pub fn pass_name(mut self, name: &'static str) -> Self {
self.pass_name = Some(name);
self
}
/// Computes the fixpoint for this dataflow problem and returns it.
pub fn iterate_to_fixpoint(self) -> Results<'tcx, A>
where
A::Domain: DebugWithContext<A>,
{
let Engine {
analysis,
body,
dead_unwinds,
mut entry_sets,
tcx,
apply_trans_for_block,
pass_name,
..
} = self;
let mut dirty_queue: WorkQueue<BasicBlock> =
WorkQueue::with_none(body.basic_blocks().len());
if A::Direction::is_forward() {
for (bb, _) in traversal::reverse_postorder(body) {
dirty_queue.insert(bb);
}
} else {
// Reverse post-order on the reverse CFG may generate a better iteration order for
// backward dataflow analyses, but probably not enough to matter.
for (bb, _) in traversal::postorder(body) {
dirty_queue.insert(bb);
}
}
// `state` is not actually used between iterations;
// this is just an optimization to avoid reallocating
// every iteration.
let mut state = analysis.bottom_value(body);
while let Some(bb) = dirty_queue.pop() {
let bb_data = &body[bb];
// Set the state to the entry state of the block.
// This is equivalent to `state = entry_sets[bb].clone()`,
// but it saves an allocation, thus improving compile times.
state.clone_from(&entry_sets[bb]);
// Apply the block transfer function, using the cached one if it exists.
match &apply_trans_for_block {
Some(apply) => apply(bb, &mut state),
None => A::Direction::apply_effects_in_block(&analysis, &mut state, bb, bb_data),
}
A::Direction::join_state_into_successors_of(
&analysis,
tcx,
body,
dead_unwinds,
&mut state,
(bb, bb_data),
|target: BasicBlock, state: &A::Domain| {
let set_changed = entry_sets[target].join(state);
if set_changed {
dirty_queue.insert(target);
}
},
);
}
let results = Results { analysis, entry_sets };
let res = write_graphviz_results(tcx, &body, &results, pass_name);
if let Err(e) = res {
error!("Failed to write graphviz dataflow results: {}", e);
}
results
}
}
// Graphviz
/// Writes a DOT file containing the results of a dataflow analysis if the user requested it via | tcx: TyCtxt<'tcx>,
body: &mir::Body<'tcx>,
results: &Results<'tcx, A>,
pass_name: Option<&'static str>,
) -> std::io::Result<()>
where
A: Analysis<'tcx>,
A::Domain: DebugWithContext<A>,
{
use std::fs;
use std::io::{self, Write};
let def_id = body.source.def_id();
let attrs = match RustcMirAttrs::parse(tcx, def_id) {
Ok(attrs) => attrs,
// Invalid `rustc_mir` attrs are reported in `RustcMirAttrs::parse`
Err(()) => return Ok(()),
};
let mut file = match attrs.output_path(A::NAME) {
Some(path) => {
debug!("printing dataflow results for {:?} to {}", def_id, path.display());
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
io::BufWriter::new(fs::File::create(&path)?)
}
None if tcx.sess.opts.debugging_opts.dump_mir_dataflow
&& dump_enabled(tcx, A::NAME, def_id) =>
{
create_dump_file(
tcx,
".dot",
None,
A::NAME,
&pass_name.unwrap_or("-----"),
body.source,
)?
}
_ => return Ok(()),
};
let style = match attrs.formatter {
Some(sym::two_phase) => graphviz::OutputStyle::BeforeAndAfter,
_ => graphviz::OutputStyle::AfterOnly,
};
let mut buf = Vec::new();
let graphviz = graphviz::Formatter::new(body, results, style);
let mut render_opts =
vec![dot::RenderOption::Fontname(tcx.sess.opts.debugging_opts.graphviz_font.clone())];
if tcx.sess.opts.debugging_opts.graphviz_dark_mode {
render_opts.push(dot::RenderOption::DarkTheme);
}
dot::render_opts(&graphviz, &mut buf, &render_opts)?;
file.write_all(&buf)?;
Ok(())
}
#[derive(Default)]
struct RustcMirAttrs {
basename_and_suffix: Option<PathBuf>,
formatter: Option<Symbol>,
}
impl RustcMirAttrs {
fn parse(tcx: TyCtxt<'tcx>, def_id: DefId) -> Result<Self, ()> {
let attrs = tcx.get_attrs(def_id);
let mut result = Ok(());
let mut ret = RustcMirAttrs::default();
let rustc_mir_attrs = attrs
.iter()
.filter(|attr| attr.has_name(sym::rustc_mir))
.flat_map(|attr| attr.meta_item_list().into_iter().flat_map(|v| v.into_iter()));
for attr in rustc_mir_attrs {
let attr_result = if attr.has_name(sym::borrowck_graphviz_postflow) {
Self::set_field(&mut ret.basename_and_suffix, tcx, &attr, |s| {
let path = PathBuf::from(s.to_string());
match path.file_name() {
Some(_) => Ok(path),
None => {
tcx.sess.span_err(attr.span(), "path must end in a filename");
Err(())
}
}
})
} else if attr.has_name(sym::borrowck_graphviz_format) {
Self::set_field(&mut ret.formatter, tcx, &attr, |s| match s {
sym::gen_kill | sym::two_phase => Ok(s),
_ => {
tcx.sess.span_err(attr.span(), "unknown formatter");
Err(())
}
})
} else {
Ok(())
};
result = result.and(attr_result);
}
result.map(|()| ret)
}
fn set_field<T>(
field: &mut Option<T>,
tcx: TyCtxt<'tcx>,
attr: &ast::NestedMetaItem,
mapper: impl FnOnce(Symbol) -> Result<T, ()>,
) -> Result<(), ()> {
if field.is_some() {
tcx.sess
.span_err(attr.span(), &format!("duplicate values for `{}`", attr.name_or_empty()));
return Err(());
}
if let Some(s) = attr.value_str() {
*field = Some(mapper(s)?);
Ok(())
} else {
tcx.sess
.span_err(attr.span(), &format!("`{}` requires an argument", attr.name_or_empty()));
Err(())
}
}
/// Returns the path where dataflow results should be written, or `None`
/// `borrowck_graphviz_postflow` was not specified.
///
/// This performs the following transformation to the argument of `borrowck_graphviz_postflow`:
///
/// "path/suffix.dot" -> "path/analysis_name_suffix.dot"
fn output_path(&self, analysis_name: &str) -> Option<PathBuf> {
let mut ret = self.basename_and_suffix.as_ref().cloned()?;
let suffix = ret.file_name().unwrap(); // Checked when parsing attrs
let mut file_name: OsString = analysis_name.into();
file_name.push("_");
file_name.push(suffix);
ret.set_file_name(file_name);
Some(ret)
}
} | /// `rustc_mir` attributes.
fn write_graphviz_results<A>( | random_line_split |
as_unsigned_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice to an immutable slice of signed integers with the same width.
// fn as_signed<'a>(&'a self) -> &'a [S];
//
// /// Converts the slice to a mutable slice of unsigned integers with the same width.
// fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
// /// Converts the slice to a mutable slice of signed integers with the same width.
// fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
// }
// macro_rules! impl_int_slice {
// ($u:ty, $s:ty, $t:ty) => {
// #[unstable(feature = "core")]
// impl IntSliceExt<$u, $s> for [$t] {
// #[inline]
// fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
// #[inline]
// fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
// #[inline]
// fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
// #[inline]
// fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
// }
// }
// }
// macro_rules! impl_int_slices {
// ($u:ty, $s:ty) => {
// impl_int_slice! { $u, $s, $u }
// impl_int_slice! { $u, $s, $s }
// }
// }
// impl_int_slices! { u8, i8 }
type U = u8;
type S = i8;
type T = S;
#[test]
fn | () {
let slice: &mut [T] = &mut [0];
{
let as_unsigned_mut: &mut [U] = slice.as_unsigned_mut();
as_unsigned_mut[0] = 0xff;
}
assert_eq!(slice, &mut[-1]);
}
}
| as_unsigned_mut_test1 | identifier_name |
as_unsigned_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice to an immutable slice of signed integers with the same width.
// fn as_signed<'a>(&'a self) -> &'a [S];
//
// /// Converts the slice to a mutable slice of unsigned integers with the same width.
// fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
// /// Converts the slice to a mutable slice of signed integers with the same width.
// fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
// }
// macro_rules! impl_int_slice {
// ($u:ty, $s:ty, $t:ty) => {
// #[unstable(feature = "core")]
// impl IntSliceExt<$u, $s> for [$t] {
// #[inline]
// fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
// #[inline]
// fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
// #[inline]
// fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
// #[inline]
// fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
// }
// }
// }
// macro_rules! impl_int_slices {
// ($u:ty, $s:ty) => {
// impl_int_slice! { $u, $s, $u }
// impl_int_slice! { $u, $s, $s }
// }
// }
// impl_int_slices! { u8, i8 }
type U = u8;
type S = i8;
type T = S;
#[test]
fn as_unsigned_mut_test1() |
}
| {
let slice: &mut [T] = &mut [0];
{
let as_unsigned_mut: &mut [U] = slice.as_unsigned_mut();
as_unsigned_mut[0] = 0xff;
}
assert_eq!(slice, &mut[-1]);
} | identifier_body |
as_unsigned_mut.rs | #![feature(core)]
extern crate core; | // pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice to an immutable slice of signed integers with the same width.
// fn as_signed<'a>(&'a self) -> &'a [S];
//
// /// Converts the slice to a mutable slice of unsigned integers with the same width.
// fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
// /// Converts the slice to a mutable slice of signed integers with the same width.
// fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
// }
// macro_rules! impl_int_slice {
// ($u:ty, $s:ty, $t:ty) => {
// #[unstable(feature = "core")]
// impl IntSliceExt<$u, $s> for [$t] {
// #[inline]
// fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
// #[inline]
// fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
// #[inline]
// fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
// #[inline]
// fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
// }
// }
// }
// macro_rules! impl_int_slices {
// ($u:ty, $s:ty) => {
// impl_int_slice! { $u, $s, $u }
// impl_int_slice! { $u, $s, $s }
// }
// }
// impl_int_slices! { u8, i8 }
type U = u8;
type S = i8;
type T = S;
#[test]
fn as_unsigned_mut_test1() {
let slice: &mut [T] = &mut [0];
{
let as_unsigned_mut: &mut [U] = slice.as_unsigned_mut();
as_unsigned_mut[0] = 0xff;
}
assert_eq!(slice, &mut[-1]);
}
} |
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
| random_line_split |
mod.rs | // 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.
//! Method lookup: the secret sauce of Rust. See `README.md`.
use astconv::AstConv;
use check::{FnCtxt};
use check::vtable;
use check::vtable::select_new_fcx_obligations;
use middle::def;
use middle::privacy::{AllPublic, DependsOn, LastPrivate, LastMod};
use middle::subst;
use middle::traits;
use middle::ty::*;
use middle::ty;
use middle::infer;
use util::ppaux::Repr;
use std::rc::Rc;
use syntax::ast::{DefId};
use syntax::ast;
use syntax::codemap::Span;
pub use self::MethodError::*;
pub use self::CandidateSource::*;
pub use self::suggest::{report_error, AllTraitsVec};
mod confirm;
mod probe;
mod suggest;
pub enum MethodError {
// Did not find an applicable method, but we did find various
// static methods that may apply, as well as a list of
// not-in-scope traits which may work.
NoMatch(Vec<CandidateSource>, Vec<ast::DefId>),
// Multiple methods might apply.
Ambiguity(Vec<CandidateSource>),
// Using a `Fn`/`FnMut`/etc method on a raw closure type before we have inferred its kind.
ClosureAmbiguity(/* DefId of fn trait */ ast::DefId),
}
// A pared down enum describing just the places from which a method
// candidate can arise. Used for error reporting only.
#[derive(Copy, PartialOrd, Ord, PartialEq, Eq)]
pub enum CandidateSource {
ImplSource(ast::DefId),
TraitSource(/* trait id */ ast::DefId),
}
type MethodIndex = uint; // just for doc purposes
/// Determines whether the type `self_ty` supports a method name `method_name` or not.
pub fn exists<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_name: ast::Name,
self_ty: Ty<'tcx>,
call_expr_id: ast::NodeId)
-> bool
{
let mode = probe::Mode::MethodCall;
match probe::probe(fcx, span, mode, method_name, self_ty, call_expr_id) {
Ok(..) => true,
Err(NoMatch(..)) => false,
Err(Ambiguity(..)) => true,
Err(ClosureAmbiguity(..)) => true,
}
}
/// Performs method lookup. If lookup is successful, it will return the callee and store an
/// appropriate adjustment for the self-expr. In some cases it may report an error (e.g., invoking
/// the `drop` method).
///
/// # Arguments
///
/// Given a method call like `foo.bar::<T1,...Tn>(...)`:
///
/// * `fcx`: the surrounding `FnCtxt` (!)
/// * `span`: the span for the method call
/// * `method_name`: the name of the method being called (`bar`)
/// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
/// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
/// * `self_expr`: the self expression (`foo`)
pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_name: ast::Name,
self_ty: Ty<'tcx>,
supplied_method_types: Vec<Ty<'tcx>>,
call_expr: &'tcx ast::Expr,
self_expr: &'tcx ast::Expr)
-> Result<MethodCallee<'tcx>, MethodError>
{
debug!("lookup(method_name={}, self_ty={}, call_expr={}, self_expr={})",
method_name.repr(fcx.tcx()),
self_ty.repr(fcx.tcx()),
call_expr.repr(fcx.tcx()),
self_expr.repr(fcx.tcx()));
let mode = probe::Mode::MethodCall;
let self_ty = fcx.infcx().resolve_type_vars_if_possible(&self_ty);
let pick = try!(probe::probe(fcx, span, mode, method_name, self_ty, call_expr.id));
Ok(confirm::confirm(fcx, span, self_expr, call_expr, self_ty, pick, supplied_method_types))
}
pub fn lookup_in_trait<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
self_expr: Option<&ast::Expr>,
m_name: ast::Name,
trait_def_id: DefId,
self_ty: Ty<'tcx>,
opt_input_types: Option<Vec<Ty<'tcx>>>)
-> Option<MethodCallee<'tcx>>
{
lookup_in_trait_adjusted(fcx, span, self_expr, m_name, trait_def_id,
ty::AutoDerefRef { autoderefs: 0, autoref: None },
self_ty, opt_input_types)
}
/// `lookup_in_trait_adjusted` is used for overloaded operators. It does a very narrow slice of
/// what the normal probe/confirm path does. In particular, it doesn't really do any probing: it
/// simply constructs an obligation for a particular trait with the given self-type and checks
/// whether that trait is implemented.
///
/// FIXME(#18741) -- It seems likely that we can consolidate some of this code with the other
/// method-lookup code. In particular, autoderef on index is basically identical to autoderef with
/// normal probes, except that the test also looks for built-in indexing. Also, the second half of
/// this method is basically the same as confirmation.
pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
self_expr: Option<&ast::Expr>,
m_name: ast::Name,
trait_def_id: DefId,
autoderefref: ty::AutoDerefRef<'tcx>,
self_ty: Ty<'tcx>,
opt_input_types: Option<Vec<Ty<'tcx>>>)
-> Option<MethodCallee<'tcx>>
{
debug!("lookup_in_trait_adjusted(self_ty={}, self_expr={}, m_name={}, trait_def_id={})",
self_ty.repr(fcx.tcx()),
self_expr.repr(fcx.tcx()),
m_name.repr(fcx.tcx()),
trait_def_id.repr(fcx.tcx()));
let trait_def = ty::lookup_trait_def(fcx.tcx(), trait_def_id);
let expected_number_of_input_types = trait_def.generics.types.len(subst::TypeSpace);
let input_types = match opt_input_types {
Some(input_types) => {
assert_eq!(expected_number_of_input_types, input_types.len());
input_types
}
None => {
fcx.inh.infcx.next_ty_vars(expected_number_of_input_types)
}
};
assert_eq!(trait_def.generics.types.len(subst::FnSpace), 0);
assert!(trait_def.generics.regions.is_empty());
// Construct a trait-reference `self_ty : Trait<input_tys>`
let substs = subst::Substs::new_trait(input_types, Vec::new(), self_ty);
let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, fcx.tcx().mk_substs(substs)));
// Construct an obligation
let poly_trait_ref = trait_ref.to_poly_trait_ref();
let obligation = traits::Obligation::misc(span,
fcx.body_id,
poly_trait_ref.as_predicate());
// Now we want to know if this can be matched
let mut selcx = traits::SelectionContext::new(fcx.infcx(), fcx);
if!selcx.evaluate_obligation(&obligation) {
debug!("--> Cannot match obligation");
return None; // Cannot be matched, no such method resolution is possible.
}
// Trait must have a method named `m_name` and it should not have
// type parameters or early-bound regions.
let tcx = fcx.tcx();
let (method_num, method_ty) = trait_method(tcx, trait_def_id, m_name).unwrap();
assert_eq!(method_ty.generics.types.len(subst::FnSpace), 0);
assert_eq!(method_ty.generics.regions.len(subst::FnSpace), 0);
debug!("lookup_in_trait_adjusted: method_num={} method_ty={}",
method_num, method_ty.repr(fcx.tcx()));
// Instantiate late-bound regions and substitute the trait
// parameters into the method type to get the actual method type.
//
// NB: Instantiate late-bound regions first so that
// `instantiate_type_scheme` can normalize associated types that
// may reference those regions.
let fn_sig = fcx.infcx().replace_late_bound_regions_with_fresh_var(span,
infer::FnCall,
&method_ty.fty.sig).0;
let fn_sig = fcx.instantiate_type_scheme(span, trait_ref.substs, &fn_sig);
let transformed_self_ty = fn_sig.inputs[0];
let fty = ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(ty::BareFnTy {
sig: ty::Binder(fn_sig),
unsafety: method_ty.fty.unsafety,
abi: method_ty.fty.abi.clone(),
}));
debug!("lookup_in_trait_adjusted: matched method fty={} obligation={}",
fty.repr(fcx.tcx()),
obligation.repr(fcx.tcx()));
// Register obligations for the parameters. This will include the
// `Self` parameter, which in turn has a bound of the main trait,
// so this also effectively registers `obligation` as well. (We
// used to register `obligation` explicitly, but that resulted in
// double error messages being reported.)
//
// Note that as the method comes from a trait, it should not have
// any late-bound regions appearing in its bounds.
let method_bounds = fcx.instantiate_bounds(span, trait_ref.substs, &method_ty.predicates);
assert!(!method_bounds.has_escaping_regions());
fcx.add_obligations_for_parameters(
traits::ObligationCause::misc(span, fcx.body_id),
&method_bounds);
// FIXME(#18653) -- Try to resolve obligations, giving us more
// typing information, which can sometimes be needed to avoid
// pathological region inference failures.
vtable::select_new_fcx_obligations(fcx);
// Insert any adjustments needed (always an autoref of some mutability).
match self_expr {
None => { }
Some(self_expr) => {
debug!("lookup_in_trait_adjusted: inserting adjustment if needed \
(self-id={}, base adjustment={:?}, explicit_self={:?})",
self_expr.id, autoderefref, method_ty.explicit_self);
match method_ty.explicit_self {
ty::ByValueExplicitSelfCategory => {
// Trait method is fn(self), no transformation needed.
if!autoderefref.is_identity() {
fcx.write_adjustment(
self_expr.id,
span,
ty::AdjustDerefRef(autoderefref));
}
}
ty::ByReferenceExplicitSelfCategory(..) => {
// Trait method is fn(&self) or fn(&mut self), need an
// autoref. Pull the region etc out of the type of first argument.
match transformed_self_ty.sty {
ty::ty_rptr(region, ty::mt { mutbl, ty: _ }) => {
let ty::AutoDerefRef { autoderefs, autoref } = autoderefref;
let autoref = autoref.map(|r| box r);
fcx.write_adjustment(
self_expr.id,
span,
ty::AdjustDerefRef(ty::AutoDerefRef {
autoderefs: autoderefs,
autoref: Some(ty::AutoPtr(*region, mutbl, autoref))
}));
}
_ => {
fcx.tcx().sess.span_bug(
span,
&format!(
"trait method is &self but first arg is: {}",
transformed_self_ty.repr(fcx.tcx())));
}
}
}
_ => {
fcx.tcx().sess.span_bug(
span,
&format!(
"unexpected explicit self type in operator method: {:?}",
method_ty.explicit_self));
}
}
}
}
let callee = MethodCallee {
origin: MethodTypeParam(MethodParam{trait_ref: trait_ref.clone(),
method_num: method_num,
impl_def_id: None}),
ty: fty,
substs: trait_ref.substs.clone()
};
debug!("callee = {}", callee.repr(fcx.tcx()));
Some(callee)
}
pub fn | <'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_name: ast::Name,
self_ty: Ty<'tcx>,
expr_id: ast::NodeId)
-> Result<(def::Def, LastPrivate), MethodError>
{
let mode = probe::Mode::Path;
let pick = try!(probe::probe(fcx, span, mode, method_name, self_ty, expr_id));
let def_id = pick.method_ty.def_id;
let mut lp = LastMod(AllPublic);
let provenance = match pick.kind {
probe::InherentImplPick(impl_def_id) => {
if pick.method_ty.vis!= ast::Public {
lp = LastMod(DependsOn(def_id));
}
def::FromImpl(impl_def_id)
}
_ => def::FromTrait(pick.method_ty.container.id())
};
Ok((def::DefMethod(def_id, provenance), lp))
}
/// Find method with name `method_name` defined in `trait_def_id` and return it, along with its
/// index (or `None`, if no such method).
fn trait_method<'tcx>(tcx: &ty::ctxt<'tcx>,
trait_def_id: ast::DefId,
method_name: ast::Name)
-> Option<(uint, Rc<ty::Method<'tcx>>)>
{
let trait_items = ty::trait_items(tcx, trait_def_id);
trait_items
.iter()
.enumerate()
.find(|&(_, ref item)| item.name() == method_name)
.and_then(|(idx, item)| item.as_opt_method().map(|m| (idx, m)))
}
fn impl_method<'tcx>(tcx: &ty::ctxt<'tcx>,
impl_def_id: ast::DefId,
method_name: ast::Name)
-> Option<Rc<ty::Method<'tcx>>>
{
let impl_items = tcx.impl_items.borrow();
let impl_items = impl_items.get(&impl_def_id).unwrap();
impl_items
.iter()
.map(|&did| ty::impl_or_trait_item(tcx, did.def_id()))
.find(|m| m.name() == method_name)
.and_then(|item| item.as_opt_method())
}
| resolve_ufcs | identifier_name |
mod.rs | // 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.
//! Method lookup: the secret sauce of Rust. See `README.md`.
use astconv::AstConv;
use check::{FnCtxt};
use check::vtable;
use check::vtable::select_new_fcx_obligations;
use middle::def;
use middle::privacy::{AllPublic, DependsOn, LastPrivate, LastMod};
use middle::subst;
use middle::traits;
use middle::ty::*;
use middle::ty;
use middle::infer;
use util::ppaux::Repr;
use std::rc::Rc;
use syntax::ast::{DefId};
use syntax::ast;
use syntax::codemap::Span;
pub use self::MethodError::*;
pub use self::CandidateSource::*;
pub use self::suggest::{report_error, AllTraitsVec};
mod confirm;
mod probe;
mod suggest;
pub enum MethodError {
// Did not find an applicable method, but we did find various
// static methods that may apply, as well as a list of
// not-in-scope traits which may work.
NoMatch(Vec<CandidateSource>, Vec<ast::DefId>),
// Multiple methods might apply.
Ambiguity(Vec<CandidateSource>),
// Using a `Fn`/`FnMut`/etc method on a raw closure type before we have inferred its kind.
ClosureAmbiguity(/* DefId of fn trait */ ast::DefId),
}
// A pared down enum describing just the places from which a method
// candidate can arise. Used for error reporting only.
#[derive(Copy, PartialOrd, Ord, PartialEq, Eq)]
pub enum CandidateSource {
ImplSource(ast::DefId),
TraitSource(/* trait id */ ast::DefId),
}
type MethodIndex = uint; // just for doc purposes
/// Determines whether the type `self_ty` supports a method name `method_name` or not.
pub fn exists<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_name: ast::Name,
self_ty: Ty<'tcx>,
call_expr_id: ast::NodeId)
-> bool | Ok(..) => true,
Err(NoMatch(..)) => false,
Err(Ambiguity(..)) => true,
Err(ClosureAmbiguity(..)) => true,
}
}
/// Performs method lookup. If lookup is successful, it will return the callee and store an
/// appropriate adjustment for the self-expr. In some cases it may report an error (e.g., invoking
/// the `drop` method).
///
/// # Arguments
///
/// Given a method call like `foo.bar::<T1,...Tn>(...)`:
///
/// * `fcx`: the surrounding `FnCtxt` (!)
/// * `span`: the span for the method call
/// * `method_name`: the name of the method being called (`bar`)
/// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
/// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
/// * `self_expr`: the self expression (`foo`)
pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_name: ast::Name,
self_ty: Ty<'tcx>,
supplied_method_types: Vec<Ty<'tcx>>,
call_expr: &'tcx ast::Expr,
self_expr: &'tcx ast::Expr)
-> Result<MethodCallee<'tcx>, MethodError>
{
debug!("lookup(method_name={}, self_ty={}, call_expr={}, self_expr={})",
method_name.repr(fcx.tcx()),
self_ty.repr(fcx.tcx()),
call_expr.repr(fcx.tcx()),
self_expr.repr(fcx.tcx()));
let mode = probe::Mode::MethodCall;
let self_ty = fcx.infcx().resolve_type_vars_if_possible(&self_ty);
let pick = try!(probe::probe(fcx, span, mode, method_name, self_ty, call_expr.id));
Ok(confirm::confirm(fcx, span, self_expr, call_expr, self_ty, pick, supplied_method_types))
}
pub fn lookup_in_trait<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
self_expr: Option<&ast::Expr>,
m_name: ast::Name,
trait_def_id: DefId,
self_ty: Ty<'tcx>,
opt_input_types: Option<Vec<Ty<'tcx>>>)
-> Option<MethodCallee<'tcx>>
{
lookup_in_trait_adjusted(fcx, span, self_expr, m_name, trait_def_id,
ty::AutoDerefRef { autoderefs: 0, autoref: None },
self_ty, opt_input_types)
}
/// `lookup_in_trait_adjusted` is used for overloaded operators. It does a very narrow slice of
/// what the normal probe/confirm path does. In particular, it doesn't really do any probing: it
/// simply constructs an obligation for a particular trait with the given self-type and checks
/// whether that trait is implemented.
///
/// FIXME(#18741) -- It seems likely that we can consolidate some of this code with the other
/// method-lookup code. In particular, autoderef on index is basically identical to autoderef with
/// normal probes, except that the test also looks for built-in indexing. Also, the second half of
/// this method is basically the same as confirmation.
pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
self_expr: Option<&ast::Expr>,
m_name: ast::Name,
trait_def_id: DefId,
autoderefref: ty::AutoDerefRef<'tcx>,
self_ty: Ty<'tcx>,
opt_input_types: Option<Vec<Ty<'tcx>>>)
-> Option<MethodCallee<'tcx>>
{
debug!("lookup_in_trait_adjusted(self_ty={}, self_expr={}, m_name={}, trait_def_id={})",
self_ty.repr(fcx.tcx()),
self_expr.repr(fcx.tcx()),
m_name.repr(fcx.tcx()),
trait_def_id.repr(fcx.tcx()));
let trait_def = ty::lookup_trait_def(fcx.tcx(), trait_def_id);
let expected_number_of_input_types = trait_def.generics.types.len(subst::TypeSpace);
let input_types = match opt_input_types {
Some(input_types) => {
assert_eq!(expected_number_of_input_types, input_types.len());
input_types
}
None => {
fcx.inh.infcx.next_ty_vars(expected_number_of_input_types)
}
};
assert_eq!(trait_def.generics.types.len(subst::FnSpace), 0);
assert!(trait_def.generics.regions.is_empty());
// Construct a trait-reference `self_ty : Trait<input_tys>`
let substs = subst::Substs::new_trait(input_types, Vec::new(), self_ty);
let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, fcx.tcx().mk_substs(substs)));
// Construct an obligation
let poly_trait_ref = trait_ref.to_poly_trait_ref();
let obligation = traits::Obligation::misc(span,
fcx.body_id,
poly_trait_ref.as_predicate());
// Now we want to know if this can be matched
let mut selcx = traits::SelectionContext::new(fcx.infcx(), fcx);
if!selcx.evaluate_obligation(&obligation) {
debug!("--> Cannot match obligation");
return None; // Cannot be matched, no such method resolution is possible.
}
// Trait must have a method named `m_name` and it should not have
// type parameters or early-bound regions.
let tcx = fcx.tcx();
let (method_num, method_ty) = trait_method(tcx, trait_def_id, m_name).unwrap();
assert_eq!(method_ty.generics.types.len(subst::FnSpace), 0);
assert_eq!(method_ty.generics.regions.len(subst::FnSpace), 0);
debug!("lookup_in_trait_adjusted: method_num={} method_ty={}",
method_num, method_ty.repr(fcx.tcx()));
// Instantiate late-bound regions and substitute the trait
// parameters into the method type to get the actual method type.
//
// NB: Instantiate late-bound regions first so that
// `instantiate_type_scheme` can normalize associated types that
// may reference those regions.
let fn_sig = fcx.infcx().replace_late_bound_regions_with_fresh_var(span,
infer::FnCall,
&method_ty.fty.sig).0;
let fn_sig = fcx.instantiate_type_scheme(span, trait_ref.substs, &fn_sig);
let transformed_self_ty = fn_sig.inputs[0];
let fty = ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(ty::BareFnTy {
sig: ty::Binder(fn_sig),
unsafety: method_ty.fty.unsafety,
abi: method_ty.fty.abi.clone(),
}));
debug!("lookup_in_trait_adjusted: matched method fty={} obligation={}",
fty.repr(fcx.tcx()),
obligation.repr(fcx.tcx()));
// Register obligations for the parameters. This will include the
// `Self` parameter, which in turn has a bound of the main trait,
// so this also effectively registers `obligation` as well. (We
// used to register `obligation` explicitly, but that resulted in
// double error messages being reported.)
//
// Note that as the method comes from a trait, it should not have
// any late-bound regions appearing in its bounds.
let method_bounds = fcx.instantiate_bounds(span, trait_ref.substs, &method_ty.predicates);
assert!(!method_bounds.has_escaping_regions());
fcx.add_obligations_for_parameters(
traits::ObligationCause::misc(span, fcx.body_id),
&method_bounds);
// FIXME(#18653) -- Try to resolve obligations, giving us more
// typing information, which can sometimes be needed to avoid
// pathological region inference failures.
vtable::select_new_fcx_obligations(fcx);
// Insert any adjustments needed (always an autoref of some mutability).
match self_expr {
None => { }
Some(self_expr) => {
debug!("lookup_in_trait_adjusted: inserting adjustment if needed \
(self-id={}, base adjustment={:?}, explicit_self={:?})",
self_expr.id, autoderefref, method_ty.explicit_self);
match method_ty.explicit_self {
ty::ByValueExplicitSelfCategory => {
// Trait method is fn(self), no transformation needed.
if!autoderefref.is_identity() {
fcx.write_adjustment(
self_expr.id,
span,
ty::AdjustDerefRef(autoderefref));
}
}
ty::ByReferenceExplicitSelfCategory(..) => {
// Trait method is fn(&self) or fn(&mut self), need an
// autoref. Pull the region etc out of the type of first argument.
match transformed_self_ty.sty {
ty::ty_rptr(region, ty::mt { mutbl, ty: _ }) => {
let ty::AutoDerefRef { autoderefs, autoref } = autoderefref;
let autoref = autoref.map(|r| box r);
fcx.write_adjustment(
self_expr.id,
span,
ty::AdjustDerefRef(ty::AutoDerefRef {
autoderefs: autoderefs,
autoref: Some(ty::AutoPtr(*region, mutbl, autoref))
}));
}
_ => {
fcx.tcx().sess.span_bug(
span,
&format!(
"trait method is &self but first arg is: {}",
transformed_self_ty.repr(fcx.tcx())));
}
}
}
_ => {
fcx.tcx().sess.span_bug(
span,
&format!(
"unexpected explicit self type in operator method: {:?}",
method_ty.explicit_self));
}
}
}
}
let callee = MethodCallee {
origin: MethodTypeParam(MethodParam{trait_ref: trait_ref.clone(),
method_num: method_num,
impl_def_id: None}),
ty: fty,
substs: trait_ref.substs.clone()
};
debug!("callee = {}", callee.repr(fcx.tcx()));
Some(callee)
}
pub fn resolve_ufcs<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_name: ast::Name,
self_ty: Ty<'tcx>,
expr_id: ast::NodeId)
-> Result<(def::Def, LastPrivate), MethodError>
{
let mode = probe::Mode::Path;
let pick = try!(probe::probe(fcx, span, mode, method_name, self_ty, expr_id));
let def_id = pick.method_ty.def_id;
let mut lp = LastMod(AllPublic);
let provenance = match pick.kind {
probe::InherentImplPick(impl_def_id) => {
if pick.method_ty.vis!= ast::Public {
lp = LastMod(DependsOn(def_id));
}
def::FromImpl(impl_def_id)
}
_ => def::FromTrait(pick.method_ty.container.id())
};
Ok((def::DefMethod(def_id, provenance), lp))
}
/// Find method with name `method_name` defined in `trait_def_id` and return it, along with its
/// index (or `None`, if no such method).
fn trait_method<'tcx>(tcx: &ty::ctxt<'tcx>,
trait_def_id: ast::DefId,
method_name: ast::Name)
-> Option<(uint, Rc<ty::Method<'tcx>>)>
{
let trait_items = ty::trait_items(tcx, trait_def_id);
trait_items
.iter()
.enumerate()
.find(|&(_, ref item)| item.name() == method_name)
.and_then(|(idx, item)| item.as_opt_method().map(|m| (idx, m)))
}
fn impl_method<'tcx>(tcx: &ty::ctxt<'tcx>,
impl_def_id: ast::DefId,
method_name: ast::Name)
-> Option<Rc<ty::Method<'tcx>>>
{
let impl_items = tcx.impl_items.borrow();
let impl_items = impl_items.get(&impl_def_id).unwrap();
impl_items
.iter()
.map(|&did| ty::impl_or_trait_item(tcx, did.def_id()))
.find(|m| m.name() == method_name)
.and_then(|item| item.as_opt_method())
} | {
let mode = probe::Mode::MethodCall;
match probe::probe(fcx, span, mode, method_name, self_ty, call_expr_id) { | random_line_split |
prewitt.rs | use rgb::*;
use imgref::*;
use loop9::{Triple,loop9};
pub trait ToGray {
fn to_gray(self) -> i16;
}
impl ToGray for RGBA8 {
fn to_gray(self) -> i16 {
self.rgb().to_gray()
}
}
impl ToGray for RGB8 {
fn to_gray(self) -> i16 {
let px = self.map(|c| c as i16);
px.r + px.g + px.g + px.b
}
}
pub fn prewitt_squared_img<T: ToGray + Copy>(input: ImgRef<'_, T>) -> ImgVec<u16> {
let gray: Vec<_> = input.pixels().map(|px|px.to_gray()).collect();
let gray = Img::new(gray, input.width(), input.height());
let mut prew = Vec::with_capacity(gray.width() * gray.height()); | }
#[inline]
pub fn prewitt_squared3<T: Into<i16>>(top: Triple<T>, mid: Triple<T>, bot: Triple<T>) -> u16 {
prewitt_squared(top.prev, top.curr, top.next, mid.prev, mid.next, bot.prev, bot.curr, bot.next)
}
#[inline]
pub fn prewitt_squared<T: Into<i16>>(top_prev: T, top_curr: T, top_next: T, mid_prev: T, mid_next: T, bot_prev: T, bot_curr: T, bot_next: T) -> u16 {
let top_prev = top_prev.into();
let top_curr = top_curr.into();
let top_next = top_next.into();
let mid_prev = mid_prev.into();
let mid_next = mid_next.into();
let bot_prev = bot_prev.into();
let bot_curr = bot_curr.into();
let bot_next = bot_next.into();
let gx = (
top_next - top_prev +
mid_next - mid_prev +
bot_next - bot_prev) as i32;
let gy = (
bot_prev + bot_curr + bot_next -
top_prev - top_curr - top_next) as i32;
((gx*gx + gy*gy) / 256) as u16
} | loop9(gray.as_ref(), 0,0, gray.width(), gray.height(), |_x,_y,top,mid,bot|{
prew.push(prewitt_squared3(top, mid, bot));
});
ImgVec::new(prew, gray.width(), gray.height()) | random_line_split |
prewitt.rs | use rgb::*;
use imgref::*;
use loop9::{Triple,loop9};
pub trait ToGray {
fn to_gray(self) -> i16;
}
impl ToGray for RGBA8 {
fn to_gray(self) -> i16 {
self.rgb().to_gray()
}
}
impl ToGray for RGB8 {
fn | (self) -> i16 {
let px = self.map(|c| c as i16);
px.r + px.g + px.g + px.b
}
}
pub fn prewitt_squared_img<T: ToGray + Copy>(input: ImgRef<'_, T>) -> ImgVec<u16> {
let gray: Vec<_> = input.pixels().map(|px|px.to_gray()).collect();
let gray = Img::new(gray, input.width(), input.height());
let mut prew = Vec::with_capacity(gray.width() * gray.height());
loop9(gray.as_ref(), 0,0, gray.width(), gray.height(), |_x,_y,top,mid,bot|{
prew.push(prewitt_squared3(top, mid, bot));
});
ImgVec::new(prew, gray.width(), gray.height())
}
#[inline]
pub fn prewitt_squared3<T: Into<i16>>(top: Triple<T>, mid: Triple<T>, bot: Triple<T>) -> u16 {
prewitt_squared(top.prev, top.curr, top.next, mid.prev, mid.next, bot.prev, bot.curr, bot.next)
}
#[inline]
pub fn prewitt_squared<T: Into<i16>>(top_prev: T, top_curr: T, top_next: T, mid_prev: T, mid_next: T, bot_prev: T, bot_curr: T, bot_next: T) -> u16 {
let top_prev = top_prev.into();
let top_curr = top_curr.into();
let top_next = top_next.into();
let mid_prev = mid_prev.into();
let mid_next = mid_next.into();
let bot_prev = bot_prev.into();
let bot_curr = bot_curr.into();
let bot_next = bot_next.into();
let gx = (
top_next - top_prev +
mid_next - mid_prev +
bot_next - bot_prev) as i32;
let gy = (
bot_prev + bot_curr + bot_next -
top_prev - top_curr - top_next) as i32;
((gx*gx + gy*gy) / 256) as u16
}
| to_gray | identifier_name |
prewitt.rs | use rgb::*;
use imgref::*;
use loop9::{Triple,loop9};
pub trait ToGray {
fn to_gray(self) -> i16;
}
impl ToGray for RGBA8 {
fn to_gray(self) -> i16 {
self.rgb().to_gray()
}
}
impl ToGray for RGB8 {
fn to_gray(self) -> i16 {
let px = self.map(|c| c as i16);
px.r + px.g + px.g + px.b
}
}
pub fn prewitt_squared_img<T: ToGray + Copy>(input: ImgRef<'_, T>) -> ImgVec<u16> {
let gray: Vec<_> = input.pixels().map(|px|px.to_gray()).collect();
let gray = Img::new(gray, input.width(), input.height());
let mut prew = Vec::with_capacity(gray.width() * gray.height());
loop9(gray.as_ref(), 0,0, gray.width(), gray.height(), |_x,_y,top,mid,bot|{
prew.push(prewitt_squared3(top, mid, bot));
});
ImgVec::new(prew, gray.width(), gray.height())
}
#[inline]
pub fn prewitt_squared3<T: Into<i16>>(top: Triple<T>, mid: Triple<T>, bot: Triple<T>) -> u16 |
#[inline]
pub fn prewitt_squared<T: Into<i16>>(top_prev: T, top_curr: T, top_next: T, mid_prev: T, mid_next: T, bot_prev: T, bot_curr: T, bot_next: T) -> u16 {
let top_prev = top_prev.into();
let top_curr = top_curr.into();
let top_next = top_next.into();
let mid_prev = mid_prev.into();
let mid_next = mid_next.into();
let bot_prev = bot_prev.into();
let bot_curr = bot_curr.into();
let bot_next = bot_next.into();
let gx = (
top_next - top_prev +
mid_next - mid_prev +
bot_next - bot_prev) as i32;
let gy = (
bot_prev + bot_curr + bot_next -
top_prev - top_curr - top_next) as i32;
((gx*gx + gy*gy) / 256) as u16
}
| {
prewitt_squared(top.prev, top.curr, top.next, mid.prev, mid.next, bot.prev, bot.curr, bot.next)
} | identifier_body |
snmp-decode.rs | extern crate asn1_cereal;
extern crate argparse;
extern crate serde;
extern crate serde_json;
use asn1_cereal::{tag, byte};
use asn1_cereal::ber::stream;
// SNMP ASN.1 Definition
// https://tools.ietf.org/html/rfc1157#page-30
type ObjectIdentifier = u64;
type NetworkAddress = u64;
type ObjectName = String;
struct Message {
version: i32,
community: String,
data: PDUs,
}
enum PDUs {
get_request(GetRequest),
get_next_request(GetNextRequest),
get_response(GetResponse),
set_request(SetRequest),
trap(TrapPDU),
}
|
struct GetNextRequest(PDU);
struct GetResponse(PDU);
struct SetRequest(PDU);
struct PDU {
request_id: i32,
error_status: i32,
error_index: i32,
variable_bindings: VarBindList,
}
struct TrapPDU {
enterprise: ObjectIdentifier,
agent_addr: NetworkAddress,
generic_trap: i32,
specific_trap: i32,
time_stamp: TimeTicks,
variable_bindings: VarBindList,
}
struct VarBind {
name: ObjectName,
value: ObjectSyntax,
}
type VarBindList = Vec<VarBind>;
use std::io;
use std::io::Read;
use std::fs;
use std::path::Path;
use std::collections::BTreeMap;
use argparse::{ArgumentParser, StoreTrue, StoreOption};
use serde_json::value::Value;
use serde_json::ser::to_string_pretty;
fn main() {
let opts = parse_args();
let path = Path::new(opts.file.as_ref().unwrap());
if!path.is_file() {
panic!("Supplied file does not exist");
}
// Create a buffered reader from the file.
let reader = io::BufReader::new(fs::File::open(path).unwrap()).bytes();
}
struct ProgOpts {
file: Option<String>,
verbose: bool,
}
fn parse_args() -> ProgOpts {
let mut opts = ProgOpts {
file: None,
verbose: false,
};
{
let mut ap = ArgumentParser::new();
ap.set_description("Decode ASN.1 files");
ap.refer(&mut opts.verbose)
.add_option(&["-v", "--verbose"], StoreTrue, "Verbose output");
ap.refer(&mut opts.file)
.add_argument("file", StoreOption, "ASN.1 file to decode");
ap.parse_args_or_exit();
}
opts
} | struct GetRequest(PDU); | random_line_split |
snmp-decode.rs | extern crate asn1_cereal;
extern crate argparse;
extern crate serde;
extern crate serde_json;
use asn1_cereal::{tag, byte};
use asn1_cereal::ber::stream;
// SNMP ASN.1 Definition
// https://tools.ietf.org/html/rfc1157#page-30
type ObjectIdentifier = u64;
type NetworkAddress = u64;
type ObjectName = String;
struct Message {
version: i32,
community: String,
data: PDUs,
}
enum PDUs {
get_request(GetRequest),
get_next_request(GetNextRequest),
get_response(GetResponse),
set_request(SetRequest),
trap(TrapPDU),
}
struct GetRequest(PDU);
struct GetNextRequest(PDU);
struct GetResponse(PDU);
struct SetRequest(PDU);
struct PDU {
request_id: i32,
error_status: i32,
error_index: i32,
variable_bindings: VarBindList,
}
struct TrapPDU {
enterprise: ObjectIdentifier,
agent_addr: NetworkAddress,
generic_trap: i32,
specific_trap: i32,
time_stamp: TimeTicks,
variable_bindings: VarBindList,
}
struct VarBind {
name: ObjectName,
value: ObjectSyntax,
}
type VarBindList = Vec<VarBind>;
use std::io;
use std::io::Read;
use std::fs;
use std::path::Path;
use std::collections::BTreeMap;
use argparse::{ArgumentParser, StoreTrue, StoreOption};
use serde_json::value::Value;
use serde_json::ser::to_string_pretty;
fn main() {
let opts = parse_args();
let path = Path::new(opts.file.as_ref().unwrap());
if!path.is_file() |
// Create a buffered reader from the file.
let reader = io::BufReader::new(fs::File::open(path).unwrap()).bytes();
}
struct ProgOpts {
file: Option<String>,
verbose: bool,
}
fn parse_args() -> ProgOpts {
let mut opts = ProgOpts {
file: None,
verbose: false,
};
{
let mut ap = ArgumentParser::new();
ap.set_description("Decode ASN.1 files");
ap.refer(&mut opts.verbose)
.add_option(&["-v", "--verbose"], StoreTrue, "Verbose output");
ap.refer(&mut opts.file)
.add_argument("file", StoreOption, "ASN.1 file to decode");
ap.parse_args_or_exit();
}
opts
}
| {
panic!("Supplied file does not exist");
} | conditional_block |
snmp-decode.rs | extern crate asn1_cereal;
extern crate argparse;
extern crate serde;
extern crate serde_json;
use asn1_cereal::{tag, byte};
use asn1_cereal::ber::stream;
// SNMP ASN.1 Definition
// https://tools.ietf.org/html/rfc1157#page-30
type ObjectIdentifier = u64;
type NetworkAddress = u64;
type ObjectName = String;
struct Message {
version: i32,
community: String,
data: PDUs,
}
enum PDUs {
get_request(GetRequest),
get_next_request(GetNextRequest),
get_response(GetResponse),
set_request(SetRequest),
trap(TrapPDU),
}
struct GetRequest(PDU);
struct GetNextRequest(PDU);
struct | (PDU);
struct SetRequest(PDU);
struct PDU {
request_id: i32,
error_status: i32,
error_index: i32,
variable_bindings: VarBindList,
}
struct TrapPDU {
enterprise: ObjectIdentifier,
agent_addr: NetworkAddress,
generic_trap: i32,
specific_trap: i32,
time_stamp: TimeTicks,
variable_bindings: VarBindList,
}
struct VarBind {
name: ObjectName,
value: ObjectSyntax,
}
type VarBindList = Vec<VarBind>;
use std::io;
use std::io::Read;
use std::fs;
use std::path::Path;
use std::collections::BTreeMap;
use argparse::{ArgumentParser, StoreTrue, StoreOption};
use serde_json::value::Value;
use serde_json::ser::to_string_pretty;
fn main() {
let opts = parse_args();
let path = Path::new(opts.file.as_ref().unwrap());
if!path.is_file() {
panic!("Supplied file does not exist");
}
// Create a buffered reader from the file.
let reader = io::BufReader::new(fs::File::open(path).unwrap()).bytes();
}
struct ProgOpts {
file: Option<String>,
verbose: bool,
}
fn parse_args() -> ProgOpts {
let mut opts = ProgOpts {
file: None,
verbose: false,
};
{
let mut ap = ArgumentParser::new();
ap.set_description("Decode ASN.1 files");
ap.refer(&mut opts.verbose)
.add_option(&["-v", "--verbose"], StoreTrue, "Verbose output");
ap.refer(&mut opts.file)
.add_argument("file", StoreOption, "ASN.1 file to decode");
ap.parse_args_or_exit();
}
opts
}
| GetResponse | identifier_name |
edit_role.rs | use std::collections::HashMap;
use bytes::buf::Buf;
use reqwest::Url;
use tokio::{fs::File, io::AsyncReadExt};
use crate::http::{AttachmentType, Http};
use crate::internal::prelude::*;
use crate::model::{guild::Role, Permissions};
/// A builder to create or edit a [`Role`] for use via a number of model methods.
///
/// These are:
///
/// - [`PartialGuild::create_role`]
/// - [`Guild::create_role`]
/// - [`Guild::edit_role`]
/// - [`GuildId::create_role`]
/// - [`GuildId::edit_role`]
/// - [`Role::edit`]
///
/// Defaults are provided for each parameter on role creation.
///
/// # Examples
///
/// Create a hoisted, mentionable role named `"a test role"`:
///
/// ```rust,no_run
/// # use serenity::{model::id::{ChannelId, GuildId}, http::Http};
/// # use std::sync::Arc;
/// #
/// # let http = Arc::new(Http::default());
/// # let (channel_id, guild_id) = (ChannelId(1), GuildId(2));
/// #
/// // assuming a `channel_id` and `guild_id` has been bound
///
/// let role = guild_id.create_role(&http, |r| r.hoist(true).mentionable(true).name("a test role"));
/// ```
///
/// [`PartialGuild::create_role`]: crate::model::guild::PartialGuild::create_role
/// [`Guild::create_role`]: crate::model::guild::Guild::create_role
/// [`Guild::edit_role`]: crate::model::guild::Guild::edit_role
/// [`GuildId::create_role`]: crate::model::id::GuildId::create_role
/// [`GuildId::edit_role`]: crate::model::id::GuildId::edit_role
#[derive(Clone, Debug, Default)]
pub struct EditRole(pub HashMap<&'static str, Value>);
impl EditRole {
/// Creates a new builder with the values of the given [`Role`].
pub fn new(role: &Role) -> Self {
let mut map = HashMap::with_capacity(9);
#[cfg(feature = "utils")]
{
map.insert("color", Value::Number(Number::from(role.colour.0)));
}
#[cfg(not(feature = "utils"))]
{
map.insert("color", Value::Number(Number::from(role.colour)));
}
map.insert("hoist", Value::Bool(role.hoist));
map.insert("managed", Value::Bool(role.managed));
map.insert("mentionable", Value::Bool(role.mentionable));
map.insert("name", Value::String(role.name.clone()));
map.insert("permissions", Value::Number(Number::from(role.permissions.bits())));
map.insert("position", Value::Number(Number::from(role.position)));
if let Some(unicode_emoji) = &role.unicode_emoji {
map.insert("unicode_emoji", Value::String(unicode_emoji.clone()));
}
if let Some(icon) = &role.icon {
map.insert("icon", Value::String(icon.clone()));
}
EditRole(map)
}
/// Sets the colour of the role.
pub fn colour(&mut self, colour: u64) -> &mut Self {
self.0.insert("color", Value::Number(Number::from(colour)));
self
}
/// Whether or not to hoist the role above lower-positioned role in the user
/// list.
pub fn hoist(&mut self, hoist: bool) -> &mut Self {
self.0.insert("hoist", Value::Bool(hoist));
self
}
/// Whether or not to make the role mentionable, notifying its users.
pub fn mentionable(&mut self, mentionable: bool) -> &mut Self {
self.0.insert("mentionable", Value::Bool(mentionable));
self
}
/// The name of the role to set.
pub fn name<S: ToString>(&mut self, name: S) -> &mut Self {
self.0.insert("name", Value::String(name.to_string()));
self
}
/// The set of permissions to assign the role.
pub fn permissions(&mut self, permissions: Permissions) -> &mut Self {
self.0.insert("permissions", Value::Number(Number::from(permissions.bits())));
self
}
/// The position to assign the role in the role list. This correlates to the
/// role's position in the user list.
pub fn | (&mut self, position: u8) -> &mut Self {
self.0.insert("position", Value::Number(Number::from(position)));
self
}
/// The unicode emoji to set as the role image.
pub fn unicode_emoji<S: ToString>(&mut self, unicode_emoji: S) -> &mut Self {
self.0.remove("icon");
self.0.insert("unicode_emoji", Value::String(unicode_emoji.to_string()));
self
}
/// The image to set as the role icon.
///
/// # Errors
///
/// May error if the icon is a URL and the HTTP request fails, or if the icon is a file
/// on a path that doesn't exist.
pub async fn icon<'a>(
&mut self,
http: impl AsRef<Http>,
icon: impl Into<AttachmentType<'a>>,
) -> Result<&mut Self> {
let icon = match icon.into() {
AttachmentType::Bytes {
data,
filename: _,
} => "data:image/png;base64,".to_string() + &base64::encode(&data.into_owned()),
AttachmentType::File {
file,
filename: _,
} => {
let mut buf = Vec::new();
file.try_clone().await?.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Path(path) => {
let mut file = File::open(path).await?;
let mut buf = vec![];
file.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Image(url) => {
let url = Url::parse(url).map_err(|_| Error::Url(url.to_string()))?;
let response = http.as_ref().client.get(url).send().await?;
let mut bytes = response.bytes().await?;
let mut picture: Vec<u8> = vec![0; bytes.len()];
bytes.copy_to_slice(&mut picture[..]);
"data:image/png;base64,".to_string() + &base64::encode(&picture)
},
};
self.0.remove("unicode_emoji");
self.0.insert("icon", Value::String(icon));
Ok(self)
}
}
| position | identifier_name |
edit_role.rs | use std::collections::HashMap;
use bytes::buf::Buf;
use reqwest::Url;
use tokio::{fs::File, io::AsyncReadExt};
use crate::http::{AttachmentType, Http};
use crate::internal::prelude::*;
use crate::model::{guild::Role, Permissions};
/// A builder to create or edit a [`Role`] for use via a number of model methods.
///
/// These are:
///
/// - [`PartialGuild::create_role`]
/// - [`Guild::create_role`]
/// - [`Guild::edit_role`]
/// - [`GuildId::create_role`]
/// - [`GuildId::edit_role`]
/// - [`Role::edit`]
///
/// Defaults are provided for each parameter on role creation.
///
/// # Examples
///
/// Create a hoisted, mentionable role named `"a test role"`:
///
/// ```rust,no_run
/// # use serenity::{model::id::{ChannelId, GuildId}, http::Http};
/// # use std::sync::Arc;
/// #
/// # let http = Arc::new(Http::default());
/// # let (channel_id, guild_id) = (ChannelId(1), GuildId(2));
/// #
/// // assuming a `channel_id` and `guild_id` has been bound
///
/// let role = guild_id.create_role(&http, |r| r.hoist(true).mentionable(true).name("a test role"));
/// ```
///
/// [`PartialGuild::create_role`]: crate::model::guild::PartialGuild::create_role
/// [`Guild::create_role`]: crate::model::guild::Guild::create_role
/// [`Guild::edit_role`]: crate::model::guild::Guild::edit_role
/// [`GuildId::create_role`]: crate::model::id::GuildId::create_role
/// [`GuildId::edit_role`]: crate::model::id::GuildId::edit_role
#[derive(Clone, Debug, Default)]
pub struct EditRole(pub HashMap<&'static str, Value>);
impl EditRole {
/// Creates a new builder with the values of the given [`Role`].
pub fn new(role: &Role) -> Self {
let mut map = HashMap::with_capacity(9);
#[cfg(feature = "utils")]
{
map.insert("color", Value::Number(Number::from(role.colour.0)));
}
#[cfg(not(feature = "utils"))]
{
map.insert("color", Value::Number(Number::from(role.colour)));
}
map.insert("hoist", Value::Bool(role.hoist));
map.insert("managed", Value::Bool(role.managed));
map.insert("mentionable", Value::Bool(role.mentionable));
map.insert("name", Value::String(role.name.clone()));
map.insert("permissions", Value::Number(Number::from(role.permissions.bits())));
map.insert("position", Value::Number(Number::from(role.position)));
if let Some(unicode_emoji) = &role.unicode_emoji {
map.insert("unicode_emoji", Value::String(unicode_emoji.clone()));
}
if let Some(icon) = &role.icon |
EditRole(map)
}
/// Sets the colour of the role.
pub fn colour(&mut self, colour: u64) -> &mut Self {
self.0.insert("color", Value::Number(Number::from(colour)));
self
}
/// Whether or not to hoist the role above lower-positioned role in the user
/// list.
pub fn hoist(&mut self, hoist: bool) -> &mut Self {
self.0.insert("hoist", Value::Bool(hoist));
self
}
/// Whether or not to make the role mentionable, notifying its users.
pub fn mentionable(&mut self, mentionable: bool) -> &mut Self {
self.0.insert("mentionable", Value::Bool(mentionable));
self
}
/// The name of the role to set.
pub fn name<S: ToString>(&mut self, name: S) -> &mut Self {
self.0.insert("name", Value::String(name.to_string()));
self
}
/// The set of permissions to assign the role.
pub fn permissions(&mut self, permissions: Permissions) -> &mut Self {
self.0.insert("permissions", Value::Number(Number::from(permissions.bits())));
self
}
/// The position to assign the role in the role list. This correlates to the
/// role's position in the user list.
pub fn position(&mut self, position: u8) -> &mut Self {
self.0.insert("position", Value::Number(Number::from(position)));
self
}
/// The unicode emoji to set as the role image.
pub fn unicode_emoji<S: ToString>(&mut self, unicode_emoji: S) -> &mut Self {
self.0.remove("icon");
self.0.insert("unicode_emoji", Value::String(unicode_emoji.to_string()));
self
}
/// The image to set as the role icon.
///
/// # Errors
///
/// May error if the icon is a URL and the HTTP request fails, or if the icon is a file
/// on a path that doesn't exist.
pub async fn icon<'a>(
&mut self,
http: impl AsRef<Http>,
icon: impl Into<AttachmentType<'a>>,
) -> Result<&mut Self> {
let icon = match icon.into() {
AttachmentType::Bytes {
data,
filename: _,
} => "data:image/png;base64,".to_string() + &base64::encode(&data.into_owned()),
AttachmentType::File {
file,
filename: _,
} => {
let mut buf = Vec::new();
file.try_clone().await?.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Path(path) => {
let mut file = File::open(path).await?;
let mut buf = vec![];
file.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Image(url) => {
let url = Url::parse(url).map_err(|_| Error::Url(url.to_string()))?;
let response = http.as_ref().client.get(url).send().await?;
let mut bytes = response.bytes().await?;
let mut picture: Vec<u8> = vec![0; bytes.len()];
bytes.copy_to_slice(&mut picture[..]);
"data:image/png;base64,".to_string() + &base64::encode(&picture)
},
};
self.0.remove("unicode_emoji");
self.0.insert("icon", Value::String(icon));
Ok(self)
}
}
| {
map.insert("icon", Value::String(icon.clone()));
} | conditional_block |
edit_role.rs | use std::collections::HashMap;
use bytes::buf::Buf;
use reqwest::Url;
use tokio::{fs::File, io::AsyncReadExt};
use crate::http::{AttachmentType, Http};
use crate::internal::prelude::*;
use crate::model::{guild::Role, Permissions};
/// A builder to create or edit a [`Role`] for use via a number of model methods.
///
/// These are:
///
/// - [`PartialGuild::create_role`]
/// - [`Guild::create_role`]
/// - [`Guild::edit_role`]
/// - [`GuildId::create_role`]
/// - [`GuildId::edit_role`]
/// - [`Role::edit`]
///
/// Defaults are provided for each parameter on role creation.
///
/// # Examples
///
/// Create a hoisted, mentionable role named `"a test role"`:
///
/// ```rust,no_run
/// # use serenity::{model::id::{ChannelId, GuildId}, http::Http};
/// # use std::sync::Arc;
/// #
/// # let http = Arc::new(Http::default());
/// # let (channel_id, guild_id) = (ChannelId(1), GuildId(2));
/// #
/// // assuming a `channel_id` and `guild_id` has been bound
///
/// let role = guild_id.create_role(&http, |r| r.hoist(true).mentionable(true).name("a test role"));
/// ```
///
/// [`PartialGuild::create_role`]: crate::model::guild::PartialGuild::create_role
/// [`Guild::create_role`]: crate::model::guild::Guild::create_role
/// [`Guild::edit_role`]: crate::model::guild::Guild::edit_role
/// [`GuildId::create_role`]: crate::model::id::GuildId::create_role
/// [`GuildId::edit_role`]: crate::model::id::GuildId::edit_role
#[derive(Clone, Debug, Default)]
pub struct EditRole(pub HashMap<&'static str, Value>);
impl EditRole {
/// Creates a new builder with the values of the given [`Role`].
pub fn new(role: &Role) -> Self {
let mut map = HashMap::with_capacity(9);
#[cfg(feature = "utils")]
{
map.insert("color", Value::Number(Number::from(role.colour.0)));
}
#[cfg(not(feature = "utils"))]
{
map.insert("color", Value::Number(Number::from(role.colour)));
}
map.insert("hoist", Value::Bool(role.hoist));
map.insert("managed", Value::Bool(role.managed));
map.insert("mentionable", Value::Bool(role.mentionable));
map.insert("name", Value::String(role.name.clone()));
map.insert("permissions", Value::Number(Number::from(role.permissions.bits())));
map.insert("position", Value::Number(Number::from(role.position)));
if let Some(unicode_emoji) = &role.unicode_emoji {
map.insert("unicode_emoji", Value::String(unicode_emoji.clone()));
}
if let Some(icon) = &role.icon {
map.insert("icon", Value::String(icon.clone()));
}
EditRole(map)
}
/// Sets the colour of the role.
pub fn colour(&mut self, colour: u64) -> &mut Self {
self.0.insert("color", Value::Number(Number::from(colour)));
self
}
/// Whether or not to hoist the role above lower-positioned role in the user
/// list.
pub fn hoist(&mut self, hoist: bool) -> &mut Self {
self.0.insert("hoist", Value::Bool(hoist));
self
}
/// Whether or not to make the role mentionable, notifying its users.
pub fn mentionable(&mut self, mentionable: bool) -> &mut Self {
self.0.insert("mentionable", Value::Bool(mentionable));
self
}
/// The name of the role to set.
pub fn name<S: ToString>(&mut self, name: S) -> &mut Self |
/// The set of permissions to assign the role.
pub fn permissions(&mut self, permissions: Permissions) -> &mut Self {
self.0.insert("permissions", Value::Number(Number::from(permissions.bits())));
self
}
/// The position to assign the role in the role list. This correlates to the
/// role's position in the user list.
pub fn position(&mut self, position: u8) -> &mut Self {
self.0.insert("position", Value::Number(Number::from(position)));
self
}
/// The unicode emoji to set as the role image.
pub fn unicode_emoji<S: ToString>(&mut self, unicode_emoji: S) -> &mut Self {
self.0.remove("icon");
self.0.insert("unicode_emoji", Value::String(unicode_emoji.to_string()));
self
}
/// The image to set as the role icon.
///
/// # Errors
///
/// May error if the icon is a URL and the HTTP request fails, or if the icon is a file
/// on a path that doesn't exist.
pub async fn icon<'a>(
&mut self,
http: impl AsRef<Http>,
icon: impl Into<AttachmentType<'a>>,
) -> Result<&mut Self> {
let icon = match icon.into() {
AttachmentType::Bytes {
data,
filename: _,
} => "data:image/png;base64,".to_string() + &base64::encode(&data.into_owned()),
AttachmentType::File {
file,
filename: _,
} => {
let mut buf = Vec::new();
file.try_clone().await?.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Path(path) => {
let mut file = File::open(path).await?;
let mut buf = vec![];
file.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Image(url) => {
let url = Url::parse(url).map_err(|_| Error::Url(url.to_string()))?;
let response = http.as_ref().client.get(url).send().await?;
let mut bytes = response.bytes().await?;
let mut picture: Vec<u8> = vec![0; bytes.len()];
bytes.copy_to_slice(&mut picture[..]);
"data:image/png;base64,".to_string() + &base64::encode(&picture)
},
};
self.0.remove("unicode_emoji");
self.0.insert("icon", Value::String(icon));
Ok(self)
}
}
| {
self.0.insert("name", Value::String(name.to_string()));
self
} | identifier_body |
edit_role.rs | use std::collections::HashMap;
use bytes::buf::Buf;
use reqwest::Url;
use tokio::{fs::File, io::AsyncReadExt};
use crate::http::{AttachmentType, Http};
use crate::internal::prelude::*;
use crate::model::{guild::Role, Permissions};
/// A builder to create or edit a [`Role`] for use via a number of model methods.
///
/// These are:
///
/// - [`PartialGuild::create_role`]
/// - [`Guild::create_role`]
/// - [`Guild::edit_role`]
/// - [`GuildId::create_role`]
/// - [`GuildId::edit_role`]
/// - [`Role::edit`]
///
/// Defaults are provided for each parameter on role creation.
///
/// # Examples
///
/// Create a hoisted, mentionable role named `"a test role"`:
///
/// ```rust,no_run
/// # use serenity::{model::id::{ChannelId, GuildId}, http::Http};
/// # use std::sync::Arc;
/// #
/// # let http = Arc::new(Http::default());
/// # let (channel_id, guild_id) = (ChannelId(1), GuildId(2));
/// #
/// // assuming a `channel_id` and `guild_id` has been bound
///
/// let role = guild_id.create_role(&http, |r| r.hoist(true).mentionable(true).name("a test role"));
/// ```
///
/// [`PartialGuild::create_role`]: crate::model::guild::PartialGuild::create_role
/// [`Guild::create_role`]: crate::model::guild::Guild::create_role
/// [`Guild::edit_role`]: crate::model::guild::Guild::edit_role
/// [`GuildId::create_role`]: crate::model::id::GuildId::create_role
/// [`GuildId::edit_role`]: crate::model::id::GuildId::edit_role
#[derive(Clone, Debug, Default)]
pub struct EditRole(pub HashMap<&'static str, Value>);
impl EditRole {
/// Creates a new builder with the values of the given [`Role`].
pub fn new(role: &Role) -> Self {
let mut map = HashMap::with_capacity(9);
#[cfg(feature = "utils")]
{
map.insert("color", Value::Number(Number::from(role.colour.0)));
}
#[cfg(not(feature = "utils"))]
{
map.insert("color", Value::Number(Number::from(role.colour)));
}
map.insert("hoist", Value::Bool(role.hoist));
map.insert("managed", Value::Bool(role.managed));
map.insert("mentionable", Value::Bool(role.mentionable));
map.insert("name", Value::String(role.name.clone()));
map.insert("permissions", Value::Number(Number::from(role.permissions.bits())));
map.insert("position", Value::Number(Number::from(role.position)));
if let Some(unicode_emoji) = &role.unicode_emoji {
map.insert("unicode_emoji", Value::String(unicode_emoji.clone()));
}
if let Some(icon) = &role.icon {
map.insert("icon", Value::String(icon.clone()));
}
EditRole(map)
}
/// Sets the colour of the role.
pub fn colour(&mut self, colour: u64) -> &mut Self {
self.0.insert("color", Value::Number(Number::from(colour)));
self
}
/// Whether or not to hoist the role above lower-positioned role in the user
/// list.
pub fn hoist(&mut self, hoist: bool) -> &mut Self {
self.0.insert("hoist", Value::Bool(hoist));
self
}
/// Whether or not to make the role mentionable, notifying its users.
pub fn mentionable(&mut self, mentionable: bool) -> &mut Self {
self.0.insert("mentionable", Value::Bool(mentionable));
self
}
/// The name of the role to set.
pub fn name<S: ToString>(&mut self, name: S) -> &mut Self {
self.0.insert("name", Value::String(name.to_string()));
self
} | self.0.insert("permissions", Value::Number(Number::from(permissions.bits())));
self
}
/// The position to assign the role in the role list. This correlates to the
/// role's position in the user list.
pub fn position(&mut self, position: u8) -> &mut Self {
self.0.insert("position", Value::Number(Number::from(position)));
self
}
/// The unicode emoji to set as the role image.
pub fn unicode_emoji<S: ToString>(&mut self, unicode_emoji: S) -> &mut Self {
self.0.remove("icon");
self.0.insert("unicode_emoji", Value::String(unicode_emoji.to_string()));
self
}
/// The image to set as the role icon.
///
/// # Errors
///
/// May error if the icon is a URL and the HTTP request fails, or if the icon is a file
/// on a path that doesn't exist.
pub async fn icon<'a>(
&mut self,
http: impl AsRef<Http>,
icon: impl Into<AttachmentType<'a>>,
) -> Result<&mut Self> {
let icon = match icon.into() {
AttachmentType::Bytes {
data,
filename: _,
} => "data:image/png;base64,".to_string() + &base64::encode(&data.into_owned()),
AttachmentType::File {
file,
filename: _,
} => {
let mut buf = Vec::new();
file.try_clone().await?.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Path(path) => {
let mut file = File::open(path).await?;
let mut buf = vec![];
file.read_to_end(&mut buf).await?;
"data:image/png;base64,".to_string() + &base64::encode(&buf)
},
AttachmentType::Image(url) => {
let url = Url::parse(url).map_err(|_| Error::Url(url.to_string()))?;
let response = http.as_ref().client.get(url).send().await?;
let mut bytes = response.bytes().await?;
let mut picture: Vec<u8> = vec![0; bytes.len()];
bytes.copy_to_slice(&mut picture[..]);
"data:image/png;base64,".to_string() + &base64::encode(&picture)
},
};
self.0.remove("unicode_emoji");
self.0.insert("icon", Value::String(icon));
Ok(self)
}
} |
/// The set of permissions to assign the role.
pub fn permissions(&mut self, permissions: Permissions) -> &mut Self { | random_line_split |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
pub use self::builder::BlockFlowDisplayListBuilding;
pub use self::builder::BorderPaintingMode;
pub use self::builder::DisplayListBuildState;
pub use self::builder::FlexFlowDisplayListBuilding;
pub use self::builder::IndexableText;
pub use self::builder::InlineFlowDisplayListBuilding;
pub use self::builder::ListItemFlowDisplayListBuilding; | mod background;
mod builder;
mod conversions;
pub mod items;
mod webrender_helpers; | pub use self::builder::StackingContextCollectionFlags;
pub use self::builder::StackingContextCollectionState;
pub use self::conversions::ToLayout;
pub use self::webrender_helpers::WebRenderDisplayListConverter;
| random_line_split |
font_face.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(missing_docs)]
#[cfg(feature = "gecko")]
use computed_values::{font_style, font_weight, font_stretch};
use computed_values::font_family::FamilyName;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
#[cfg(feature = "gecko")] use cssparser::UnicodeRange;
use parser::{ParserContext, log_css_error, Parse};
use std::fmt;
use std::iter;
use style_traits::{ToCss, OneOrMoreCommaSeparated};
use values::specified::url::SpecifiedUrl;
/// A source for a font-face rule.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub enum Source {
/// A `url()` source.
Url(UrlSource),
/// A `local()` source.
Local(FamilyName),
}
impl ToCss for Source {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
Source::Url(ref url) => {
try!(dest.write_str("url(\""));
try!(url.to_css(dest));
},
Source::Local(ref family) => {
try!(dest.write_str("local(\""));
try!(family.to_css(dest));
},
}
dest.write_str("\")")
}
}
impl OneOrMoreCommaSeparated for Source {}
/// A `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// https://drafts.csswg.org/css-fonts/#src-desc
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct UrlSource {
/// The specified url.
pub url: SpecifiedUrl,
/// The format hints specified with the `format()` function.
pub format_hints: Vec<String>,
}
impl ToCss for UrlSource {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str(self.url.as_str())
}
}
/// Parse the block inside a `@font-face` rule.
///
/// Note that the prelude parsing code lives in the `stylesheets` module.
pub fn parse_font_face_block(context: &ParserContext, input: &mut Parser)
-> Result<FontFaceRule, ()> {
let mut rule = FontFaceRule::initial();
{
let parser = FontFaceRuleParser {
context: context,
rule: &mut rule,
missing: MissingDescriptors::new(),
};
let mut iter = DeclarationListParser::new(input, parser);
while let Some(declaration) = iter.next() {
if let Err(range) = declaration {
let pos = range.start;
let message = format!("Unsupported @font-face descriptor declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, context);
}
}
if iter.parser.missing.any() {
return Err(())
}
}
Ok(rule)
}
/// A list of effective sources that we send over through IPC to the font cache.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct EffectiveSources(Vec<Source>);
impl FontFaceRule {
/// Returns the list of effective sources for that font-face, that is the
/// sources which don't list any format hint, or the ones which list at
/// least "truetype" or "opentype".
pub fn effective_sources(&self) -> EffectiveSources {
EffectiveSources(self.sources.iter().rev().filter(|source| {
if let Source::Url(ref url_source) = **source | else {
true
}
}).cloned().collect())
}
}
impl iter::Iterator for EffectiveSources {
type Item = Source;
fn next(&mut self) -> Option<Source> {
self.0.pop()
}
}
struct FontFaceRuleParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
rule: &'a mut FontFaceRule,
missing: MissingDescriptors,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for FontFaceRuleParser<'a, 'b> {
type Prelude = ();
type AtRule = ();
}
impl Parse for Source {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Source, ()> {
if input.try(|input| input.expect_function_matching("local")).is_ok() {
return input.parse_nested_block(|input| {
FamilyName::parse(context, input)
}).map(Source::Local)
}
let url = SpecifiedUrl::parse(context, input)?;
// Parsing optional format()
let format_hints = if input.try(|input| input.expect_function_matching("format")).is_ok() {
input.parse_nested_block(|input| {
input.parse_comma_separated(|input| {
Ok(input.expect_string()?.into_owned())
})
})?
} else {
vec![]
};
Ok(Source::Url(UrlSource {
url: url,
format_hints: format_hints,
}))
}
}
macro_rules! font_face_descriptors {
(
mandatory descriptors = [
$( #[$m_doc: meta] $m_name: tt $m_ident: ident: $m_ty: ty = $m_initial: expr, )*
]
optional descriptors = [
$( #[$o_doc: meta] $o_name: tt $o_ident: ident: $o_ty: ty = $o_initial: expr, )*
]
) => {
/// A `@font-face` rule.
///
/// https://drafts.csswg.org/css-fonts/#font-face-rule
#[derive(Debug, PartialEq, Eq)]
pub struct FontFaceRule {
$(
#[$m_doc]
pub $m_ident: $m_ty,
)*
$(
#[$o_doc]
pub $o_ident: $o_ty,
)*
}
struct MissingDescriptors {
$(
$m_ident: bool,
)*
}
impl MissingDescriptors {
fn new() -> Self {
MissingDescriptors {
$(
$m_ident: true,
)*
}
}
fn any(&self) -> bool {
$(
self.$m_ident
)||*
}
}
impl FontFaceRule {
fn initial() -> Self {
FontFaceRule {
$(
$m_ident: $m_initial,
)*
$(
$o_ident: $o_initial,
)*
}
}
}
impl ToCss for FontFaceRule {
// Serialization of FontFaceRule is not specced.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@font-face {\n")?;
$(
dest.write_str(concat!(" ", $m_name, ": "))?;
ToCss::to_css(&self.$m_ident, dest)?;
dest.write_str(";\n")?;
)*
$(
// Because of parse_font_face_block,
// this condition is always true for "src" and "font-family".
// But it can be false for other descriptors.
if self.$o_ident!= $o_initial {
dest.write_str(concat!(" ", $o_name, ": "))?;
ToCss::to_css(&self.$o_ident, dest)?;
dest.write_str(";\n")?;
}
)*
dest.write_str("}")
}
}
impl<'a, 'b> DeclarationParser for FontFaceRuleParser<'a, 'b> {
type Declaration = ();
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> {
match_ignore_ascii_case! { name,
$(
$m_name => {
self.rule.$m_ident = Parse::parse(self.context, input)?;
self.missing.$m_ident = false
},
)*
$(
$o_name => self.rule.$o_ident = Parse::parse(self.context, input)?,
)*
_ => return Err(())
}
Ok(())
}
}
}
}
/// css-name rust_identifier: Type = initial_value,
#[cfg(feature = "gecko")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
/// The style of this font face
"font-style" style: font_style::T = font_style::T::normal,
/// The weight of this font face
"font-weight" weight: font_weight::T = font_weight::T::Weight400 /* normal */,
/// The stretch of this font face
"font-stretch" stretch: font_stretch::T = font_stretch::T::normal,
/// The ranges of code points outside of which this font face should not be used.
"unicode-range" unicode_range: Vec<UnicodeRange> = vec![
UnicodeRange { start: 0, end: 0x10FFFF }
],
]
}
#[cfg(feature = "servo")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
]
}
| {
let hints = &url_source.format_hints;
// We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be
// downloaded in case we support them.
hints.is_empty() || hints.iter().any(|hint| {
hint == "truetype" || hint == "opentype" || hint == "woff"
})
} | conditional_block |
font_face.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(missing_docs)]
#[cfg(feature = "gecko")]
use computed_values::{font_style, font_weight, font_stretch};
use computed_values::font_family::FamilyName;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
#[cfg(feature = "gecko")] use cssparser::UnicodeRange;
use parser::{ParserContext, log_css_error, Parse};
use std::fmt;
use std::iter;
use style_traits::{ToCss, OneOrMoreCommaSeparated};
use values::specified::url::SpecifiedUrl;
/// A source for a font-face rule.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub enum Source {
/// A `url()` source.
Url(UrlSource),
/// A `local()` source.
Local(FamilyName),
}
impl ToCss for Source {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
Source::Url(ref url) => {
try!(dest.write_str("url(\""));
try!(url.to_css(dest));
},
Source::Local(ref family) => {
try!(dest.write_str("local(\""));
try!(family.to_css(dest));
},
}
dest.write_str("\")")
}
}
impl OneOrMoreCommaSeparated for Source {}
/// A `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// https://drafts.csswg.org/css-fonts/#src-desc
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct | {
/// The specified url.
pub url: SpecifiedUrl,
/// The format hints specified with the `format()` function.
pub format_hints: Vec<String>,
}
impl ToCss for UrlSource {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str(self.url.as_str())
}
}
/// Parse the block inside a `@font-face` rule.
///
/// Note that the prelude parsing code lives in the `stylesheets` module.
pub fn parse_font_face_block(context: &ParserContext, input: &mut Parser)
-> Result<FontFaceRule, ()> {
let mut rule = FontFaceRule::initial();
{
let parser = FontFaceRuleParser {
context: context,
rule: &mut rule,
missing: MissingDescriptors::new(),
};
let mut iter = DeclarationListParser::new(input, parser);
while let Some(declaration) = iter.next() {
if let Err(range) = declaration {
let pos = range.start;
let message = format!("Unsupported @font-face descriptor declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, context);
}
}
if iter.parser.missing.any() {
return Err(())
}
}
Ok(rule)
}
/// A list of effective sources that we send over through IPC to the font cache.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct EffectiveSources(Vec<Source>);
impl FontFaceRule {
/// Returns the list of effective sources for that font-face, that is the
/// sources which don't list any format hint, or the ones which list at
/// least "truetype" or "opentype".
pub fn effective_sources(&self) -> EffectiveSources {
EffectiveSources(self.sources.iter().rev().filter(|source| {
if let Source::Url(ref url_source) = **source {
let hints = &url_source.format_hints;
// We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be
// downloaded in case we support them.
hints.is_empty() || hints.iter().any(|hint| {
hint == "truetype" || hint == "opentype" || hint == "woff"
})
} else {
true
}
}).cloned().collect())
}
}
impl iter::Iterator for EffectiveSources {
type Item = Source;
fn next(&mut self) -> Option<Source> {
self.0.pop()
}
}
struct FontFaceRuleParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
rule: &'a mut FontFaceRule,
missing: MissingDescriptors,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for FontFaceRuleParser<'a, 'b> {
type Prelude = ();
type AtRule = ();
}
impl Parse for Source {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Source, ()> {
if input.try(|input| input.expect_function_matching("local")).is_ok() {
return input.parse_nested_block(|input| {
FamilyName::parse(context, input)
}).map(Source::Local)
}
let url = SpecifiedUrl::parse(context, input)?;
// Parsing optional format()
let format_hints = if input.try(|input| input.expect_function_matching("format")).is_ok() {
input.parse_nested_block(|input| {
input.parse_comma_separated(|input| {
Ok(input.expect_string()?.into_owned())
})
})?
} else {
vec![]
};
Ok(Source::Url(UrlSource {
url: url,
format_hints: format_hints,
}))
}
}
macro_rules! font_face_descriptors {
(
mandatory descriptors = [
$( #[$m_doc: meta] $m_name: tt $m_ident: ident: $m_ty: ty = $m_initial: expr, )*
]
optional descriptors = [
$( #[$o_doc: meta] $o_name: tt $o_ident: ident: $o_ty: ty = $o_initial: expr, )*
]
) => {
/// A `@font-face` rule.
///
/// https://drafts.csswg.org/css-fonts/#font-face-rule
#[derive(Debug, PartialEq, Eq)]
pub struct FontFaceRule {
$(
#[$m_doc]
pub $m_ident: $m_ty,
)*
$(
#[$o_doc]
pub $o_ident: $o_ty,
)*
}
struct MissingDescriptors {
$(
$m_ident: bool,
)*
}
impl MissingDescriptors {
fn new() -> Self {
MissingDescriptors {
$(
$m_ident: true,
)*
}
}
fn any(&self) -> bool {
$(
self.$m_ident
)||*
}
}
impl FontFaceRule {
fn initial() -> Self {
FontFaceRule {
$(
$m_ident: $m_initial,
)*
$(
$o_ident: $o_initial,
)*
}
}
}
impl ToCss for FontFaceRule {
// Serialization of FontFaceRule is not specced.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@font-face {\n")?;
$(
dest.write_str(concat!(" ", $m_name, ": "))?;
ToCss::to_css(&self.$m_ident, dest)?;
dest.write_str(";\n")?;
)*
$(
// Because of parse_font_face_block,
// this condition is always true for "src" and "font-family".
// But it can be false for other descriptors.
if self.$o_ident!= $o_initial {
dest.write_str(concat!(" ", $o_name, ": "))?;
ToCss::to_css(&self.$o_ident, dest)?;
dest.write_str(";\n")?;
}
)*
dest.write_str("}")
}
}
impl<'a, 'b> DeclarationParser for FontFaceRuleParser<'a, 'b> {
type Declaration = ();
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> {
match_ignore_ascii_case! { name,
$(
$m_name => {
self.rule.$m_ident = Parse::parse(self.context, input)?;
self.missing.$m_ident = false
},
)*
$(
$o_name => self.rule.$o_ident = Parse::parse(self.context, input)?,
)*
_ => return Err(())
}
Ok(())
}
}
}
}
/// css-name rust_identifier: Type = initial_value,
#[cfg(feature = "gecko")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
/// The style of this font face
"font-style" style: font_style::T = font_style::T::normal,
/// The weight of this font face
"font-weight" weight: font_weight::T = font_weight::T::Weight400 /* normal */,
/// The stretch of this font face
"font-stretch" stretch: font_stretch::T = font_stretch::T::normal,
/// The ranges of code points outside of which this font face should not be used.
"unicode-range" unicode_range: Vec<UnicodeRange> = vec![
UnicodeRange { start: 0, end: 0x10FFFF }
],
]
}
#[cfg(feature = "servo")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
]
}
| UrlSource | identifier_name |
font_face.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(missing_docs)]
#[cfg(feature = "gecko")]
use computed_values::{font_style, font_weight, font_stretch};
use computed_values::font_family::FamilyName;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
#[cfg(feature = "gecko")] use cssparser::UnicodeRange;
use parser::{ParserContext, log_css_error, Parse};
use std::fmt;
use std::iter;
use style_traits::{ToCss, OneOrMoreCommaSeparated};
use values::specified::url::SpecifiedUrl;
/// A source for a font-face rule.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub enum Source {
/// A `url()` source.
Url(UrlSource),
/// A `local()` source.
Local(FamilyName),
}
impl ToCss for Source {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
Source::Url(ref url) => {
try!(dest.write_str("url(\""));
try!(url.to_css(dest));
},
Source::Local(ref family) => {
try!(dest.write_str("local(\""));
try!(family.to_css(dest));
},
}
dest.write_str("\")")
}
}
impl OneOrMoreCommaSeparated for Source {}
/// A `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// https://drafts.csswg.org/css-fonts/#src-desc
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct UrlSource {
/// The specified url.
pub url: SpecifiedUrl,
/// The format hints specified with the `format()` function.
pub format_hints: Vec<String>,
}
impl ToCss for UrlSource {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str(self.url.as_str())
}
}
/// Parse the block inside a `@font-face` rule.
///
/// Note that the prelude parsing code lives in the `stylesheets` module.
pub fn parse_font_face_block(context: &ParserContext, input: &mut Parser)
-> Result<FontFaceRule, ()> {
let mut rule = FontFaceRule::initial();
{
let parser = FontFaceRuleParser {
context: context,
rule: &mut rule,
missing: MissingDescriptors::new(),
};
let mut iter = DeclarationListParser::new(input, parser);
while let Some(declaration) = iter.next() {
if let Err(range) = declaration {
let pos = range.start;
let message = format!("Unsupported @font-face descriptor declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, context);
}
}
if iter.parser.missing.any() {
return Err(())
}
}
Ok(rule)
}
/// A list of effective sources that we send over through IPC to the font cache.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct EffectiveSources(Vec<Source>);
impl FontFaceRule {
/// Returns the list of effective sources for that font-face, that is the
/// sources which don't list any format hint, or the ones which list at
/// least "truetype" or "opentype".
pub fn effective_sources(&self) -> EffectiveSources {
EffectiveSources(self.sources.iter().rev().filter(|source| {
if let Source::Url(ref url_source) = **source {
let hints = &url_source.format_hints;
// We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be
// downloaded in case we support them.
hints.is_empty() || hints.iter().any(|hint| {
hint == "truetype" || hint == "opentype" || hint == "woff"
})
} else {
true
}
}).cloned().collect())
}
}
impl iter::Iterator for EffectiveSources {
type Item = Source;
fn next(&mut self) -> Option<Source> {
self.0.pop()
}
}
struct FontFaceRuleParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
rule: &'a mut FontFaceRule,
missing: MissingDescriptors,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for FontFaceRuleParser<'a, 'b> {
type Prelude = ();
type AtRule = ();
}
impl Parse for Source {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Source, ()> | Ok(Source::Url(UrlSource {
url: url,
format_hints: format_hints,
}))
}
}
macro_rules! font_face_descriptors {
(
mandatory descriptors = [
$( #[$m_doc: meta] $m_name: tt $m_ident: ident: $m_ty: ty = $m_initial: expr, )*
]
optional descriptors = [
$( #[$o_doc: meta] $o_name: tt $o_ident: ident: $o_ty: ty = $o_initial: expr, )*
]
) => {
/// A `@font-face` rule.
///
/// https://drafts.csswg.org/css-fonts/#font-face-rule
#[derive(Debug, PartialEq, Eq)]
pub struct FontFaceRule {
$(
#[$m_doc]
pub $m_ident: $m_ty,
)*
$(
#[$o_doc]
pub $o_ident: $o_ty,
)*
}
struct MissingDescriptors {
$(
$m_ident: bool,
)*
}
impl MissingDescriptors {
fn new() -> Self {
MissingDescriptors {
$(
$m_ident: true,
)*
}
}
fn any(&self) -> bool {
$(
self.$m_ident
)||*
}
}
impl FontFaceRule {
fn initial() -> Self {
FontFaceRule {
$(
$m_ident: $m_initial,
)*
$(
$o_ident: $o_initial,
)*
}
}
}
impl ToCss for FontFaceRule {
// Serialization of FontFaceRule is not specced.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@font-face {\n")?;
$(
dest.write_str(concat!(" ", $m_name, ": "))?;
ToCss::to_css(&self.$m_ident, dest)?;
dest.write_str(";\n")?;
)*
$(
// Because of parse_font_face_block,
// this condition is always true for "src" and "font-family".
// But it can be false for other descriptors.
if self.$o_ident!= $o_initial {
dest.write_str(concat!(" ", $o_name, ": "))?;
ToCss::to_css(&self.$o_ident, dest)?;
dest.write_str(";\n")?;
}
)*
dest.write_str("}")
}
}
impl<'a, 'b> DeclarationParser for FontFaceRuleParser<'a, 'b> {
type Declaration = ();
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> {
match_ignore_ascii_case! { name,
$(
$m_name => {
self.rule.$m_ident = Parse::parse(self.context, input)?;
self.missing.$m_ident = false
},
)*
$(
$o_name => self.rule.$o_ident = Parse::parse(self.context, input)?,
)*
_ => return Err(())
}
Ok(())
}
}
}
}
/// css-name rust_identifier: Type = initial_value,
#[cfg(feature = "gecko")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
/// The style of this font face
"font-style" style: font_style::T = font_style::T::normal,
/// The weight of this font face
"font-weight" weight: font_weight::T = font_weight::T::Weight400 /* normal */,
/// The stretch of this font face
"font-stretch" stretch: font_stretch::T = font_stretch::T::normal,
/// The ranges of code points outside of which this font face should not be used.
"unicode-range" unicode_range: Vec<UnicodeRange> = vec![
UnicodeRange { start: 0, end: 0x10FFFF }
],
]
}
#[cfg(feature = "servo")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
]
}
| {
if input.try(|input| input.expect_function_matching("local")).is_ok() {
return input.parse_nested_block(|input| {
FamilyName::parse(context, input)
}).map(Source::Local)
}
let url = SpecifiedUrl::parse(context, input)?;
// Parsing optional format()
let format_hints = if input.try(|input| input.expect_function_matching("format")).is_ok() {
input.parse_nested_block(|input| {
input.parse_comma_separated(|input| {
Ok(input.expect_string()?.into_owned())
})
})?
} else {
vec![]
};
| identifier_body |
font_face.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(missing_docs)]
#[cfg(feature = "gecko")]
use computed_values::{font_style, font_weight, font_stretch};
use computed_values::font_family::FamilyName;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
#[cfg(feature = "gecko")] use cssparser::UnicodeRange;
use parser::{ParserContext, log_css_error, Parse};
use std::fmt;
use std::iter;
use style_traits::{ToCss, OneOrMoreCommaSeparated};
use values::specified::url::SpecifiedUrl;
/// A source for a font-face rule.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub enum Source {
/// A `url()` source.
Url(UrlSource),
/// A `local()` source.
Local(FamilyName),
}
impl ToCss for Source {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
Source::Url(ref url) => {
try!(dest.write_str("url(\""));
try!(url.to_css(dest));
},
Source::Local(ref family) => {
try!(dest.write_str("local(\""));
try!(family.to_css(dest));
},
}
dest.write_str("\")")
}
}
impl OneOrMoreCommaSeparated for Source {}
/// A `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// https://drafts.csswg.org/css-fonts/#src-desc
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct UrlSource {
/// The specified url.
pub url: SpecifiedUrl,
/// The format hints specified with the `format()` function.
pub format_hints: Vec<String>,
}
impl ToCss for UrlSource {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str(self.url.as_str())
}
}
/// Parse the block inside a `@font-face` rule.
///
/// Note that the prelude parsing code lives in the `stylesheets` module.
pub fn parse_font_face_block(context: &ParserContext, input: &mut Parser)
-> Result<FontFaceRule, ()> {
let mut rule = FontFaceRule::initial();
{
let parser = FontFaceRuleParser {
context: context,
rule: &mut rule,
missing: MissingDescriptors::new(),
};
let mut iter = DeclarationListParser::new(input, parser);
while let Some(declaration) = iter.next() {
if let Err(range) = declaration {
let pos = range.start;
let message = format!("Unsupported @font-face descriptor declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, context);
}
}
if iter.parser.missing.any() {
return Err(())
}
}
Ok(rule)
}
/// A list of effective sources that we send over through IPC to the font cache.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct EffectiveSources(Vec<Source>);
impl FontFaceRule {
/// Returns the list of effective sources for that font-face, that is the
/// sources which don't list any format hint, or the ones which list at
/// least "truetype" or "opentype".
pub fn effective_sources(&self) -> EffectiveSources {
EffectiveSources(self.sources.iter().rev().filter(|source| {
if let Source::Url(ref url_source) = **source {
let hints = &url_source.format_hints;
// We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be
// downloaded in case we support them.
hints.is_empty() || hints.iter().any(|hint| {
hint == "truetype" || hint == "opentype" || hint == "woff"
})
} else {
true
}
}).cloned().collect())
}
}
impl iter::Iterator for EffectiveSources {
type Item = Source;
fn next(&mut self) -> Option<Source> {
self.0.pop()
}
}
struct FontFaceRuleParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
rule: &'a mut FontFaceRule,
missing: MissingDescriptors,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for FontFaceRuleParser<'a, 'b> {
type Prelude = ();
type AtRule = ();
}
impl Parse for Source {
fn parse(context: &ParserContext, input: &mut Parser) -> Result<Source, ()> {
if input.try(|input| input.expect_function_matching("local")).is_ok() {
return input.parse_nested_block(|input| {
FamilyName::parse(context, input)
}).map(Source::Local)
}
let url = SpecifiedUrl::parse(context, input)?;
// Parsing optional format()
let format_hints = if input.try(|input| input.expect_function_matching("format")).is_ok() {
input.parse_nested_block(|input| {
input.parse_comma_separated(|input| {
Ok(input.expect_string()?.into_owned())
})
})?
} else {
vec![]
};
Ok(Source::Url(UrlSource {
url: url,
format_hints: format_hints,
}))
}
}
macro_rules! font_face_descriptors {
(
mandatory descriptors = [
$( #[$m_doc: meta] $m_name: tt $m_ident: ident: $m_ty: ty = $m_initial: expr, )*
]
optional descriptors = [
$( #[$o_doc: meta] $o_name: tt $o_ident: ident: $o_ty: ty = $o_initial: expr, )*
]
) => {
/// A `@font-face` rule.
///
/// https://drafts.csswg.org/css-fonts/#font-face-rule
#[derive(Debug, PartialEq, Eq)]
pub struct FontFaceRule {
$(
#[$m_doc]
pub $m_ident: $m_ty,
)*
$(
#[$o_doc]
pub $o_ident: $o_ty,
)*
}
struct MissingDescriptors {
$(
$m_ident: bool,
)*
}
impl MissingDescriptors {
fn new() -> Self {
MissingDescriptors {
$(
$m_ident: true,
)*
}
}
fn any(&self) -> bool {
$( | }
}
impl FontFaceRule {
fn initial() -> Self {
FontFaceRule {
$(
$m_ident: $m_initial,
)*
$(
$o_ident: $o_initial,
)*
}
}
}
impl ToCss for FontFaceRule {
// Serialization of FontFaceRule is not specced.
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@font-face {\n")?;
$(
dest.write_str(concat!(" ", $m_name, ": "))?;
ToCss::to_css(&self.$m_ident, dest)?;
dest.write_str(";\n")?;
)*
$(
// Because of parse_font_face_block,
// this condition is always true for "src" and "font-family".
// But it can be false for other descriptors.
if self.$o_ident!= $o_initial {
dest.write_str(concat!(" ", $o_name, ": "))?;
ToCss::to_css(&self.$o_ident, dest)?;
dest.write_str(";\n")?;
}
)*
dest.write_str("}")
}
}
impl<'a, 'b> DeclarationParser for FontFaceRuleParser<'a, 'b> {
type Declaration = ();
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> {
match_ignore_ascii_case! { name,
$(
$m_name => {
self.rule.$m_ident = Parse::parse(self.context, input)?;
self.missing.$m_ident = false
},
)*
$(
$o_name => self.rule.$o_ident = Parse::parse(self.context, input)?,
)*
_ => return Err(())
}
Ok(())
}
}
}
}
/// css-name rust_identifier: Type = initial_value,
#[cfg(feature = "gecko")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
/// The style of this font face
"font-style" style: font_style::T = font_style::T::normal,
/// The weight of this font face
"font-weight" weight: font_weight::T = font_weight::T::Weight400 /* normal */,
/// The stretch of this font face
"font-stretch" stretch: font_stretch::T = font_stretch::T::normal,
/// The ranges of code points outside of which this font face should not be used.
"unicode-range" unicode_range: Vec<UnicodeRange> = vec![
UnicodeRange { start: 0, end: 0x10FFFF }
],
]
}
#[cfg(feature = "servo")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family: FamilyName = FamilyName(atom!("")),
/// The alternative sources for this font face.
"src" sources: Vec<Source> = Vec::new(),
]
optional descriptors = [
]
} | self.$m_ident
)||* | random_line_split |
intersection.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate aabb_quadtree;
extern crate map_model;
use aabb_quadtree::geom::Rect;
use ezgui::canvas::GfxCtx;
use geom::geometry;
use graphics;
use graphics::math::Vec2d;
use graphics::types::Color;
use map_model::{Bounds, IntersectionID, Map};
use render::DrawRoad;
use std::f64;
#[derive(Debug)]
pub struct | {
pub id: IntersectionID,
pub point: Vec2d,
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
for r in &map.get_roads_to_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons.last().unwrap()[2]);
pts.push(dr.polygons.last().unwrap()[3]);
}
for r in &map.get_roads_from_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons[0][0]);
pts.push(dr.polygons[0][1]);
}
let center = geometry::gps_to_screen_space(&inter.point, bounds);
// Sort points by angle from the center
pts.sort_by_key(|pt| {
let mut angle = (pt[1] - center.y()).atan2(pt[0] - center.x()).to_degrees();
if angle < 0.0 {
angle += 360.0;
}
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly = graphics::Polygon::new(color);
poly.draw(&self.polygon, &g.ctx.draw_state, g.ctx.transform, g.gfx);
}
pub fn contains_pt(&self, x: f64, y: f64) -> bool {
geometry::point_in_polygon(x, y, &self.polygon)
}
pub fn get_bbox(&self) -> Rect {
geometry::get_bbox_for_polygons(&[self.polygon.clone()])
}
}
| DrawIntersection | identifier_name |
intersection.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate aabb_quadtree;
extern crate map_model;
use aabb_quadtree::geom::Rect;
use ezgui::canvas::GfxCtx;
use geom::geometry;
use graphics;
use graphics::math::Vec2d;
use graphics::types::Color;
use map_model::{Bounds, IntersectionID, Map};
use render::DrawRoad;
use std::f64;
#[derive(Debug)]
pub struct DrawIntersection {
pub id: IntersectionID, |
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
for r in &map.get_roads_to_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons.last().unwrap()[2]);
pts.push(dr.polygons.last().unwrap()[3]);
}
for r in &map.get_roads_from_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons[0][0]);
pts.push(dr.polygons[0][1]);
}
let center = geometry::gps_to_screen_space(&inter.point, bounds);
// Sort points by angle from the center
pts.sort_by_key(|pt| {
let mut angle = (pt[1] - center.y()).atan2(pt[0] - center.x()).to_degrees();
if angle < 0.0 {
angle += 360.0;
}
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly = graphics::Polygon::new(color);
poly.draw(&self.polygon, &g.ctx.draw_state, g.ctx.transform, g.gfx);
}
pub fn contains_pt(&self, x: f64, y: f64) -> bool {
geometry::point_in_polygon(x, y, &self.polygon)
}
pub fn get_bbox(&self) -> Rect {
geometry::get_bbox_for_polygons(&[self.polygon.clone()])
}
} | pub point: Vec2d, | random_line_split |
intersection.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate aabb_quadtree;
extern crate map_model;
use aabb_quadtree::geom::Rect;
use ezgui::canvas::GfxCtx;
use geom::geometry;
use graphics;
use graphics::math::Vec2d;
use graphics::types::Color;
use map_model::{Bounds, IntersectionID, Map};
use render::DrawRoad;
use std::f64;
#[derive(Debug)]
pub struct DrawIntersection {
pub id: IntersectionID,
pub point: Vec2d,
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
for r in &map.get_roads_to_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons.last().unwrap()[2]);
pts.push(dr.polygons.last().unwrap()[3]);
}
for r in &map.get_roads_from_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons[0][0]);
pts.push(dr.polygons[0][1]);
}
let center = geometry::gps_to_screen_space(&inter.point, bounds);
// Sort points by angle from the center
pts.sort_by_key(|pt| {
let mut angle = (pt[1] - center.y()).atan2(pt[0] - center.x()).to_degrees();
if angle < 0.0 |
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly = graphics::Polygon::new(color);
poly.draw(&self.polygon, &g.ctx.draw_state, g.ctx.transform, g.gfx);
}
pub fn contains_pt(&self, x: f64, y: f64) -> bool {
geometry::point_in_polygon(x, y, &self.polygon)
}
pub fn get_bbox(&self) -> Rect {
geometry::get_bbox_for_polygons(&[self.polygon.clone()])
}
}
| {
angle += 360.0;
} | conditional_block |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1; | let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn serve_partial(video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
} | response.set_header(ContentLength(content_len));
response.set_header(content_range); | random_line_split |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range | else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn serve_partial(video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(content_range);
let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} | conditional_block |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> | if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(content_range);
let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn serve_partial(video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => { | identifier_body |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(content_range);
let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn | (video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| serve_partial | identifier_name |
s3.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::PhantomData;
use futures_util::{
future::FutureExt,
io::{AsyncRead, AsyncReadExt},
stream::TryStreamExt,
};
use rusoto_core::{
request::DispatchSignedRequest,
{ByteStream, RusotoError},
};
use rusoto_s3::*;
use rusoto_util::new_client;
use super::{
util::{block_on_external_io, error_stream, retry, RetryError},
ExternalStorage,
};
use kvproto::backup::S3 as Config;
/// S3 compatible storage
#[derive(Clone)]
pub struct S3Storage {
config: Config,
client: S3Client,
// The current implementation (rosoto 0.43.0 + hyper 0.13.3) is not `Send`
// in practical. See more https://github.com/tikv/tikv/issues/7236.
// FIXME: remove it.
_not_send: PhantomData<*const ()>,
}
impl S3Storage {
/// Create a new S3 storage for the given config.
pub fn new(config: &Config) -> io::Result<S3Storage> {
Self::check_config(config)?;
let client = new_client!(S3Client, config);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
pub fn with_request_dispatcher<D>(config: &Config, dispatcher: D) -> io::Result<S3Storage>
where
D: DispatchSignedRequest + Send + Sync +'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::Result<()> {
if config.bucket.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"missing bucket name",
));
}
Ok(())
}
fn maybe_prefix_key(&self, key: &str) -> String {
if!self.config.prefix.is_empty() {
return format!("{}/{}", self.config.prefix, key);
}
key.to_owned()
}
}
impl<E> RetryError for RusotoError<E> {
fn placeholder() -> Self {
Self::Blocking
}
fn is_retryable(&self) -> bool {
match self {
Self::HttpDispatch(_) => true,
Self::Unknown(resp) if resp.status.is_server_error() => true,
// FIXME: Retry NOT_READY & THROTTLED (403).
_ => false,
}
}
}
/// A helper for uploading a large files to S3 storage.
///
/// Note: this uploader does not support uploading files larger than 19.5 GiB.
struct S3Uploader<'client> {
client: &'client S3Client,
bucket: String,
key: String,
acl: Option<String>,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader with a given target location and upload configuration.
fn new(client: &'client S3Client, config: &Config, key: String) -> Self {
fn get_var(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
}
Self {
client,
bucket: config.bucket.clone(),
key,
acl: get_var(&config.acl),
server_side_encryption: get_var(&config.sse),
ssekms_key_id: get_var(&config.sse_kms_key_id),
storage_class: get_var(&config.storage_class),
upload_id: "".to_owned(),
parts: Vec::new(),
}
}
/// Executes the upload process.
async fn run(
mut self,
reader: &mut (dyn AsyncRead + Unpin),
est_len: u64,
) -> Result<(), Box<dyn std::error::Error>> {
if est_len <= MINIMUM_PART_SIZE as u64 {
// For short files, execute one put_object to upload the entire thing.
let mut data = Vec::with_capacity(est_len as usize);
reader.read_to_end(&mut data).await?;
retry(|| self.upload(&data)).await?;
Ok(())
} else {
// Otherwise, use multipart upload to improve robustness.
self.upload_id = retry(|| self.begin()).await?;
let upload_res = async {
let mut buf = vec![0; MINIMUM_PART_SIZE];
let mut part_number = 1;
loop {
let data_size = reader.read(&mut buf).await?;
if data_size == 0 {
break;
}
let part = retry(|| self.upload_part(part_number, &buf[..data_size])).await?;
self.parts.push(part);
part_number += 1;
}
Ok(())
}
.await;
if upload_res.is_ok() {
retry(|| self.complete()).await?;
} else {
let _ = retry(|| self.abort()).await;
}
upload_res
}
}
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
..Default::default()
})
.await?;
output.upload_id.ok_or_else(|| {
RusotoError::ParseError("missing upload-id from create_multipart_upload()".to_owned())
})
}
/// Completes a multipart upload process, asking S3 to join all parts into a single file.
async fn complete(&self) -> Result<(), RusotoError<CompleteMultipartUploadError>> {
self.client
.complete_multipart_upload(CompleteMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(self.parts.clone()),
}),
..Default::default()
})
.await?;
Ok(())
}
/// Aborts the multipart upload process, deletes all uploaded parts.
async fn abort(&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default()
})
.await?;
Ok(())
}
/// Uploads a part of the file.
///
/// The `part_number` must be between 1 to 10000.
async fn upload_part(
&self,
part_number: i64,
data: &[u8],
) -> Result<CompletedPart, RusotoError<UploadPartError>> {
let part = self
.client
.upload_part(UploadPartRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
part_number,
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(CompletedPart {
e_tag: part.e_tag,
part_number: Some(part_number),
})
}
/// Uploads a file atomically.
///
/// This should be used only when the data is known to be short, and thus relatively cheap to
/// retry the entire upload.
async fn upload(&self, data: &[u8]) -> Result<(), RusotoError<PutObjectError>> {
self.client
.put_object(PutObjectRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(())
}
}
impl ExternalStorage for S3Storage {
fn write(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
let key = self.maybe_prefix_key(name);
debug!("save file to s3 storage"; "key" => %key);
let uploader = S3Uploader::new(&self.client, &self.config, key);
block_on_external_io(uploader.run(&mut *reader, content_length)).map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("failed to put object {}", e))
})
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let key = self.maybe_prefix_key(name);
let bucket = self.config.bucket.clone();
debug!("read file from s3 storage"; "key" => %key);
let req = GetObjectRequest {
key,
bucket: bucket.clone(),
..Default::default()
};
Box::new(
self.client
.get_object(req)
.map(move |future| match future {
Ok(out) => out.body.unwrap(),
Err(RusotoError::Service(GetObjectError::NoSuchKey(key))) => {
ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::NotFound,
format!("no key {} at bucket {}", key, bucket),
)))
}
Err(e) => ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::Other,
format!("failed to get object {}", e),
))),
})
.flatten_stream()
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::io::AsyncReadExt;
use rusoto_core::signature::SignedRequest;
use rusoto_mock::MockRequestDispatcher;
#[test]
fn test_s3_config() {
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let cases = vec![
// bucket is empty
Config {
bucket: "".to_owned(),
..config.clone()
},
];
for case in cases {
let r = S3Storage::new(&case);
assert!(r.is_err());
}
assert!(S3Storage::new(&config).is_ok());
}
#[test]
fn test_s3_storage() | "mykey",
Box::new(magic_contents.as_bytes()),
magic_contents.len() as u64,
)
.unwrap();
let mut reader = s.read("mykey");
let mut buf = Vec::new();
let ret = block_on_external_io(reader.read_to_end(&mut buf));
assert!(ret.unwrap() == 0);
assert!(buf.is_empty());
}
#[test]
#[cfg(FALSE)]
// FIXME: enable this (or move this to an integration test) if we've got a
// reliable way to test s3 (rusoto_mock requires custom logic to verify the
// body stream which itself can have bug)
fn test_real_s3_storage() {
use std::f64::INFINITY;
use tikv_util::time::Limiter;
let mut s3 = Config::default();
s3.set_endpoint("http://127.0.0.1:9000".to_owned());
s3.set_bucket("bucket".to_owned());
s3.set_prefix("prefix".to_owned());
s3.set_access_key("93QZ01QRBYQQXC37XHZV".to_owned());
s3.set_secret_access_key("N2VcI4Emg0Nm7fDzGBMJvguHHUxLGpjfwt2y4+vJ".to_owned());
s3.set_force_path_style(true);
let limiter = Limiter::new(INFINITY);
let storage = S3Storage::new(&s3).unwrap();
const LEN: usize = 1024 * 1024 * 4;
static CONTENT: [u8; LEN] = [50_u8; LEN];
storage
.write(
"huge_file",
Box::new(limiter.limit(&CONTENT[..])),
LEN as u64,
)
.unwrap();
let mut reader = storage.read("huge_file");
let mut buf = Vec::new();
block_on_external_io(reader.read_to_end(&mut buf)).unwrap();
assert_eq!(buf.len(), LEN);
assert_eq!(buf.iter().position(|b| *b!= 50_u8), None);
}
}
| {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let dispatcher = MockRequestDispatcher::with_status(200).with_request_checker(
move |req: &SignedRequest| {
assert_eq!(req.region.name(), "ap-southeast-2");
assert_eq!(req.path(), "/mybucket/myprefix/mykey");
// PutObject is translated to HTTP PUT.
assert_eq!(req.payload.is_some(), req.method() == "PUT");
},
);
let s = S3Storage::with_request_dispatcher(&config, dispatcher).unwrap();
s.write( | identifier_body |
s3.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::PhantomData;
use futures_util::{
future::FutureExt,
io::{AsyncRead, AsyncReadExt},
stream::TryStreamExt,
};
use rusoto_core::{
request::DispatchSignedRequest,
{ByteStream, RusotoError},
};
use rusoto_s3::*;
use rusoto_util::new_client;
use super::{
util::{block_on_external_io, error_stream, retry, RetryError},
ExternalStorage,
};
use kvproto::backup::S3 as Config;
/// S3 compatible storage
#[derive(Clone)]
pub struct S3Storage {
config: Config,
client: S3Client,
// The current implementation (rosoto 0.43.0 + hyper 0.13.3) is not `Send`
// in practical. See more https://github.com/tikv/tikv/issues/7236.
// FIXME: remove it.
_not_send: PhantomData<*const ()>,
}
impl S3Storage {
/// Create a new S3 storage for the given config.
pub fn new(config: &Config) -> io::Result<S3Storage> {
Self::check_config(config)?;
let client = new_client!(S3Client, config);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
pub fn with_request_dispatcher<D>(config: &Config, dispatcher: D) -> io::Result<S3Storage>
where
D: DispatchSignedRequest + Send + Sync +'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::Result<()> {
if config.bucket.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"missing bucket name",
));
}
Ok(())
}
fn maybe_prefix_key(&self, key: &str) -> String {
if!self.config.prefix.is_empty() {
return format!("{}/{}", self.config.prefix, key);
}
key.to_owned()
}
}
impl<E> RetryError for RusotoError<E> {
fn placeholder() -> Self {
Self::Blocking
}
fn is_retryable(&self) -> bool {
match self {
Self::HttpDispatch(_) => true,
Self::Unknown(resp) if resp.status.is_server_error() => true,
// FIXME: Retry NOT_READY & THROTTLED (403).
_ => false,
}
}
}
/// A helper for uploading a large files to S3 storage.
///
/// Note: this uploader does not support uploading files larger than 19.5 GiB.
struct S3Uploader<'client> {
client: &'client S3Client,
bucket: String,
key: String,
acl: Option<String>,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader with a given target location and upload configuration.
fn new(client: &'client S3Client, config: &Config, key: String) -> Self {
fn get_var(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
}
Self {
client,
bucket: config.bucket.clone(),
key,
acl: get_var(&config.acl),
server_side_encryption: get_var(&config.sse),
ssekms_key_id: get_var(&config.sse_kms_key_id),
storage_class: get_var(&config.storage_class),
upload_id: "".to_owned(),
parts: Vec::new(),
}
}
/// Executes the upload process.
async fn run(
mut self,
reader: &mut (dyn AsyncRead + Unpin),
est_len: u64,
) -> Result<(), Box<dyn std::error::Error>> {
if est_len <= MINIMUM_PART_SIZE as u64 {
// For short files, execute one put_object to upload the entire thing.
let mut data = Vec::with_capacity(est_len as usize);
reader.read_to_end(&mut data).await?;
retry(|| self.upload(&data)).await?;
Ok(())
} else {
// Otherwise, use multipart upload to improve robustness.
self.upload_id = retry(|| self.begin()).await?;
let upload_res = async {
let mut buf = vec![0; MINIMUM_PART_SIZE];
let mut part_number = 1;
loop {
let data_size = reader.read(&mut buf).await?;
if data_size == 0 {
break;
}
let part = retry(|| self.upload_part(part_number, &buf[..data_size])).await?;
self.parts.push(part);
part_number += 1;
}
Ok(())
}
.await;
if upload_res.is_ok() {
retry(|| self.complete()).await?;
} else { | }
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
..Default::default()
})
.await?;
output.upload_id.ok_or_else(|| {
RusotoError::ParseError("missing upload-id from create_multipart_upload()".to_owned())
})
}
/// Completes a multipart upload process, asking S3 to join all parts into a single file.
async fn complete(&self) -> Result<(), RusotoError<CompleteMultipartUploadError>> {
self.client
.complete_multipart_upload(CompleteMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(self.parts.clone()),
}),
..Default::default()
})
.await?;
Ok(())
}
/// Aborts the multipart upload process, deletes all uploaded parts.
async fn abort(&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default()
})
.await?;
Ok(())
}
/// Uploads a part of the file.
///
/// The `part_number` must be between 1 to 10000.
async fn upload_part(
&self,
part_number: i64,
data: &[u8],
) -> Result<CompletedPart, RusotoError<UploadPartError>> {
let part = self
.client
.upload_part(UploadPartRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
part_number,
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(CompletedPart {
e_tag: part.e_tag,
part_number: Some(part_number),
})
}
/// Uploads a file atomically.
///
/// This should be used only when the data is known to be short, and thus relatively cheap to
/// retry the entire upload.
async fn upload(&self, data: &[u8]) -> Result<(), RusotoError<PutObjectError>> {
self.client
.put_object(PutObjectRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(())
}
}
impl ExternalStorage for S3Storage {
fn write(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
let key = self.maybe_prefix_key(name);
debug!("save file to s3 storage"; "key" => %key);
let uploader = S3Uploader::new(&self.client, &self.config, key);
block_on_external_io(uploader.run(&mut *reader, content_length)).map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("failed to put object {}", e))
})
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let key = self.maybe_prefix_key(name);
let bucket = self.config.bucket.clone();
debug!("read file from s3 storage"; "key" => %key);
let req = GetObjectRequest {
key,
bucket: bucket.clone(),
..Default::default()
};
Box::new(
self.client
.get_object(req)
.map(move |future| match future {
Ok(out) => out.body.unwrap(),
Err(RusotoError::Service(GetObjectError::NoSuchKey(key))) => {
ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::NotFound,
format!("no key {} at bucket {}", key, bucket),
)))
}
Err(e) => ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::Other,
format!("failed to get object {}", e),
))),
})
.flatten_stream()
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::io::AsyncReadExt;
use rusoto_core::signature::SignedRequest;
use rusoto_mock::MockRequestDispatcher;
#[test]
fn test_s3_config() {
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let cases = vec![
// bucket is empty
Config {
bucket: "".to_owned(),
..config.clone()
},
];
for case in cases {
let r = S3Storage::new(&case);
assert!(r.is_err());
}
assert!(S3Storage::new(&config).is_ok());
}
#[test]
fn test_s3_storage() {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let dispatcher = MockRequestDispatcher::with_status(200).with_request_checker(
move |req: &SignedRequest| {
assert_eq!(req.region.name(), "ap-southeast-2");
assert_eq!(req.path(), "/mybucket/myprefix/mykey");
// PutObject is translated to HTTP PUT.
assert_eq!(req.payload.is_some(), req.method() == "PUT");
},
);
let s = S3Storage::with_request_dispatcher(&config, dispatcher).unwrap();
s.write(
"mykey",
Box::new(magic_contents.as_bytes()),
magic_contents.len() as u64,
)
.unwrap();
let mut reader = s.read("mykey");
let mut buf = Vec::new();
let ret = block_on_external_io(reader.read_to_end(&mut buf));
assert!(ret.unwrap() == 0);
assert!(buf.is_empty());
}
#[test]
#[cfg(FALSE)]
// FIXME: enable this (or move this to an integration test) if we've got a
// reliable way to test s3 (rusoto_mock requires custom logic to verify the
// body stream which itself can have bug)
fn test_real_s3_storage() {
use std::f64::INFINITY;
use tikv_util::time::Limiter;
let mut s3 = Config::default();
s3.set_endpoint("http://127.0.0.1:9000".to_owned());
s3.set_bucket("bucket".to_owned());
s3.set_prefix("prefix".to_owned());
s3.set_access_key("93QZ01QRBYQQXC37XHZV".to_owned());
s3.set_secret_access_key("N2VcI4Emg0Nm7fDzGBMJvguHHUxLGpjfwt2y4+vJ".to_owned());
s3.set_force_path_style(true);
let limiter = Limiter::new(INFINITY);
let storage = S3Storage::new(&s3).unwrap();
const LEN: usize = 1024 * 1024 * 4;
static CONTENT: [u8; LEN] = [50_u8; LEN];
storage
.write(
"huge_file",
Box::new(limiter.limit(&CONTENT[..])),
LEN as u64,
)
.unwrap();
let mut reader = storage.read("huge_file");
let mut buf = Vec::new();
block_on_external_io(reader.read_to_end(&mut buf)).unwrap();
assert_eq!(buf.len(), LEN);
assert_eq!(buf.iter().position(|b| *b!= 50_u8), None);
}
} | let _ = retry(|| self.abort()).await;
}
upload_res
} | random_line_split |
s3.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::PhantomData;
use futures_util::{
future::FutureExt,
io::{AsyncRead, AsyncReadExt},
stream::TryStreamExt,
};
use rusoto_core::{
request::DispatchSignedRequest,
{ByteStream, RusotoError},
};
use rusoto_s3::*;
use rusoto_util::new_client;
use super::{
util::{block_on_external_io, error_stream, retry, RetryError},
ExternalStorage,
};
use kvproto::backup::S3 as Config;
/// S3 compatible storage
#[derive(Clone)]
pub struct S3Storage {
config: Config,
client: S3Client,
// The current implementation (rosoto 0.43.0 + hyper 0.13.3) is not `Send`
// in practical. See more https://github.com/tikv/tikv/issues/7236.
// FIXME: remove it.
_not_send: PhantomData<*const ()>,
}
impl S3Storage {
/// Create a new S3 storage for the given config.
pub fn new(config: &Config) -> io::Result<S3Storage> {
Self::check_config(config)?;
let client = new_client!(S3Client, config);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
pub fn with_request_dispatcher<D>(config: &Config, dispatcher: D) -> io::Result<S3Storage>
where
D: DispatchSignedRequest + Send + Sync +'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::Result<()> {
if config.bucket.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"missing bucket name",
));
}
Ok(())
}
fn maybe_prefix_key(&self, key: &str) -> String {
if!self.config.prefix.is_empty() {
return format!("{}/{}", self.config.prefix, key);
}
key.to_owned()
}
}
impl<E> RetryError for RusotoError<E> {
fn placeholder() -> Self {
Self::Blocking
}
fn is_retryable(&self) -> bool {
match self {
Self::HttpDispatch(_) => true,
Self::Unknown(resp) if resp.status.is_server_error() => true,
// FIXME: Retry NOT_READY & THROTTLED (403).
_ => false,
}
}
}
/// A helper for uploading a large files to S3 storage.
///
/// Note: this uploader does not support uploading files larger than 19.5 GiB.
struct S3Uploader<'client> {
client: &'client S3Client,
bucket: String,
key: String,
acl: Option<String>,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader with a given target location and upload configuration.
fn new(client: &'client S3Client, config: &Config, key: String) -> Self {
fn get_var(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
}
Self {
client,
bucket: config.bucket.clone(),
key,
acl: get_var(&config.acl),
server_side_encryption: get_var(&config.sse),
ssekms_key_id: get_var(&config.sse_kms_key_id),
storage_class: get_var(&config.storage_class),
upload_id: "".to_owned(),
parts: Vec::new(),
}
}
/// Executes the upload process.
async fn run(
mut self,
reader: &mut (dyn AsyncRead + Unpin),
est_len: u64,
) -> Result<(), Box<dyn std::error::Error>> {
if est_len <= MINIMUM_PART_SIZE as u64 {
// For short files, execute one put_object to upload the entire thing.
let mut data = Vec::with_capacity(est_len as usize);
reader.read_to_end(&mut data).await?;
retry(|| self.upload(&data)).await?;
Ok(())
} else {
// Otherwise, use multipart upload to improve robustness.
self.upload_id = retry(|| self.begin()).await?;
let upload_res = async {
let mut buf = vec![0; MINIMUM_PART_SIZE];
let mut part_number = 1;
loop {
let data_size = reader.read(&mut buf).await?;
if data_size == 0 {
break;
}
let part = retry(|| self.upload_part(part_number, &buf[..data_size])).await?;
self.parts.push(part);
part_number += 1;
}
Ok(())
}
.await;
if upload_res.is_ok() {
retry(|| self.complete()).await?;
} else {
let _ = retry(|| self.abort()).await;
}
upload_res
}
}
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
..Default::default()
})
.await?;
output.upload_id.ok_or_else(|| {
RusotoError::ParseError("missing upload-id from create_multipart_upload()".to_owned())
})
}
/// Completes a multipart upload process, asking S3 to join all parts into a single file.
async fn complete(&self) -> Result<(), RusotoError<CompleteMultipartUploadError>> {
self.client
.complete_multipart_upload(CompleteMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(self.parts.clone()),
}),
..Default::default()
})
.await?;
Ok(())
}
/// Aborts the multipart upload process, deletes all uploaded parts.
async fn | (&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default()
})
.await?;
Ok(())
}
/// Uploads a part of the file.
///
/// The `part_number` must be between 1 to 10000.
async fn upload_part(
&self,
part_number: i64,
data: &[u8],
) -> Result<CompletedPart, RusotoError<UploadPartError>> {
let part = self
.client
.upload_part(UploadPartRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
part_number,
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(CompletedPart {
e_tag: part.e_tag,
part_number: Some(part_number),
})
}
/// Uploads a file atomically.
///
/// This should be used only when the data is known to be short, and thus relatively cheap to
/// retry the entire upload.
async fn upload(&self, data: &[u8]) -> Result<(), RusotoError<PutObjectError>> {
self.client
.put_object(PutObjectRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(())
}
}
impl ExternalStorage for S3Storage {
fn write(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
let key = self.maybe_prefix_key(name);
debug!("save file to s3 storage"; "key" => %key);
let uploader = S3Uploader::new(&self.client, &self.config, key);
block_on_external_io(uploader.run(&mut *reader, content_length)).map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("failed to put object {}", e))
})
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let key = self.maybe_prefix_key(name);
let bucket = self.config.bucket.clone();
debug!("read file from s3 storage"; "key" => %key);
let req = GetObjectRequest {
key,
bucket: bucket.clone(),
..Default::default()
};
Box::new(
self.client
.get_object(req)
.map(move |future| match future {
Ok(out) => out.body.unwrap(),
Err(RusotoError::Service(GetObjectError::NoSuchKey(key))) => {
ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::NotFound,
format!("no key {} at bucket {}", key, bucket),
)))
}
Err(e) => ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::Other,
format!("failed to get object {}", e),
))),
})
.flatten_stream()
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::io::AsyncReadExt;
use rusoto_core::signature::SignedRequest;
use rusoto_mock::MockRequestDispatcher;
#[test]
fn test_s3_config() {
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let cases = vec![
// bucket is empty
Config {
bucket: "".to_owned(),
..config.clone()
},
];
for case in cases {
let r = S3Storage::new(&case);
assert!(r.is_err());
}
assert!(S3Storage::new(&config).is_ok());
}
#[test]
fn test_s3_storage() {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let dispatcher = MockRequestDispatcher::with_status(200).with_request_checker(
move |req: &SignedRequest| {
assert_eq!(req.region.name(), "ap-southeast-2");
assert_eq!(req.path(), "/mybucket/myprefix/mykey");
// PutObject is translated to HTTP PUT.
assert_eq!(req.payload.is_some(), req.method() == "PUT");
},
);
let s = S3Storage::with_request_dispatcher(&config, dispatcher).unwrap();
s.write(
"mykey",
Box::new(magic_contents.as_bytes()),
magic_contents.len() as u64,
)
.unwrap();
let mut reader = s.read("mykey");
let mut buf = Vec::new();
let ret = block_on_external_io(reader.read_to_end(&mut buf));
assert!(ret.unwrap() == 0);
assert!(buf.is_empty());
}
#[test]
#[cfg(FALSE)]
// FIXME: enable this (or move this to an integration test) if we've got a
// reliable way to test s3 (rusoto_mock requires custom logic to verify the
// body stream which itself can have bug)
fn test_real_s3_storage() {
use std::f64::INFINITY;
use tikv_util::time::Limiter;
let mut s3 = Config::default();
s3.set_endpoint("http://127.0.0.1:9000".to_owned());
s3.set_bucket("bucket".to_owned());
s3.set_prefix("prefix".to_owned());
s3.set_access_key("93QZ01QRBYQQXC37XHZV".to_owned());
s3.set_secret_access_key("N2VcI4Emg0Nm7fDzGBMJvguHHUxLGpjfwt2y4+vJ".to_owned());
s3.set_force_path_style(true);
let limiter = Limiter::new(INFINITY);
let storage = S3Storage::new(&s3).unwrap();
const LEN: usize = 1024 * 1024 * 4;
static CONTENT: [u8; LEN] = [50_u8; LEN];
storage
.write(
"huge_file",
Box::new(limiter.limit(&CONTENT[..])),
LEN as u64,
)
.unwrap();
let mut reader = storage.read("huge_file");
let mut buf = Vec::new();
block_on_external_io(reader.read_to_end(&mut buf)).unwrap();
assert_eq!(buf.len(), LEN);
assert_eq!(buf.iter().position(|b| *b!= 50_u8), None);
}
}
| abort | identifier_name |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crate struct MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
/// Stores the first "member" constraint for a given `R0`. This is an
/// index into the `constraints` vector below.
first_constraints: FxHashMap<R, NllMemberConstraintIndex>,
/// Stores the data about each `R0 member of [R1..Rn]` constraint.
/// These are organized into a linked list, so each constraint
/// contains the index of the next constraint with the same `R0`.
constraints: IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'tcx>>,
/// Stores the `R1..Rn` regions for *all* sets. For any given
/// constraint, we keep two indices so that we can pull out a
/// slice.
choice_regions: Vec<ty::RegionVid>,
}
/// Represents a `R0 member of [R1..Rn]` constraint
crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
crate member_region_vid: ty::RegionVid,
/// Index of `R1` in `choice_regions` vector from `MemberConstraintSet`.
start_index: usize,
/// Index of `Rn` in `choice_regions` vector from `MemberConstraintSet`.
end_index: usize,
}
rustc_index::newtype_index! {
crate struct NllMemberConstraintIndex {
DEBUG_FORMAT = "MemberConstraintIndex({})"
}
}
impl Default for MemberConstraintSet<'tcx, ty::RegionVid> {
fn default() -> Self {
Self {
first_constraints: Default::default(),
constraints: Default::default(),
choice_regions: Default::default(),
}
}
}
impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> {
/// Pushes a member constraint into the set.
///
/// The input member constraint `m_c` is in the form produced by
/// the `rustc_middle::infer` code.
///
/// The `to_region_vid` callback fn is used to convert the regions
/// within into `RegionVid` format -- it typically consults the
/// `UniversalRegions` data structure that is known to the caller
/// (but which this code is unaware of).
crate fn push_constraint(
&mut self,
m_c: &MemberConstraint<'tcx>,
mut to_region_vid: impl FnMut(ty::Region<'tcx>) -> ty::RegionVid,
) {
debug!("push_constraint(m_c={:?})", m_c);
let member_region_vid: ty::RegionVid = to_region_vid(m_c.member_region);
let next_constraint = self.first_constraints.get(&member_region_vid).cloned();
let start_index = self.choice_regions.len();
let end_index = start_index + m_c.choice_regions.len();
debug!("push_constraint: member_region_vid={:?}", member_region_vid);
let constraint_index = self.constraints.push(NllMemberConstraint {
next_constraint,
member_region_vid,
definition_span: m_c.definition_span,
hidden_ty: m_c.hidden_ty,
start_index,
end_index,
});
self.first_constraints.insert(member_region_vid, constraint_index);
self.choice_regions.extend(m_c.choice_regions.iter().map(|&r| to_region_vid(r)));
}
}
impl<R1> MemberConstraintSet<'tcx, R1>
where
R1: Copy + Hash + Eq,
{
/// Remap the "member region" key using `map_fn`, producing a new
/// member constraint set. This is used in the NLL code to map from
/// the original `RegionVid` to an scc index. In some cases, we
/// may have multiple `R1` values mapping to the same `R2` key -- that
/// is ok, the two sets will be merged.
crate fn into_mapped<R2>(
self,
mut map_fn: impl FnMut(R1) -> R2,
) -> MemberConstraintSet<'tcx, R2>
where
R2: Copy + Hash + Eq,
{
// We can re-use most of the original data, just tweaking the
// linked list links a bit.
//
// For example if we had two keys `Ra` and `Rb` that both now
// wind up mapped to the same key `S`, we would append the
// linked list for `Ra` onto the end of the linked list for
// `Rb` (or vice versa) -- this basically just requires
// rewriting the final link from one list to point at the other
// other (see `append_list`).
let MemberConstraintSet { first_constraints, mut constraints, choice_regions } = self;
let mut first_constraints2 = FxHashMap::default();
first_constraints2.reserve(first_constraints.len());
for (r1, start1) in first_constraints {
let r2 = map_fn(r1);
if let Some(&start2) = first_constraints2.get(&r2) {
append_list(&mut constraints, start1, start2);
}
first_constraints2.insert(r2, start1);
}
MemberConstraintSet { first_constraints: first_constraints2, constraints, choice_regions }
}
}
impl<R> MemberConstraintSet<'tcx, R>
where
R: Copy + Hash + Eq,
{
crate fn all_indices(&self) -> impl Iterator<Item = NllMemberConstraintIndex> {
self.constraints.indices()
}
/// Iterate down the constraint indices associated with a given
/// peek-region. You can then use `choice_regions` and other
/// methods to access data.
crate fn indices(
&self,
member_region_vid: R,
) -> impl Iterator<Item = NllMemberConstraintIndex> + '_ {
let mut next = self.first_constraints.get(&member_region_vid).cloned();
std::iter::from_fn(move || -> Option<NllMemberConstraintIndex> {
if let Some(current) = next {
next = self.constraints[current].next_constraint;
Some(current)
} else {
None
}
})
}
/// Returns the "choice regions" for a given member
/// constraint. This is the `R1..Rn` from a constraint like:
///
/// ```
/// R0 member of [R1..Rn]
/// ```
crate fn choice_regions(&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index,.. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
type Output = NllMemberConstraint<'tcx>;
fn index(&self, i: NllMemberConstraintIndex) -> &NllMemberConstraint<'tcx> |
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// target_list: A -> B -> C -> D -> E -> F -> (None)
/// ```
fn append_list(
constraints: &mut IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'_>>,
target_list: NllMemberConstraintIndex,
source_list: NllMemberConstraintIndex,
) {
let mut p = target_list;
loop {
let mut r = &mut constraints[p];
match r.next_constraint {
Some(q) => p = q,
None => {
r.next_constraint = Some(source_list);
return;
}
}
}
}
| {
&self.constraints[i]
} | identifier_body |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crate struct MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
/// Stores the first "member" constraint for a given `R0`. This is an
/// index into the `constraints` vector below.
first_constraints: FxHashMap<R, NllMemberConstraintIndex>,
/// Stores the data about each `R0 member of [R1..Rn]` constraint.
/// These are organized into a linked list, so each constraint
/// contains the index of the next constraint with the same `R0`.
constraints: IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'tcx>>,
/// Stores the `R1..Rn` regions for *all* sets. For any given
/// constraint, we keep two indices so that we can pull out a
/// slice.
choice_regions: Vec<ty::RegionVid>,
}
/// Represents a `R0 member of [R1..Rn]` constraint | crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
crate member_region_vid: ty::RegionVid,
/// Index of `R1` in `choice_regions` vector from `MemberConstraintSet`.
start_index: usize,
/// Index of `Rn` in `choice_regions` vector from `MemberConstraintSet`.
end_index: usize,
}
rustc_index::newtype_index! {
crate struct NllMemberConstraintIndex {
DEBUG_FORMAT = "MemberConstraintIndex({})"
}
}
impl Default for MemberConstraintSet<'tcx, ty::RegionVid> {
fn default() -> Self {
Self {
first_constraints: Default::default(),
constraints: Default::default(),
choice_regions: Default::default(),
}
}
}
impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> {
/// Pushes a member constraint into the set.
///
/// The input member constraint `m_c` is in the form produced by
/// the `rustc_middle::infer` code.
///
/// The `to_region_vid` callback fn is used to convert the regions
/// within into `RegionVid` format -- it typically consults the
/// `UniversalRegions` data structure that is known to the caller
/// (but which this code is unaware of).
crate fn push_constraint(
&mut self,
m_c: &MemberConstraint<'tcx>,
mut to_region_vid: impl FnMut(ty::Region<'tcx>) -> ty::RegionVid,
) {
debug!("push_constraint(m_c={:?})", m_c);
let member_region_vid: ty::RegionVid = to_region_vid(m_c.member_region);
let next_constraint = self.first_constraints.get(&member_region_vid).cloned();
let start_index = self.choice_regions.len();
let end_index = start_index + m_c.choice_regions.len();
debug!("push_constraint: member_region_vid={:?}", member_region_vid);
let constraint_index = self.constraints.push(NllMemberConstraint {
next_constraint,
member_region_vid,
definition_span: m_c.definition_span,
hidden_ty: m_c.hidden_ty,
start_index,
end_index,
});
self.first_constraints.insert(member_region_vid, constraint_index);
self.choice_regions.extend(m_c.choice_regions.iter().map(|&r| to_region_vid(r)));
}
}
impl<R1> MemberConstraintSet<'tcx, R1>
where
R1: Copy + Hash + Eq,
{
/// Remap the "member region" key using `map_fn`, producing a new
/// member constraint set. This is used in the NLL code to map from
/// the original `RegionVid` to an scc index. In some cases, we
/// may have multiple `R1` values mapping to the same `R2` key -- that
/// is ok, the two sets will be merged.
crate fn into_mapped<R2>(
self,
mut map_fn: impl FnMut(R1) -> R2,
) -> MemberConstraintSet<'tcx, R2>
where
R2: Copy + Hash + Eq,
{
// We can re-use most of the original data, just tweaking the
// linked list links a bit.
//
// For example if we had two keys `Ra` and `Rb` that both now
// wind up mapped to the same key `S`, we would append the
// linked list for `Ra` onto the end of the linked list for
// `Rb` (or vice versa) -- this basically just requires
// rewriting the final link from one list to point at the other
// other (see `append_list`).
let MemberConstraintSet { first_constraints, mut constraints, choice_regions } = self;
let mut first_constraints2 = FxHashMap::default();
first_constraints2.reserve(first_constraints.len());
for (r1, start1) in first_constraints {
let r2 = map_fn(r1);
if let Some(&start2) = first_constraints2.get(&r2) {
append_list(&mut constraints, start1, start2);
}
first_constraints2.insert(r2, start1);
}
MemberConstraintSet { first_constraints: first_constraints2, constraints, choice_regions }
}
}
impl<R> MemberConstraintSet<'tcx, R>
where
R: Copy + Hash + Eq,
{
crate fn all_indices(&self) -> impl Iterator<Item = NllMemberConstraintIndex> {
self.constraints.indices()
}
/// Iterate down the constraint indices associated with a given
/// peek-region. You can then use `choice_regions` and other
/// methods to access data.
crate fn indices(
&self,
member_region_vid: R,
) -> impl Iterator<Item = NllMemberConstraintIndex> + '_ {
let mut next = self.first_constraints.get(&member_region_vid).cloned();
std::iter::from_fn(move || -> Option<NllMemberConstraintIndex> {
if let Some(current) = next {
next = self.constraints[current].next_constraint;
Some(current)
} else {
None
}
})
}
/// Returns the "choice regions" for a given member
/// constraint. This is the `R1..Rn` from a constraint like:
///
/// ```
/// R0 member of [R1..Rn]
/// ```
crate fn choice_regions(&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index,.. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
type Output = NllMemberConstraint<'tcx>;
fn index(&self, i: NllMemberConstraintIndex) -> &NllMemberConstraint<'tcx> {
&self.constraints[i]
}
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// target_list: A -> B -> C -> D -> E -> F -> (None)
/// ```
fn append_list(
constraints: &mut IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'_>>,
target_list: NllMemberConstraintIndex,
source_list: NllMemberConstraintIndex,
) {
let mut p = target_list;
loop {
let mut r = &mut constraints[p];
match r.next_constraint {
Some(q) => p = q,
None => {
r.next_constraint = Some(source_list);
return;
}
}
}
} | random_line_split |
|
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crate struct MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
/// Stores the first "member" constraint for a given `R0`. This is an
/// index into the `constraints` vector below.
first_constraints: FxHashMap<R, NllMemberConstraintIndex>,
/// Stores the data about each `R0 member of [R1..Rn]` constraint.
/// These are organized into a linked list, so each constraint
/// contains the index of the next constraint with the same `R0`.
constraints: IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'tcx>>,
/// Stores the `R1..Rn` regions for *all* sets. For any given
/// constraint, we keep two indices so that we can pull out a
/// slice.
choice_regions: Vec<ty::RegionVid>,
}
/// Represents a `R0 member of [R1..Rn]` constraint
crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
crate member_region_vid: ty::RegionVid,
/// Index of `R1` in `choice_regions` vector from `MemberConstraintSet`.
start_index: usize,
/// Index of `Rn` in `choice_regions` vector from `MemberConstraintSet`.
end_index: usize,
}
rustc_index::newtype_index! {
crate struct NllMemberConstraintIndex {
DEBUG_FORMAT = "MemberConstraintIndex({})"
}
}
impl Default for MemberConstraintSet<'tcx, ty::RegionVid> {
fn default() -> Self {
Self {
first_constraints: Default::default(),
constraints: Default::default(),
choice_regions: Default::default(),
}
}
}
impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> {
/// Pushes a member constraint into the set.
///
/// The input member constraint `m_c` is in the form produced by
/// the `rustc_middle::infer` code.
///
/// The `to_region_vid` callback fn is used to convert the regions
/// within into `RegionVid` format -- it typically consults the
/// `UniversalRegions` data structure that is known to the caller
/// (but which this code is unaware of).
crate fn push_constraint(
&mut self,
m_c: &MemberConstraint<'tcx>,
mut to_region_vid: impl FnMut(ty::Region<'tcx>) -> ty::RegionVid,
) {
debug!("push_constraint(m_c={:?})", m_c);
let member_region_vid: ty::RegionVid = to_region_vid(m_c.member_region);
let next_constraint = self.first_constraints.get(&member_region_vid).cloned();
let start_index = self.choice_regions.len();
let end_index = start_index + m_c.choice_regions.len();
debug!("push_constraint: member_region_vid={:?}", member_region_vid);
let constraint_index = self.constraints.push(NllMemberConstraint {
next_constraint,
member_region_vid,
definition_span: m_c.definition_span,
hidden_ty: m_c.hidden_ty,
start_index,
end_index,
});
self.first_constraints.insert(member_region_vid, constraint_index);
self.choice_regions.extend(m_c.choice_regions.iter().map(|&r| to_region_vid(r)));
}
}
impl<R1> MemberConstraintSet<'tcx, R1>
where
R1: Copy + Hash + Eq,
{
/// Remap the "member region" key using `map_fn`, producing a new
/// member constraint set. This is used in the NLL code to map from
/// the original `RegionVid` to an scc index. In some cases, we
/// may have multiple `R1` values mapping to the same `R2` key -- that
/// is ok, the two sets will be merged.
crate fn into_mapped<R2>(
self,
mut map_fn: impl FnMut(R1) -> R2,
) -> MemberConstraintSet<'tcx, R2>
where
R2: Copy + Hash + Eq,
{
// We can re-use most of the original data, just tweaking the
// linked list links a bit.
//
// For example if we had two keys `Ra` and `Rb` that both now
// wind up mapped to the same key `S`, we would append the
// linked list for `Ra` onto the end of the linked list for
// `Rb` (or vice versa) -- this basically just requires
// rewriting the final link from one list to point at the other
// other (see `append_list`).
let MemberConstraintSet { first_constraints, mut constraints, choice_regions } = self;
let mut first_constraints2 = FxHashMap::default();
first_constraints2.reserve(first_constraints.len());
for (r1, start1) in first_constraints {
let r2 = map_fn(r1);
if let Some(&start2) = first_constraints2.get(&r2) {
append_list(&mut constraints, start1, start2);
}
first_constraints2.insert(r2, start1);
}
MemberConstraintSet { first_constraints: first_constraints2, constraints, choice_regions }
}
}
impl<R> MemberConstraintSet<'tcx, R>
where
R: Copy + Hash + Eq,
{
crate fn all_indices(&self) -> impl Iterator<Item = NllMemberConstraintIndex> {
self.constraints.indices()
}
/// Iterate down the constraint indices associated with a given
/// peek-region. You can then use `choice_regions` and other
/// methods to access data.
crate fn indices(
&self,
member_region_vid: R,
) -> impl Iterator<Item = NllMemberConstraintIndex> + '_ {
let mut next = self.first_constraints.get(&member_region_vid).cloned();
std::iter::from_fn(move || -> Option<NllMemberConstraintIndex> {
if let Some(current) = next {
next = self.constraints[current].next_constraint;
Some(current)
} else {
None
}
})
}
/// Returns the "choice regions" for a given member
/// constraint. This is the `R1..Rn` from a constraint like:
///
/// ```
/// R0 member of [R1..Rn]
/// ```
crate fn | (&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index,.. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
type Output = NllMemberConstraint<'tcx>;
fn index(&self, i: NllMemberConstraintIndex) -> &NllMemberConstraint<'tcx> {
&self.constraints[i]
}
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// target_list: A -> B -> C -> D -> E -> F -> (None)
/// ```
fn append_list(
constraints: &mut IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'_>>,
target_list: NllMemberConstraintIndex,
source_list: NllMemberConstraintIndex,
) {
let mut p = target_list;
loop {
let mut r = &mut constraints[p];
match r.next_constraint {
Some(q) => p = q,
None => {
r.next_constraint = Some(source_list);
return;
}
}
}
}
| choice_regions | identifier_name |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!( | const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once
const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS
const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS
const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous
const MS_NOATIME = libc::MS_NOATIME; // Do not update access times
const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times
const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place
const MS_MOVE = libc::MS_MOVE;
const MS_REC = libc::MS_REC;
const MS_VERBOSE = 1 << 15; // Deprecated
const MS_SILENT = libc::MS_SILENT;
const MS_POSIXACL = libc::MS_POSIXACL;
const MS_UNBINDABLE = libc::MS_UNBINDABLE;
const MS_PRIVATE = libc::MS_PRIVATE;
const MS_SLAVE = libc::MS_SLAVE;
const MS_SHARED = libc::MS_SHARED;
const MS_RELATIME = libc::MS_RELATIME;
const MS_KERNMOUNT = libc::MS_KERNMOUNT;
const MS_I_VERSION = libc::MS_I_VERSION;
const MS_STRICTATIME = libc::MS_STRICTATIME;
const MS_NOSEC = 1 << 28;
const MS_BORN = 1 << 29;
const MS_ACTIVE = libc::MS_ACTIVE;
const MS_NOUSER = libc::MS_NOUSER;
const MS_RMT_MASK = libc::MS_RMT_MASK;
const MS_MGC_VAL = libc::MS_MGC_VAL;
const MS_MGC_MSK = libc::MS_MGC_MSK;
}
);
libc_bitflags!(
pub flags MntFlags: c_int {
MNT_FORCE,
MNT_DETACH,
MNT_EXPIRE,
}
);
pub fn mount<P1:?Sized + NixPath, P2:?Sized + NixPath, P3:?Sized + NixPath, P4:?Sized + NixPath>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>) -> Result<()> {
use libc;
let res = try!(try!(try!(try!(
source.with_nix_path(|source| {
target.with_nix_path(|target| {
fstype.with_nix_path(|fstype| {
data.with_nix_path(|data| {
unsafe {
libc::mount(source.as_ptr(),
target.as_ptr(),
fstype.as_ptr(),
flags.bits,
data.as_ptr() as *const libc::c_void)
}
})
})
})
})))));
Errno::result(res).map(drop)
}
pub fn umount<P:?Sized + NixPath>(target: &P) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
pub fn umount2<P:?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
} | pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only | random_line_split |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!(
pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only
const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once
const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS
const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS
const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous
const MS_NOATIME = libc::MS_NOATIME; // Do not update access times
const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times
const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place
const MS_MOVE = libc::MS_MOVE;
const MS_REC = libc::MS_REC;
const MS_VERBOSE = 1 << 15; // Deprecated
const MS_SILENT = libc::MS_SILENT;
const MS_POSIXACL = libc::MS_POSIXACL;
const MS_UNBINDABLE = libc::MS_UNBINDABLE;
const MS_PRIVATE = libc::MS_PRIVATE;
const MS_SLAVE = libc::MS_SLAVE;
const MS_SHARED = libc::MS_SHARED;
const MS_RELATIME = libc::MS_RELATIME;
const MS_KERNMOUNT = libc::MS_KERNMOUNT;
const MS_I_VERSION = libc::MS_I_VERSION;
const MS_STRICTATIME = libc::MS_STRICTATIME;
const MS_NOSEC = 1 << 28;
const MS_BORN = 1 << 29;
const MS_ACTIVE = libc::MS_ACTIVE;
const MS_NOUSER = libc::MS_NOUSER;
const MS_RMT_MASK = libc::MS_RMT_MASK;
const MS_MGC_VAL = libc::MS_MGC_VAL;
const MS_MGC_MSK = libc::MS_MGC_MSK;
}
);
libc_bitflags!(
pub flags MntFlags: c_int {
MNT_FORCE,
MNT_DETACH,
MNT_EXPIRE,
}
);
pub fn mount<P1:?Sized + NixPath, P2:?Sized + NixPath, P3:?Sized + NixPath, P4:?Sized + NixPath>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>) -> Result<()> {
use libc;
let res = try!(try!(try!(try!(
source.with_nix_path(|source| {
target.with_nix_path(|target| {
fstype.with_nix_path(|fstype| {
data.with_nix_path(|data| {
unsafe {
libc::mount(source.as_ptr(),
target.as_ptr(),
fstype.as_ptr(),
flags.bits,
data.as_ptr() as *const libc::c_void)
}
})
})
})
})))));
Errno::result(res).map(drop)
}
pub fn umount<P:?Sized + NixPath>(target: &P) -> Result<()> |
pub fn umount2<P:?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
}
| {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
} | identifier_body |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!(
pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only
const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once
const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS
const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS
const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous
const MS_NOATIME = libc::MS_NOATIME; // Do not update access times
const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times
const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place
const MS_MOVE = libc::MS_MOVE;
const MS_REC = libc::MS_REC;
const MS_VERBOSE = 1 << 15; // Deprecated
const MS_SILENT = libc::MS_SILENT;
const MS_POSIXACL = libc::MS_POSIXACL;
const MS_UNBINDABLE = libc::MS_UNBINDABLE;
const MS_PRIVATE = libc::MS_PRIVATE;
const MS_SLAVE = libc::MS_SLAVE;
const MS_SHARED = libc::MS_SHARED;
const MS_RELATIME = libc::MS_RELATIME;
const MS_KERNMOUNT = libc::MS_KERNMOUNT;
const MS_I_VERSION = libc::MS_I_VERSION;
const MS_STRICTATIME = libc::MS_STRICTATIME;
const MS_NOSEC = 1 << 28;
const MS_BORN = 1 << 29;
const MS_ACTIVE = libc::MS_ACTIVE;
const MS_NOUSER = libc::MS_NOUSER;
const MS_RMT_MASK = libc::MS_RMT_MASK;
const MS_MGC_VAL = libc::MS_MGC_VAL;
const MS_MGC_MSK = libc::MS_MGC_MSK;
}
);
libc_bitflags!(
pub flags MntFlags: c_int {
MNT_FORCE,
MNT_DETACH,
MNT_EXPIRE,
}
);
pub fn mount<P1:?Sized + NixPath, P2:?Sized + NixPath, P3:?Sized + NixPath, P4:?Sized + NixPath>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>) -> Result<()> {
use libc;
let res = try!(try!(try!(try!(
source.with_nix_path(|source| {
target.with_nix_path(|target| {
fstype.with_nix_path(|fstype| {
data.with_nix_path(|data| {
unsafe {
libc::mount(source.as_ptr(),
target.as_ptr(),
fstype.as_ptr(),
flags.bits,
data.as_ptr() as *const libc::c_void)
}
})
})
})
})))));
Errno::result(res).map(drop)
}
pub fn | <P:?Sized + NixPath>(target: &P) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
pub fn umount2<P:?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
}
| umount | identifier_name |
mod.rs | // 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.
//! Lints, aka compiler warnings.
//!
//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are defined elsewhere in the compiler and work by
//! calling `add_lint()` on the overall `Session` object. This works when
//! it happens before the main lint pass, which emits the lints stored by
//! `add_lint()`. To emit lints after the main lint pass (from trans, for
//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
//! in `context.rs`.
pub use self::Level::*;
pub use self::LintSource::*;
use std::hash;
use std::ascii::AsciiExt;
use syntax::codemap::Span;
use syntax::visit::FnKind;
use syntax::ast;
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
#[derive(Copy, Show)]
pub struct Lint {
/// A string identifier for the lint.
///
/// This identifies the lint in attributes and in command-line arguments.
/// In those contexts it is always lowercase, but this field is compared
/// in a way which is case-insensitive for ASCII characters. This allows
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
/// The name is written with underscores, e.g. "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Default level for the lint.
pub default_level: Level,
/// Description of the lint or the issue it detects.
///
/// e.g. "imports that are never used"
pub desc: &'static str,
}
impl Lint {
/// Get the lint's name, with ASCII letters converted to lowercase.
pub fn name_lower(&self) -> String {
self.name.to_ascii_lowercase()
}
}
/// Build a `Lint` initializer.
#[macro_export]
macro_rules! lint_initializer {
($name:ident, $level:ident, $desc:expr) => (
::rustc::lint::Lint {
name: stringify!($name),
default_level: ::rustc::lint::$level,
desc: $desc,
}
)
}
/// Declare a static item of type `&'static Lint`.
#[macro_export]
macro_rules! declare_lint {
// FIXME(#14660): deduplicate
(pub $name:ident, $level:ident, $desc:expr) => (
pub static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
($name:ident, $level:ident, $desc:expr) => (
static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lint];
/// Trait for types providing lint checks.
///
/// Each `check` method checks a single syntax node, and should not
/// invoke methods recursively (unlike `Visitor`). By default they
/// do nothing.
//
// FIXME: eliminate the duplication with `Visitor`. But this also
// contains a few lint-specific methods with no equivalent in `Visitor`.
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
/// NB: there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
fn get_lints(&self) -> LintArray;
fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
fn check_item(&mut self, _: &Context, _: &ast::Item) { }
fn check_local(&mut self, _: &Context, _: &ast::Local) { }
fn check_block(&mut self, _: &Context, _: &ast::Block) { }
fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { }
fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
/// Called when entering a syntax node that can have lint attributes such
/// as `#[allow(...)]`. Called with *all* the attributes of that node.
fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
/// Counterpart to `enter_lint_attrs`.
fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
}
/// A lint pass boxed up as a trait object.
pub type LintPassObject = Box<LintPass +'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
impl PartialEq for LintId {
fn eq(&self, other: &LintId) -> bool {
(self.lint as *const Lint) == (other.lint as *const Lint)
}
}
impl Eq for LintId { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId {
fn hash(&self, state: &mut S) {
let ptr = self.lint as *const Lint;
ptr.hash(state);
}
}
impl LintId {
/// Get the `LintId` for a `Lint`.
pub fn of(lint: &'static Lint) -> LintId {
LintId {
lint: lint,
}
}
/// Get the name of the lint.
pub fn as_str(&self) -> String {
self.lint.name_lower()
}
}
/// Setting for how to handle a lint.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)]
pub enum | {
Allow, Warn, Deny, Forbid
}
impl Level {
/// Convert a level to a lower-case string.
pub fn as_str(self) -> &'static str {
match self {
Allow => "allow",
Warn => "warn",
Deny => "deny",
Forbid => "forbid",
}
}
/// Convert a lower-case string to a level.
pub fn from_str(x: &str) -> Option<Level> {
match x {
"allow" => Some(Allow),
"warn" => Some(Warn),
"deny" => Some(Deny),
"forbid" => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
Default,
/// Lint level was set by an attribute.
Node(Span),
/// Lint level was set by a command-line flag.
CommandLine,
/// Lint level was set by the release channel.
ReleaseChannel
}
pub type LevelSource = (Level, LintSource);
pub mod builtin;
mod context;
| Level | identifier_name |
mod.rs | // 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.
//! Lints, aka compiler warnings.
//!
//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are defined elsewhere in the compiler and work by
//! calling `add_lint()` on the overall `Session` object. This works when
//! it happens before the main lint pass, which emits the lints stored by
//! `add_lint()`. To emit lints after the main lint pass (from trans, for
//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
//! in `context.rs`.
pub use self::Level::*;
pub use self::LintSource::*;
use std::hash;
use std::ascii::AsciiExt;
use syntax::codemap::Span;
use syntax::visit::FnKind;
use syntax::ast;
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
#[derive(Copy, Show)]
pub struct Lint {
/// A string identifier for the lint.
///
/// This identifies the lint in attributes and in command-line arguments.
/// In those contexts it is always lowercase, but this field is compared
/// in a way which is case-insensitive for ASCII characters. This allows
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
/// The name is written with underscores, e.g. "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Default level for the lint.
pub default_level: Level,
/// Description of the lint or the issue it detects.
///
/// e.g. "imports that are never used"
pub desc: &'static str,
}
impl Lint {
/// Get the lint's name, with ASCII letters converted to lowercase.
pub fn name_lower(&self) -> String {
self.name.to_ascii_lowercase()
}
}
/// Build a `Lint` initializer.
#[macro_export]
macro_rules! lint_initializer {
($name:ident, $level:ident, $desc:expr) => (
::rustc::lint::Lint {
name: stringify!($name),
default_level: ::rustc::lint::$level,
desc: $desc,
}
)
}
/// Declare a static item of type `&'static Lint`.
#[macro_export]
macro_rules! declare_lint {
// FIXME(#14660): deduplicate
(pub $name:ident, $level:ident, $desc:expr) => (
pub static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
($name:ident, $level:ident, $desc:expr) => (
static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lint];
/// Trait for types providing lint checks.
///
/// Each `check` method checks a single syntax node, and should not
/// invoke methods recursively (unlike `Visitor`). By default they
/// do nothing.
//
// FIXME: eliminate the duplication with `Visitor`. But this also
// contains a few lint-specific methods with no equivalent in `Visitor`.
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
/// NB: there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
fn get_lints(&self) -> LintArray;
fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
fn check_item(&mut self, _: &Context, _: &ast::Item) { }
fn check_local(&mut self, _: &Context, _: &ast::Local) { }
fn check_block(&mut self, _: &Context, _: &ast::Block) { }
fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) |
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { }
fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
/// Called when entering a syntax node that can have lint attributes such
/// as `#[allow(...)]`. Called with *all* the attributes of that node.
fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
/// Counterpart to `enter_lint_attrs`.
fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
}
/// A lint pass boxed up as a trait object.
pub type LintPassObject = Box<LintPass +'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
impl PartialEq for LintId {
fn eq(&self, other: &LintId) -> bool {
(self.lint as *const Lint) == (other.lint as *const Lint)
}
}
impl Eq for LintId { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId {
fn hash(&self, state: &mut S) {
let ptr = self.lint as *const Lint;
ptr.hash(state);
}
}
impl LintId {
/// Get the `LintId` for a `Lint`.
pub fn of(lint: &'static Lint) -> LintId {
LintId {
lint: lint,
}
}
/// Get the name of the lint.
pub fn as_str(&self) -> String {
self.lint.name_lower()
}
}
/// Setting for how to handle a lint.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)]
pub enum Level {
Allow, Warn, Deny, Forbid
}
impl Level {
/// Convert a level to a lower-case string.
pub fn as_str(self) -> &'static str {
match self {
Allow => "allow",
Warn => "warn",
Deny => "deny",
Forbid => "forbid",
}
}
/// Convert a lower-case string to a level.
pub fn from_str(x: &str) -> Option<Level> {
match x {
"allow" => Some(Allow),
"warn" => Some(Warn),
"deny" => Some(Deny),
"forbid" => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
Default,
/// Lint level was set by an attribute.
Node(Span),
/// Lint level was set by a command-line flag.
CommandLine,
/// Lint level was set by the release channel.
ReleaseChannel
}
pub type LevelSource = (Level, LintSource);
pub mod builtin;
mod context;
| { } | identifier_body |
mod.rs | // 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.
//! Lints, aka compiler warnings.
//!
//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are defined elsewhere in the compiler and work by
//! calling `add_lint()` on the overall `Session` object. This works when
//! it happens before the main lint pass, which emits the lints stored by
//! `add_lint()`. To emit lints after the main lint pass (from trans, for
//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
//! in `context.rs`.
pub use self::Level::*;
pub use self::LintSource::*;
use std::hash;
use std::ascii::AsciiExt;
use syntax::codemap::Span;
use syntax::visit::FnKind;
use syntax::ast;
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
#[derive(Copy, Show)]
pub struct Lint {
/// A string identifier for the lint.
///
/// This identifies the lint in attributes and in command-line arguments.
/// In those contexts it is always lowercase, but this field is compared
/// in a way which is case-insensitive for ASCII characters. This allows
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
/// The name is written with underscores, e.g. "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Default level for the lint.
pub default_level: Level,
/// Description of the lint or the issue it detects.
///
/// e.g. "imports that are never used"
pub desc: &'static str,
}
impl Lint {
/// Get the lint's name, with ASCII letters converted to lowercase.
pub fn name_lower(&self) -> String {
self.name.to_ascii_lowercase()
}
}
/// Build a `Lint` initializer.
#[macro_export]
macro_rules! lint_initializer {
($name:ident, $level:ident, $desc:expr) => (
::rustc::lint::Lint {
name: stringify!($name),
default_level: ::rustc::lint::$level,
desc: $desc,
}
)
}
/// Declare a static item of type `&'static Lint`.
#[macro_export]
macro_rules! declare_lint {
// FIXME(#14660): deduplicate
(pub $name:ident, $level:ident, $desc:expr) => (
pub static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
($name:ident, $level:ident, $desc:expr) => (
static $name: &'static ::rustc::lint::Lint | );
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lint];
/// Trait for types providing lint checks.
///
/// Each `check` method checks a single syntax node, and should not
/// invoke methods recursively (unlike `Visitor`). By default they
/// do nothing.
//
// FIXME: eliminate the duplication with `Visitor`. But this also
// contains a few lint-specific methods with no equivalent in `Visitor`.
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
/// NB: there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
fn get_lints(&self) -> LintArray;
fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
fn check_item(&mut self, _: &Context, _: &ast::Item) { }
fn check_local(&mut self, _: &Context, _: &ast::Local) { }
fn check_block(&mut self, _: &Context, _: &ast::Block) { }
fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { }
fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
/// Called when entering a syntax node that can have lint attributes such
/// as `#[allow(...)]`. Called with *all* the attributes of that node.
fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
/// Counterpart to `enter_lint_attrs`.
fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
}
/// A lint pass boxed up as a trait object.
pub type LintPassObject = Box<LintPass +'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
impl PartialEq for LintId {
fn eq(&self, other: &LintId) -> bool {
(self.lint as *const Lint) == (other.lint as *const Lint)
}
}
impl Eq for LintId { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId {
fn hash(&self, state: &mut S) {
let ptr = self.lint as *const Lint;
ptr.hash(state);
}
}
impl LintId {
/// Get the `LintId` for a `Lint`.
pub fn of(lint: &'static Lint) -> LintId {
LintId {
lint: lint,
}
}
/// Get the name of the lint.
pub fn as_str(&self) -> String {
self.lint.name_lower()
}
}
/// Setting for how to handle a lint.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)]
pub enum Level {
Allow, Warn, Deny, Forbid
}
impl Level {
/// Convert a level to a lower-case string.
pub fn as_str(self) -> &'static str {
match self {
Allow => "allow",
Warn => "warn",
Deny => "deny",
Forbid => "forbid",
}
}
/// Convert a lower-case string to a level.
pub fn from_str(x: &str) -> Option<Level> {
match x {
"allow" => Some(Allow),
"warn" => Some(Warn),
"deny" => Some(Deny),
"forbid" => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
Default,
/// Lint level was set by an attribute.
Node(Span),
/// Lint level was set by a command-line flag.
CommandLine,
/// Lint level was set by the release channel.
ReleaseChannel
}
pub type LevelSource = (Level, LintSource);
pub mod builtin;
mod context; | = &lint_initializer!($name, $level, $desc); | random_line_split |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline] | self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
} | pub unsafe fn make_current(&self) -> Result<(), ContextError> { | random_line_split |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() |
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
}
| {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
} | conditional_block |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) |
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
}
| {
self.proxy.wakeup_event_loop();
} | identifier_body |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn | (mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
}
| with_title | identifier_name |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 core::mem;
use core::slice;
pub unsafe trait Safe {}
pub trait AsBytes {
fn as_bytes(&self) -> &[u8];
fn as_mut_bytes(&mut self) -> &mut [u8];
}
impl<T: Safe> AsBytes for [T] {
#[inline]
fn as_bytes(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
}
#[inline]
fn as_mut_bytes(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
} |
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {} | } | random_line_split |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 core::mem;
use core::slice;
pub unsafe trait Safe {}
pub trait AsBytes {
fn as_bytes(&self) -> &[u8];
fn as_mut_bytes(&mut self) -> &mut [u8];
}
impl<T: Safe> AsBytes for [T] {
#[inline]
fn as_bytes(&self) -> &[u8] |
#[inline]
fn as_mut_bytes(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
}
}
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {}
| {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
} | identifier_body |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 core::mem;
use core::slice;
pub unsafe trait Safe {}
pub trait AsBytes {
fn as_bytes(&self) -> &[u8];
fn as_mut_bytes(&mut self) -> &mut [u8];
}
impl<T: Safe> AsBytes for [T] {
#[inline]
fn as_bytes(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
}
#[inline]
fn | (&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
}
}
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {}
| as_mut_bytes | identifier_name |
problem.rs | struct Container(i32, i32);
// A trait which checks if 2 items are stored inside of container.
// Also retrieves first or last value.
trait Contains<A, B> {
fn contains(&self, &A, &B) -> bool; // Explicitly requires `A` and `B`.
fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`.
fn last(&self) -> i32; // Doesn't explicitly require `A` or `B`.
}
impl Contains<i32, i32> for Container {
// True if the numbers stored are equal.
fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
// Grab the first number.
fn first(&self) -> i32 { self.0 }
// Grab the last number.
fn | (&self) -> i32 { self.1 }
}
// `C` contains `A` and `B`. In light of that, having to express `A` and
// `B` again is a nuisance.
fn difference<A, B, C>(container: &C) -> i32 where
C: Contains<A, B> {
container.last() - container.first()
}
fn main() {
let number_1 = 3;
let number_2 = 10;
let container = Container(number_1, number_2);
println!("Does container contain {} and {}: {}",
&number_1, &number_2,
container.contains(&number_1, &number_2));
println!("First number: {}", container.first());
println!("Last number: {}", container.last());
println!("The difference is: {}", difference(&container));
}
| last | identifier_name |
problem.rs | struct Container(i32, i32);
// A trait which checks if 2 items are stored inside of container.
// Also retrieves first or last value.
trait Contains<A, B> {
fn contains(&self, &A, &B) -> bool; // Explicitly requires `A` and `B`.
fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`.
fn last(&self) -> i32; // Doesn't explicitly require `A` or `B`.
}
impl Contains<i32, i32> for Container {
// True if the numbers stored are equal.
fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
// Grab the first number.
fn first(&self) -> i32 { self.0 }
// Grab the last number.
fn last(&self) -> i32 { self.1 }
}
// `C` contains `A` and `B`. In light of that, having to express `A` and
// `B` again is a nuisance.
fn difference<A, B, C>(container: &C) -> i32 where
C: Contains<A, B> |
fn main() {
let number_1 = 3;
let number_2 = 10;
let container = Container(number_1, number_2);
println!("Does container contain {} and {}: {}",
&number_1, &number_2,
container.contains(&number_1, &number_2));
println!("First number: {}", container.first());
println!("Last number: {}", container.last());
println!("The difference is: {}", difference(&container));
}
| {
container.last() - container.first()
} | identifier_body |
problem.rs | struct Container(i32, i32);
// A trait which checks if 2 items are stored inside of container.
// Also retrieves first or last value.
trait Contains<A, B> { | }
impl Contains<i32, i32> for Container {
// True if the numbers stored are equal.
fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
// Grab the first number.
fn first(&self) -> i32 { self.0 }
// Grab the last number.
fn last(&self) -> i32 { self.1 }
}
// `C` contains `A` and `B`. In light of that, having to express `A` and
// `B` again is a nuisance.
fn difference<A, B, C>(container: &C) -> i32 where
C: Contains<A, B> {
container.last() - container.first()
}
fn main() {
let number_1 = 3;
let number_2 = 10;
let container = Container(number_1, number_2);
println!("Does container contain {} and {}: {}",
&number_1, &number_2,
container.contains(&number_1, &number_2));
println!("First number: {}", container.first());
println!("Last number: {}", container.last());
println!("The difference is: {}", difference(&container));
} | fn contains(&self, &A, &B) -> bool; // Explicitly requires `A` and `B`.
fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`.
fn last(&self) -> i32; // Doesn't explicitly require `A` or `B`. | random_line_split |
schema.rs | table! {
__diesel_schema_migrations (version) {
version -> VarChar,
run_on -> Timestamp,
}
}
pub struct NewMigration<'a>(pub &'a str);
use backend::Backend;
use expression::AsExpression;
use expression::helper_types::AsExpr;
use persistable::{Insertable, ColumnInsertValue, InsertValues};
impl<'update: 'a, 'a, DB> Insertable<__diesel_schema_migrations::table, DB>
for &'update NewMigration<'a> where
DB: Backend,
(ColumnInsertValue<
__diesel_schema_migrations::version,
AsExpr<&'a str, __diesel_schema_migrations::version>,
>,): InsertValues<DB>,
{
type Values = (ColumnInsertValue<
__diesel_schema_migrations::version,
AsExpr<&'a str, __diesel_schema_migrations::version>,
>,);
| }
} | fn values(self) -> Self::Values {
(ColumnInsertValue::Expression(
__diesel_schema_migrations::version,
AsExpression::<::types::VarChar>::as_expression(self.0),
),) | random_line_split |
schema.rs | table! {
__diesel_schema_migrations (version) {
version -> VarChar,
run_on -> Timestamp,
}
}
pub struct | <'a>(pub &'a str);
use backend::Backend;
use expression::AsExpression;
use expression::helper_types::AsExpr;
use persistable::{Insertable, ColumnInsertValue, InsertValues};
impl<'update: 'a, 'a, DB> Insertable<__diesel_schema_migrations::table, DB>
for &'update NewMigration<'a> where
DB: Backend,
(ColumnInsertValue<
__diesel_schema_migrations::version,
AsExpr<&'a str, __diesel_schema_migrations::version>,
>,): InsertValues<DB>,
{
type Values = (ColumnInsertValue<
__diesel_schema_migrations::version,
AsExpr<&'a str, __diesel_schema_migrations::version>,
>,);
fn values(self) -> Self::Values {
(ColumnInsertValue::Expression(
__diesel_schema_migrations::version,
AsExpression::<::types::VarChar>::as_expression(self.0),
),)
}
}
| NewMigration | identifier_name |
autobind.rs | // 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.
fn f<T>(x: Vec<T>) -> T { return x.into_iter().next().unwrap(); }
fn g(act: |Vec<int> | -> int) -> int |
pub fn main() {
assert_eq!(g(f), 1);
let f1: |Vec<String>| -> String = f;
assert_eq!(f1(vec!["x".to_string(), "y".to_string(), "z".to_string()]),
"x".to_string());
}
| { return act(vec!(1, 2, 3)); } | identifier_body |
autobind.rs | // 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.
fn f<T>(x: Vec<T>) -> T { return x.into_iter().next().unwrap(); }
fn g(act: |Vec<int> | -> int) -> int { return act(vec!(1, 2, 3)); }
pub fn main() {
assert_eq!(g(f), 1);
let f1: |Vec<String>| -> String = f;
assert_eq!(f1(vec!["x".to_string(), "y".to_string(), "z".to_string()]),
"x".to_string());
} | // | random_line_split |
autobind.rs | // 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.
fn | <T>(x: Vec<T>) -> T { return x.into_iter().next().unwrap(); }
fn g(act: |Vec<int> | -> int) -> int { return act(vec!(1, 2, 3)); }
pub fn main() {
assert_eq!(g(f), 1);
let f1: |Vec<String>| -> String = f;
assert_eq!(f1(vec!["x".to_string(), "y".to_string(), "z".to_string()]),
"x".to_string());
}
| f | identifier_name |
suggestions.rs | #[cfg(feature = "suggestions")]
use strsim;
/// Produces a string from a given list of possible values which is similar to
/// the passed in value `v` with a certain confidence.
/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
/// `Some("foo")`, whereas "blark" would yield `None`.
#[cfg(feature = "suggestions")]
#[cfg_attr(feature = "lints", allow(needless_lifetimes))]
pub fn | <'a, T, I>(v: &str,
possible_values: I)
-> Option<&'a str>
where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
{
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values.into_iter() {
let confidence = strsim::jaro_winkler(v, pv.as_ref());
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv.as_ref()));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
#[cfg(not(feature = "suggestions"))]
pub fn did_you_mean<'a, T, I>(_: &str,
_: I)
-> Option<&'a str>
where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
{
None
}
/// A helper to determine message formatting
pub enum DidYouMeanMessageStyle {
/// Suggested value is a long flag
LongFlag,
/// Suggested value is one of various possible values
EnumValue,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn did_you_mean_possible_values() {
let p_vals = ["test", "possible", "values"];
assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
}
}
| did_you_mean | identifier_name |
suggestions.rs | #[cfg(feature = "suggestions")]
use strsim;
/// Produces a string from a given list of possible values which is similar to
/// the passed in value `v` with a certain confidence.
/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
/// `Some("foo")`, whereas "blark" would yield `None`.
#[cfg(feature = "suggestions")]
#[cfg_attr(feature = "lints", allow(needless_lifetimes))]
pub fn did_you_mean<'a, T, I>(v: &str,
possible_values: I)
-> Option<&'a str>
where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
{
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values.into_iter() {
let confidence = strsim::jaro_winkler(v, pv.as_ref());
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv.as_ref()));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
#[cfg(not(feature = "suggestions"))]
pub fn did_you_mean<'a, T, I>(_: &str,
_: I)
-> Option<&'a str>
where T: AsRef<str> + 'a, | /// A helper to determine message formatting
pub enum DidYouMeanMessageStyle {
/// Suggested value is a long flag
LongFlag,
/// Suggested value is one of various possible values
EnumValue,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn did_you_mean_possible_values() {
let p_vals = ["test", "possible", "values"];
assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
}
} | I: IntoIterator<Item = &'a T>
{
None
}
| random_line_split |
suggestions.rs | #[cfg(feature = "suggestions")]
use strsim;
/// Produces a string from a given list of possible values which is similar to
/// the passed in value `v` with a certain confidence.
/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
/// `Some("foo")`, whereas "blark" would yield `None`.
#[cfg(feature = "suggestions")]
#[cfg_attr(feature = "lints", allow(needless_lifetimes))]
pub fn did_you_mean<'a, T, I>(v: &str,
possible_values: I)
-> Option<&'a str>
where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
|
#[cfg(not(feature = "suggestions"))]
pub fn did_you_mean<'a, T, I>(_: &str,
_: I)
-> Option<&'a str>
where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
{
None
}
/// A helper to determine message formatting
pub enum DidYouMeanMessageStyle {
/// Suggested value is a long flag
LongFlag,
/// Suggested value is one of various possible values
EnumValue,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn did_you_mean_possible_values() {
let p_vals = ["test", "possible", "values"];
assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
}
}
| {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values.into_iter() {
let confidence = strsim::jaro_winkler(v, pv.as_ref());
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv.as_ref()));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
} | identifier_body |
workqueue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, XorShiftRng, weak_rng};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use task::spawn_named;
use task_state;
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker to measure the heap size of its TLS using the supplied function.
HeapSizeOfTLS(fn() -> usize),
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
HeapSizeOfTLS(usize),
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
const SPINS_UNTIL_BACKOFF: u32 = 128;
const BACKOFF_INCREMENT_IN_US: u32 = 5;
const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6;
fn next_power_of_two(mut v: u32) -> u32 {
v -= 1;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v += 1;
v
}
impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1;
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
WorkerMsg::HeapSizeOfTLS(f) => {
self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap();
continue;
}
};
let mut back_off_sleep = 0 as u32;
// We're off!
'outer: loop {
let work_unit;
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
loop {
// Don't just use `rand % len` because that's slow on ARM.
let mut victim;
loop {
victim = self.rng.next_u32() & deque_index_mask;
if (victim as usize) < self.other_deques.len() {
break
}
}
match self.other_deques[victim as usize].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
if back_off_sleep >= BACKOFF_INCREMENT_IN_US *
BACKOFFS_UNTIL_CONTROL_CHECK {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => break 'outer,
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
}
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
i = 0
} else {
i += 1
}
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
// queue_data is kept alive in the stack frame of
// WorkQueue::run until we send the
// SupervisorMsg::ReturnDeque message below.
queue_data: unsafe { &*queue_data },
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::Release) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: &'a QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::Relaxed));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data(&self) -> &'a QueueData |
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
}
impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for (i, mut thread) in threads.iter_mut().enumerate() {
for (j, info) in infos.iter().enumerate() {
if i!= j {
thread.other_deques.push(info.thief.clone())
}
}
assert!(thread.other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i + 1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self, data: &QueueData) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in &mut self.workers {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in &self.workers {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
/// Synchronously measure memory usage of any thread-local storage.
pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> {
// Tell the workers to measure themselves.
for worker in &self.workers {
worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap()
}
// Wait for the workers to finish measuring themselves.
let mut sizes = vec![];
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::HeapSizeOfTLS(size) => {
sizes.push(size);
}
_ => panic!("unexpected message!"),
}
}
sizes
}
pub fn shutdown(&mut self) {
for worker in &self.workers {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
| {
self.queue_data
} | identifier_body |
workqueue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, XorShiftRng, weak_rng};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use task::spawn_named;
use task_state;
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker to measure the heap size of its TLS using the supplied function.
HeapSizeOfTLS(fn() -> usize),
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
HeapSizeOfTLS(usize),
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
const SPINS_UNTIL_BACKOFF: u32 = 128;
const BACKOFF_INCREMENT_IN_US: u32 = 5;
const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6;
fn next_power_of_two(mut v: u32) -> u32 {
v -= 1;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v += 1;
v
}
impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1;
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
WorkerMsg::HeapSizeOfTLS(f) => {
self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap();
continue;
}
};
let mut back_off_sleep = 0 as u32;
// We're off!
'outer: loop {
let work_unit;
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
loop {
// Don't just use `rand % len` because that's slow on ARM.
let mut victim; | break
}
}
match self.other_deques[victim as usize].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
if back_off_sleep >= BACKOFF_INCREMENT_IN_US *
BACKOFFS_UNTIL_CONTROL_CHECK {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => break 'outer,
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
}
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
i = 0
} else {
i += 1
}
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
// queue_data is kept alive in the stack frame of
// WorkQueue::run until we send the
// SupervisorMsg::ReturnDeque message below.
queue_data: unsafe { &*queue_data },
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::Release) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: &'a QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::Relaxed));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data(&self) -> &'a QueueData {
self.queue_data
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
}
impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for (i, mut thread) in threads.iter_mut().enumerate() {
for (j, info) in infos.iter().enumerate() {
if i!= j {
thread.other_deques.push(info.thief.clone())
}
}
assert!(thread.other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i + 1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self, data: &QueueData) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in &mut self.workers {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in &self.workers {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
/// Synchronously measure memory usage of any thread-local storage.
pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> {
// Tell the workers to measure themselves.
for worker in &self.workers {
worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap()
}
// Wait for the workers to finish measuring themselves.
let mut sizes = vec![];
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::HeapSizeOfTLS(size) => {
sizes.push(size);
}
_ => panic!("unexpected message!"),
}
}
sizes
}
pub fn shutdown(&mut self) {
for worker in &self.workers {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
} | loop {
victim = self.rng.next_u32() & deque_index_mask;
if (victim as usize) < self.other_deques.len() { | random_line_split |
workqueue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, XorShiftRng, weak_rng};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use task::spawn_named;
use task_state;
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker to measure the heap size of its TLS using the supplied function.
HeapSizeOfTLS(fn() -> usize),
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
HeapSizeOfTLS(usize),
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
const SPINS_UNTIL_BACKOFF: u32 = 128;
const BACKOFF_INCREMENT_IN_US: u32 = 5;
const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6;
fn | (mut v: u32) -> u32 {
v -= 1;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v += 1;
v
}
impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1;
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
WorkerMsg::HeapSizeOfTLS(f) => {
self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap();
continue;
}
};
let mut back_off_sleep = 0 as u32;
// We're off!
'outer: loop {
let work_unit;
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
loop {
// Don't just use `rand % len` because that's slow on ARM.
let mut victim;
loop {
victim = self.rng.next_u32() & deque_index_mask;
if (victim as usize) < self.other_deques.len() {
break
}
}
match self.other_deques[victim as usize].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
if back_off_sleep >= BACKOFF_INCREMENT_IN_US *
BACKOFFS_UNTIL_CONTROL_CHECK {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => break 'outer,
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
}
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
i = 0
} else {
i += 1
}
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
// queue_data is kept alive in the stack frame of
// WorkQueue::run until we send the
// SupervisorMsg::ReturnDeque message below.
queue_data: unsafe { &*queue_data },
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::Release) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: &'a QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::Relaxed));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data(&self) -> &'a QueueData {
self.queue_data
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
}
impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for (i, mut thread) in threads.iter_mut().enumerate() {
for (j, info) in infos.iter().enumerate() {
if i!= j {
thread.other_deques.push(info.thief.clone())
}
}
assert!(thread.other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i + 1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self, data: &QueueData) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in &mut self.workers {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in &self.workers {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
/// Synchronously measure memory usage of any thread-local storage.
pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> {
// Tell the workers to measure themselves.
for worker in &self.workers {
worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap()
}
// Wait for the workers to finish measuring themselves.
let mut sizes = vec![];
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::HeapSizeOfTLS(size) => {
sizes.push(size);
}
_ => panic!("unexpected message!"),
}
}
sizes
}
pub fn shutdown(&mut self) {
for worker in &self.workers {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
| next_power_of_two | identifier_name |
mod.rs | // 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.
pub use syntax::diagnostic;
use back::link;
use driver::driver::{Input, FileInput, StrInput};
use driver::session::{Session, build_session};
use lint::Lint;
use lint;
use metadata;
use std::any::AnyRefExt;
use std::io;
use std::os;
use std::task::TaskBuilder;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
use getopts;
pub mod driver;
pub mod session;
pub mod config;
pub fn main_args(args: &[String]) -> int {
let owned_args = args.to_vec();
monitor(proc() run_compiler(owned_args.as_slice()));
0
}
static BUG_REPORT_URL: &'static str =
"http://doc.rust-lang.org/complement-bugreport.html";
fn | (args: &[String]) {
let matches = match handle_options(Vec::from_slice(args)) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS);
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(code.as_slice()) {
Some(ref description) => {
println!("{}", description);
}
None => {
early_error(format!("no extended information for {}", code).as_slice());
}
}
return;
},
None => ()
}
let sopts = config::build_session_options(&matches);
let (input, input_file_path) = match matches.free.len() {
0u => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
ls.register_builtin(None);
describe_lints(&ls, false);
return;
}
early_error("no input filename given");
}
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = String::from_utf8(contents).unwrap();
(StrInput(src), None)
} else {
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => early_error("multiple input filenames provided")
};
let sess = build_session(sopts, input_file_path, descriptions);
let cfg = config::build_configuration(&sess);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let pretty = matches.opt_default("pretty", "normal").map(|a| {
parse_pretty(&sess, a.as_slice())
});
match pretty {
Some((ppm, opt_uii)) => {
driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
FileInput(ref ifile) => {
let mut stdout = io::stdout();
list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
StrInput(_) => {
early_error("can not list metadata for stdin");
}
}
return;
}
if print_crate_info(&sess, &input, &odir, &ofile) {
return;
}
driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
}
/// Prints version information and returns None on success or an error
/// message on failure.
pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
None => false,
Some("verbose") => true,
Some(s) => return Some(format!("Unrecognized argument: {}", s))
};
println!("{} {}", binary, env!("CFG_VERSION"));
if verbose {
println!("binary: {}", binary);
println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
println!("host: {}", driver::host_triple());
println!("release: {}", env!("CFG_RELEASE"));
}
None
}
fn usage() {
let message = format!("Usage: rustc [OPTIONS] INPUT");
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message.as_slice(),
config::optgroups().as_slice()));
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(&y.name),
r => r,
}
});
lints
}
let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
// FIXME (#7043): We should use the width in character cells rather than
// the number of codepoints.
let max_name_len = plugin.iter().chain(builtin.iter())
.map(|&s| s.name.char_len())
.max().unwrap_or(0);
let padded = |x: &str| {
" ".repeat(max_name_len - x.char_len()).append(x)
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7s} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7s} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints.move_iter() {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7s} {}",
padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
match (loaded_plugins, plugin.len()) {
(false, 0) => {
println!("Compiler plugins can provide additional lints. To see a listing of these, \
re-run `rustc -W help` with a crate filename.");
}
(false, _) => fail!("didn't load lint plugins but got them anyway!"),
(true, 0) => println!("This crate does not load any lint plugins."),
(true, _) => {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = config::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = config::basic_codegen_options();
for &(name, parser, desc) in config::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.shift().unwrap();
if args.is_empty() {
usage();
return None;
}
let matches =
match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
early_error(f.to_string().as_slice());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage();
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| x.as_slice() == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x.as_slice() == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
match version("rustc", &matches) {
Some(err) => early_error(err.as_slice()),
None => return None
}
}
Some(matches)
}
fn print_crate_info(sess: &Session,
input: &Input,
odir: &Option<Path>,
ofile: &Option<Path>)
-> bool {
let (crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_name || crate_file_name {
let attrs = parse_crate_attrs(sess, input);
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs.as_slice(),
sess);
let id = link::find_crate_name(Some(sess), attrs.as_slice(), input);
if crate_name {
println!("{}", id);
}
if crate_file_name {
let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
let metadata = driver::collect_crate_metadata(sess, attrs.as_slice());
*sess.crate_metadata.borrow_mut() = metadata;
for &style in crate_types.iter() {
let fname = link::filename_for_input(sess, style, id.as_slice(),
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
true
} else {
false
}
}
#[deriving(PartialEq, Show)]
pub enum PpSourceMode {
PpmNormal,
PpmExpanded,
PpmTyped,
PpmIdentified,
PpmExpandedIdentified,
}
#[deriving(PartialEq, Show)]
pub enum PpMode {
PpmSource(PpSourceMode),
PpmFlowGraph,
}
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
let mut split = name.splitn(1, '=');
let first = split.next().unwrap();
let opt_second = split.next();
let first = match first {
"normal" => PpmSource(PpmNormal),
"expanded" => PpmSource(PpmExpanded),
"typed" => PpmSource(PpmTyped),
"expanded,identified" => PpmSource(PpmExpandedIdentified),
"identified" => PpmSource(PpmIdentified),
"flowgraph" => PpmFlowGraph,
_ => {
sess.fatal(format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
or `expanded,identified`; got {}", name).as_slice());
}
};
let opt_second = opt_second.and_then::<driver::UserIdentifiedItem>(from_str);
(first, opt_second)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
pub fn early_error(msg: &str) ->! {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Fatal);
fail!(diagnostic::FatalError);
}
pub fn early_warn(msg: &str) {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Warning);
}
pub fn list_metadata(sess: &Session, path: &Path,
out: &mut io::Writer) -> io::IoResult<()> {
metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc():Send) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
let mut task = TaskBuilder::new().named("rustc").stderr(box w);
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task = task.stack_size(STACK_SIZE);
}
match task.try(f) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
None,
diagnostic::Bug);
}
let xs = [
"the compiler hit an unexpected failure path. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
"run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
];
for note in xs.iter() {
emitter.emit(None, note.as_slice(), None, diagnostic::Note)
}
match r.read_to_string() {
Ok(s) => println!("{}", s),
Err(e) => {
emitter.emit(None,
format!("failed to read internal \
stderr: {}",
e).as_slice(),
None,
diagnostic::Error)
}
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(box io::util::NullWriter);
fail!();
}
}
}
| run_compiler | identifier_name |
mod.rs | // 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.
pub use syntax::diagnostic;
use back::link;
use driver::driver::{Input, FileInput, StrInput};
use driver::session::{Session, build_session};
use lint::Lint;
use lint;
use metadata;
use std::any::AnyRefExt;
use std::io;
use std::os;
use std::task::TaskBuilder;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
use getopts;
pub mod driver;
pub mod session;
pub mod config;
pub fn main_args(args: &[String]) -> int {
let owned_args = args.to_vec();
monitor(proc() run_compiler(owned_args.as_slice()));
0
}
static BUG_REPORT_URL: &'static str =
"http://doc.rust-lang.org/complement-bugreport.html";
fn run_compiler(args: &[String]) { |
let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS);
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(code.as_slice()) {
Some(ref description) => {
println!("{}", description);
}
None => {
early_error(format!("no extended information for {}", code).as_slice());
}
}
return;
},
None => ()
}
let sopts = config::build_session_options(&matches);
let (input, input_file_path) = match matches.free.len() {
0u => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
ls.register_builtin(None);
describe_lints(&ls, false);
return;
}
early_error("no input filename given");
}
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = String::from_utf8(contents).unwrap();
(StrInput(src), None)
} else {
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => early_error("multiple input filenames provided")
};
let sess = build_session(sopts, input_file_path, descriptions);
let cfg = config::build_configuration(&sess);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let pretty = matches.opt_default("pretty", "normal").map(|a| {
parse_pretty(&sess, a.as_slice())
});
match pretty {
Some((ppm, opt_uii)) => {
driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
FileInput(ref ifile) => {
let mut stdout = io::stdout();
list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
StrInput(_) => {
early_error("can not list metadata for stdin");
}
}
return;
}
if print_crate_info(&sess, &input, &odir, &ofile) {
return;
}
driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
}
/// Prints version information and returns None on success or an error
/// message on failure.
pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
None => false,
Some("verbose") => true,
Some(s) => return Some(format!("Unrecognized argument: {}", s))
};
println!("{} {}", binary, env!("CFG_VERSION"));
if verbose {
println!("binary: {}", binary);
println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
println!("host: {}", driver::host_triple());
println!("release: {}", env!("CFG_RELEASE"));
}
None
}
fn usage() {
let message = format!("Usage: rustc [OPTIONS] INPUT");
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message.as_slice(),
config::optgroups().as_slice()));
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(&y.name),
r => r,
}
});
lints
}
let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
// FIXME (#7043): We should use the width in character cells rather than
// the number of codepoints.
let max_name_len = plugin.iter().chain(builtin.iter())
.map(|&s| s.name.char_len())
.max().unwrap_or(0);
let padded = |x: &str| {
" ".repeat(max_name_len - x.char_len()).append(x)
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7s} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7s} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints.move_iter() {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7s} {}",
padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
match (loaded_plugins, plugin.len()) {
(false, 0) => {
println!("Compiler plugins can provide additional lints. To see a listing of these, \
re-run `rustc -W help` with a crate filename.");
}
(false, _) => fail!("didn't load lint plugins but got them anyway!"),
(true, 0) => println!("This crate does not load any lint plugins."),
(true, _) => {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = config::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = config::basic_codegen_options();
for &(name, parser, desc) in config::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.shift().unwrap();
if args.is_empty() {
usage();
return None;
}
let matches =
match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
early_error(f.to_string().as_slice());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage();
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| x.as_slice() == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x.as_slice() == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
match version("rustc", &matches) {
Some(err) => early_error(err.as_slice()),
None => return None
}
}
Some(matches)
}
fn print_crate_info(sess: &Session,
input: &Input,
odir: &Option<Path>,
ofile: &Option<Path>)
-> bool {
let (crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_name || crate_file_name {
let attrs = parse_crate_attrs(sess, input);
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs.as_slice(),
sess);
let id = link::find_crate_name(Some(sess), attrs.as_slice(), input);
if crate_name {
println!("{}", id);
}
if crate_file_name {
let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
let metadata = driver::collect_crate_metadata(sess, attrs.as_slice());
*sess.crate_metadata.borrow_mut() = metadata;
for &style in crate_types.iter() {
let fname = link::filename_for_input(sess, style, id.as_slice(),
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
true
} else {
false
}
}
#[deriving(PartialEq, Show)]
pub enum PpSourceMode {
PpmNormal,
PpmExpanded,
PpmTyped,
PpmIdentified,
PpmExpandedIdentified,
}
#[deriving(PartialEq, Show)]
pub enum PpMode {
PpmSource(PpSourceMode),
PpmFlowGraph,
}
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
let mut split = name.splitn(1, '=');
let first = split.next().unwrap();
let opt_second = split.next();
let first = match first {
"normal" => PpmSource(PpmNormal),
"expanded" => PpmSource(PpmExpanded),
"typed" => PpmSource(PpmTyped),
"expanded,identified" => PpmSource(PpmExpandedIdentified),
"identified" => PpmSource(PpmIdentified),
"flowgraph" => PpmFlowGraph,
_ => {
sess.fatal(format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
or `expanded,identified`; got {}", name).as_slice());
}
};
let opt_second = opt_second.and_then::<driver::UserIdentifiedItem>(from_str);
(first, opt_second)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
pub fn early_error(msg: &str) ->! {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Fatal);
fail!(diagnostic::FatalError);
}
pub fn early_warn(msg: &str) {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Warning);
}
pub fn list_metadata(sess: &Session, path: &Path,
out: &mut io::Writer) -> io::IoResult<()> {
metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc():Send) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
let mut task = TaskBuilder::new().named("rustc").stderr(box w);
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task = task.stack_size(STACK_SIZE);
}
match task.try(f) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
None,
diagnostic::Bug);
}
let xs = [
"the compiler hit an unexpected failure path. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
"run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
];
for note in xs.iter() {
emitter.emit(None, note.as_slice(), None, diagnostic::Note)
}
match r.read_to_string() {
Ok(s) => println!("{}", s),
Err(e) => {
emitter.emit(None,
format!("failed to read internal \
stderr: {}",
e).as_slice(),
None,
diagnostic::Error)
}
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(box io::util::NullWriter);
fail!();
}
}
} | let matches = match handle_options(Vec::from_slice(args)) {
Some(matches) => matches,
None => return
}; | random_line_split |
mod.rs | // 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.
pub use syntax::diagnostic;
use back::link;
use driver::driver::{Input, FileInput, StrInput};
use driver::session::{Session, build_session};
use lint::Lint;
use lint;
use metadata;
use std::any::AnyRefExt;
use std::io;
use std::os;
use std::task::TaskBuilder;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
use getopts;
pub mod driver;
pub mod session;
pub mod config;
pub fn main_args(args: &[String]) -> int {
let owned_args = args.to_vec();
monitor(proc() run_compiler(owned_args.as_slice()));
0
}
static BUG_REPORT_URL: &'static str =
"http://doc.rust-lang.org/complement-bugreport.html";
fn run_compiler(args: &[String]) {
let matches = match handle_options(Vec::from_slice(args)) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS);
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(code.as_slice()) {
Some(ref description) => {
println!("{}", description);
}
None => {
early_error(format!("no extended information for {}", code).as_slice());
}
}
return;
},
None => ()
}
let sopts = config::build_session_options(&matches);
let (input, input_file_path) = match matches.free.len() {
0u => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
ls.register_builtin(None);
describe_lints(&ls, false);
return;
}
early_error("no input filename given");
}
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = String::from_utf8(contents).unwrap();
(StrInput(src), None)
} else {
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => early_error("multiple input filenames provided")
};
let sess = build_session(sopts, input_file_path, descriptions);
let cfg = config::build_configuration(&sess);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let pretty = matches.opt_default("pretty", "normal").map(|a| {
parse_pretty(&sess, a.as_slice())
});
match pretty {
Some((ppm, opt_uii)) => {
driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
FileInput(ref ifile) => {
let mut stdout = io::stdout();
list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
StrInput(_) => |
}
return;
}
if print_crate_info(&sess, &input, &odir, &ofile) {
return;
}
driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
}
/// Prints version information and returns None on success or an error
/// message on failure.
pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
None => false,
Some("verbose") => true,
Some(s) => return Some(format!("Unrecognized argument: {}", s))
};
println!("{} {}", binary, env!("CFG_VERSION"));
if verbose {
println!("binary: {}", binary);
println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
println!("host: {}", driver::host_triple());
println!("release: {}", env!("CFG_RELEASE"));
}
None
}
fn usage() {
let message = format!("Usage: rustc [OPTIONS] INPUT");
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message.as_slice(),
config::optgroups().as_slice()));
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(&y.name),
r => r,
}
});
lints
}
let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
// FIXME (#7043): We should use the width in character cells rather than
// the number of codepoints.
let max_name_len = plugin.iter().chain(builtin.iter())
.map(|&s| s.name.char_len())
.max().unwrap_or(0);
let padded = |x: &str| {
" ".repeat(max_name_len - x.char_len()).append(x)
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7s} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7s} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints.move_iter() {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7s} {}",
padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
match (loaded_plugins, plugin.len()) {
(false, 0) => {
println!("Compiler plugins can provide additional lints. To see a listing of these, \
re-run `rustc -W help` with a crate filename.");
}
(false, _) => fail!("didn't load lint plugins but got them anyway!"),
(true, 0) => println!("This crate does not load any lint plugins."),
(true, _) => {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = config::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = config::basic_codegen_options();
for &(name, parser, desc) in config::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.shift().unwrap();
if args.is_empty() {
usage();
return None;
}
let matches =
match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
early_error(f.to_string().as_slice());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage();
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| x.as_slice() == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x.as_slice() == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
match version("rustc", &matches) {
Some(err) => early_error(err.as_slice()),
None => return None
}
}
Some(matches)
}
fn print_crate_info(sess: &Session,
input: &Input,
odir: &Option<Path>,
ofile: &Option<Path>)
-> bool {
let (crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_name || crate_file_name {
let attrs = parse_crate_attrs(sess, input);
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs.as_slice(),
sess);
let id = link::find_crate_name(Some(sess), attrs.as_slice(), input);
if crate_name {
println!("{}", id);
}
if crate_file_name {
let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
let metadata = driver::collect_crate_metadata(sess, attrs.as_slice());
*sess.crate_metadata.borrow_mut() = metadata;
for &style in crate_types.iter() {
let fname = link::filename_for_input(sess, style, id.as_slice(),
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
true
} else {
false
}
}
#[deriving(PartialEq, Show)]
pub enum PpSourceMode {
PpmNormal,
PpmExpanded,
PpmTyped,
PpmIdentified,
PpmExpandedIdentified,
}
#[deriving(PartialEq, Show)]
pub enum PpMode {
PpmSource(PpSourceMode),
PpmFlowGraph,
}
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
let mut split = name.splitn(1, '=');
let first = split.next().unwrap();
let opt_second = split.next();
let first = match first {
"normal" => PpmSource(PpmNormal),
"expanded" => PpmSource(PpmExpanded),
"typed" => PpmSource(PpmTyped),
"expanded,identified" => PpmSource(PpmExpandedIdentified),
"identified" => PpmSource(PpmIdentified),
"flowgraph" => PpmFlowGraph,
_ => {
sess.fatal(format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
or `expanded,identified`; got {}", name).as_slice());
}
};
let opt_second = opt_second.and_then::<driver::UserIdentifiedItem>(from_str);
(first, opt_second)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
pub fn early_error(msg: &str) ->! {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Fatal);
fail!(diagnostic::FatalError);
}
pub fn early_warn(msg: &str) {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Warning);
}
pub fn list_metadata(sess: &Session, path: &Path,
out: &mut io::Writer) -> io::IoResult<()> {
metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc():Send) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
let mut task = TaskBuilder::new().named("rustc").stderr(box w);
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task = task.stack_size(STACK_SIZE);
}
match task.try(f) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
None,
diagnostic::Bug);
}
let xs = [
"the compiler hit an unexpected failure path. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
"run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
];
for note in xs.iter() {
emitter.emit(None, note.as_slice(), None, diagnostic::Note)
}
match r.read_to_string() {
Ok(s) => println!("{}", s),
Err(e) => {
emitter.emit(None,
format!("failed to read internal \
stderr: {}",
e).as_slice(),
None,
diagnostic::Error)
}
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(box io::util::NullWriter);
fail!();
}
}
}
| {
early_error("can not list metadata for stdin");
} | conditional_block |
mod.rs | // 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.
pub use syntax::diagnostic;
use back::link;
use driver::driver::{Input, FileInput, StrInput};
use driver::session::{Session, build_session};
use lint::Lint;
use lint;
use metadata;
use std::any::AnyRefExt;
use std::io;
use std::os;
use std::task::TaskBuilder;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
use getopts;
pub mod driver;
pub mod session;
pub mod config;
pub fn main_args(args: &[String]) -> int {
let owned_args = args.to_vec();
monitor(proc() run_compiler(owned_args.as_slice()));
0
}
static BUG_REPORT_URL: &'static str =
"http://doc.rust-lang.org/complement-bugreport.html";
fn run_compiler(args: &[String]) {
let matches = match handle_options(Vec::from_slice(args)) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS);
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(code.as_slice()) {
Some(ref description) => {
println!("{}", description);
}
None => {
early_error(format!("no extended information for {}", code).as_slice());
}
}
return;
},
None => ()
}
let sopts = config::build_session_options(&matches);
let (input, input_file_path) = match matches.free.len() {
0u => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
ls.register_builtin(None);
describe_lints(&ls, false);
return;
}
early_error("no input filename given");
}
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = String::from_utf8(contents).unwrap();
(StrInput(src), None)
} else {
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => early_error("multiple input filenames provided")
};
let sess = build_session(sopts, input_file_path, descriptions);
let cfg = config::build_configuration(&sess);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let pretty = matches.opt_default("pretty", "normal").map(|a| {
parse_pretty(&sess, a.as_slice())
});
match pretty {
Some((ppm, opt_uii)) => {
driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
FileInput(ref ifile) => {
let mut stdout = io::stdout();
list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
StrInput(_) => {
early_error("can not list metadata for stdin");
}
}
return;
}
if print_crate_info(&sess, &input, &odir, &ofile) {
return;
}
driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
}
/// Prints version information and returns None on success or an error
/// message on failure.
pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> |
fn usage() {
let message = format!("Usage: rustc [OPTIONS] INPUT");
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message.as_slice(),
config::optgroups().as_slice()));
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(&y.name),
r => r,
}
});
lints
}
let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
// FIXME (#7043): We should use the width in character cells rather than
// the number of codepoints.
let max_name_len = plugin.iter().chain(builtin.iter())
.map(|&s| s.name.char_len())
.max().unwrap_or(0);
let padded = |x: &str| {
" ".repeat(max_name_len - x.char_len()).append(x)
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7s} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7s} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints.move_iter() {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7s} {}",
padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
match (loaded_plugins, plugin.len()) {
(false, 0) => {
println!("Compiler plugins can provide additional lints. To see a listing of these, \
re-run `rustc -W help` with a crate filename.");
}
(false, _) => fail!("didn't load lint plugins but got them anyway!"),
(true, 0) => println!("This crate does not load any lint plugins."),
(true, _) => {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = config::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = config::basic_codegen_options();
for &(name, parser, desc) in config::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.shift().unwrap();
if args.is_empty() {
usage();
return None;
}
let matches =
match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
early_error(f.to_string().as_slice());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage();
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| x.as_slice() == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x.as_slice() == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
match version("rustc", &matches) {
Some(err) => early_error(err.as_slice()),
None => return None
}
}
Some(matches)
}
fn print_crate_info(sess: &Session,
input: &Input,
odir: &Option<Path>,
ofile: &Option<Path>)
-> bool {
let (crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_name || crate_file_name {
let attrs = parse_crate_attrs(sess, input);
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs.as_slice(),
sess);
let id = link::find_crate_name(Some(sess), attrs.as_slice(), input);
if crate_name {
println!("{}", id);
}
if crate_file_name {
let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
let metadata = driver::collect_crate_metadata(sess, attrs.as_slice());
*sess.crate_metadata.borrow_mut() = metadata;
for &style in crate_types.iter() {
let fname = link::filename_for_input(sess, style, id.as_slice(),
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
true
} else {
false
}
}
#[deriving(PartialEq, Show)]
pub enum PpSourceMode {
PpmNormal,
PpmExpanded,
PpmTyped,
PpmIdentified,
PpmExpandedIdentified,
}
#[deriving(PartialEq, Show)]
pub enum PpMode {
PpmSource(PpSourceMode),
PpmFlowGraph,
}
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
let mut split = name.splitn(1, '=');
let first = split.next().unwrap();
let opt_second = split.next();
let first = match first {
"normal" => PpmSource(PpmNormal),
"expanded" => PpmSource(PpmExpanded),
"typed" => PpmSource(PpmTyped),
"expanded,identified" => PpmSource(PpmExpandedIdentified),
"identified" => PpmSource(PpmIdentified),
"flowgraph" => PpmFlowGraph,
_ => {
sess.fatal(format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
or `expanded,identified`; got {}", name).as_slice());
}
};
let opt_second = opt_second.and_then::<driver::UserIdentifiedItem>(from_str);
(first, opt_second)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
pub fn early_error(msg: &str) ->! {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Fatal);
fail!(diagnostic::FatalError);
}
pub fn early_warn(msg: &str) {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Warning);
}
pub fn list_metadata(sess: &Session, path: &Path,
out: &mut io::Writer) -> io::IoResult<()> {
metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc():Send) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
let mut task = TaskBuilder::new().named("rustc").stderr(box w);
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task = task.stack_size(STACK_SIZE);
}
match task.try(f) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
None,
diagnostic::Bug);
}
let xs = [
"the compiler hit an unexpected failure path. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
"run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
];
for note in xs.iter() {
emitter.emit(None, note.as_slice(), None, diagnostic::Note)
}
match r.read_to_string() {
Ok(s) => println!("{}", s),
Err(e) => {
emitter.emit(None,
format!("failed to read internal \
stderr: {}",
e).as_slice(),
None,
diagnostic::Error)
}
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(box io::util::NullWriter);
fail!();
}
}
}
| {
let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
None => false,
Some("verbose") => true,
Some(s) => return Some(format!("Unrecognized argument: {}", s))
};
println!("{} {}", binary, env!("CFG_VERSION"));
if verbose {
println!("binary: {}", binary);
println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
println!("host: {}", driver::host_triple());
println!("release: {}", env!("CFG_RELEASE"));
}
None
} | identifier_body |
combine_array_len.rs | // Copyright 2017 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.
| }
fn main() {
assert_eq!(norm2([3.0, 4.0]), 5.0*5.0);
}
// END RUST SOURCE
// START rustc.norm2.InstCombine.before.mir
// _4 = Len(_1);
// ...
// _8 = Len(_1);
// END rustc.norm2.InstCombine.before.mir
// START rustc.norm2.InstCombine.after.mir
// _4 = const 2usize;
// ...
// _8 = const 2usize;
// END rustc.norm2.InstCombine.after.mir | fn norm2(x: [f32; 2]) -> f32 {
let a = x[0];
let b = x[1];
a*a + b*b | random_line_split |
combine_array_len.rs | // Copyright 2017 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.
fn norm2(x: [f32; 2]) -> f32 {
let a = x[0];
let b = x[1];
a*a + b*b
}
fn main() |
// END RUST SOURCE
// START rustc.norm2.InstCombine.before.mir
// _4 = Len(_1);
// ...
// _8 = Len(_1);
// END rustc.norm2.InstCombine.before.mir
// START rustc.norm2.InstCombine.after.mir
// _4 = const 2usize;
// ...
// _8 = const 2usize;
// END rustc.norm2.InstCombine.after.mir
| {
assert_eq!(norm2([3.0, 4.0]), 5.0*5.0);
} | identifier_body |
combine_array_len.rs | // Copyright 2017 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.
fn norm2(x: [f32; 2]) -> f32 {
let a = x[0];
let b = x[1];
a*a + b*b
}
fn | () {
assert_eq!(norm2([3.0, 4.0]), 5.0*5.0);
}
// END RUST SOURCE
// START rustc.norm2.InstCombine.before.mir
// _4 = Len(_1);
// ...
// _8 = Len(_1);
// END rustc.norm2.InstCombine.before.mir
// START rustc.norm2.InstCombine.after.mir
// _4 = const 2usize;
// ...
// _8 = const 2usize;
// END rustc.norm2.InstCombine.after.mir
| main | identifier_name |
pattern_type_mismatch.rs | use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::last_path_segment;
use rustc_hir::{
intravisit, Body, Expr, ExprKind, FnDecl, HirId, LocalSource, MatchSource, Mutability, Pat, PatField, PatKind,
QPath, Stmt, StmtKind,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{AdtDef, FieldDef, Ty, TyKind, VariantDef};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use std::iter;
declare_clippy_lint! {
/// ### What it does
/// Checks for patterns that aren't exact representations of the types
/// they are applied to.
///
/// To satisfy this lint, you will have to adjust either the expression that is matched
/// against or the pattern itself, as well as the bindings that are introduced by the
/// adjusted patterns. For matching you will have to either dereference the expression
/// with the `*` operator, or amend the patterns to explicitly match against `&<pattern>`
/// or `&mut <pattern>` depending on the reference mutability. For the bindings you need
/// to use the inverse. You can leave them as plain bindings if you wish for the value
/// to be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct
/// a reference into the matched structure.
///
/// If you are looking for a way to learn about ownership semantics in more detail, it
/// is recommended to look at IDE options available to you to highlight types, lifetimes
/// and reference semantics in your code. The available tooling would expose these things
/// in a general way even outside of the various pattern matching mechanics. Of course
/// this lint can still be used to highlight areas of interest and ensure a good understanding
/// of ownership semantics.
///
/// ### Why is this bad?
/// It isn't bad in general. But in some contexts it can be desirable
/// because it increases ownership hints in the code, and will guard against some changes
/// in ownership.
///
/// ### Example
/// This example shows the basic adjustments necessary to satisfy the lint. Note how
/// the matched expression is explicitly dereferenced with `*` and the `inner` variable
/// is bound to a shared borrow via `ref inner`.
///
/// ```rust,ignore
/// // Bad
/// let value = &Some(Box::new(23));
/// match value {
/// Some(inner) => println!("{}", inner),
/// None => println!("none"),
/// }
///
/// // Good
/// let value = &Some(Box::new(23));
/// match *value {
/// Some(ref inner) => println!("{}", inner),
/// None => println!("none"),
/// }
/// ```
///
/// The following example demonstrates one of the advantages of the more verbose style.
/// Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable
/// borrow, while `b` is simply taken by value. This ensures that the loop body cannot
/// accidentally modify the wrong part of the structure.
///
/// ```rust,ignore
/// // Bad
/// let mut values = vec![(2, 3), (3, 4)];
/// for (a, b) in &mut values {
/// *a += *b;
/// }
///
/// // Good
/// let mut values = vec![(2, 3), (3, 4)];
/// for &mut (ref mut a, b) in &mut values {
/// *a += b;
/// }
/// ```
pub PATTERN_TYPE_MISMATCH,
restriction,
"type of pattern does not match the expression type"
}
declare_lint_pass!(PatternTypeMismatch => [PATTERN_TYPE_MISMATCH]);
impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch {
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
if let StmtKind::Local(local) = stmt.kind {
if let Some(init) = &local.init {
if let Some(init_ty) = cx.typeck_results().node_type_opt(init.hir_id) {
let pat = &local.pat;
if in_external_macro(cx.sess(), pat.span) {
return;
}
let deref_possible = match local.source {
LocalSource::Normal => DerefPossible::Possible,
_ => DerefPossible::Impossible,
};
apply_lint(cx, pat, init_ty, deref_possible);
}
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Match(scrutinee, arms, MatchSource::Normal) = expr.kind {
if let Some(expr_ty) = cx.typeck_results().node_type_opt(scrutinee.hir_id) {
'pattern_checks: for arm in arms {
let pat = &arm.pat;
if in_external_macro(cx.sess(), pat.span) {
continue 'pattern_checks;
}
if apply_lint(cx, pat, expr_ty, DerefPossible::Possible) {
break 'pattern_checks;
}
}
}
}
if let ExprKind::Let(let_pat, let_expr, _) = expr.kind {
if let Some(ref expr_ty) = cx.typeck_results().node_type_opt(let_expr.hir_id) {
if in_external_macro(cx.sess(), let_pat.span) {
return;
}
apply_lint(cx, let_pat, expr_ty, DerefPossible::Possible);
}
}
}
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
_: Span,
hir_id: HirId,
) {
if let Some(fn_sig) = cx.typeck_results().liberated_fn_sigs().get(hir_id) {
for (param, ty) in iter::zip(body.params, fn_sig.inputs()) {
apply_lint(cx, param.pat, ty, DerefPossible::Impossible);
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum DerefPossible {
Possible,
Impossible,
}
fn apply_lint<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, expr_ty: Ty<'tcx>, deref_possible: DerefPossible) -> bool {
let maybe_mismatch = find_first_mismatch(cx, pat, expr_ty, Level::Top);
if let Some((span, mutability, level)) = maybe_mismatch {
span_lint_and_help(
cx,
PATTERN_TYPE_MISMATCH,
span,
"type of pattern does not match the expression type",
None,
&format!(
"{}explicitly match against a `{}` pattern and adjust the enclosed variable bindings",
match (deref_possible, level) {
(DerefPossible::Possible, Level::Top) => "use `*` to dereference the match expression or ",
_ => "",
},
match mutability {
Mutability::Mut => "&mut _",
Mutability::Not => "&_",
},
),
);
true
} else {
false
}
}
#[derive(Debug, Copy, Clone)]
enum Level {
Top,
Lower,
}
#[allow(rustc::usage_of_ty_tykind)]
fn find_first_mismatch<'tcx>(
cx: &LateContext<'tcx>,
pat: &Pat<'_>,
ty: Ty<'tcx>,
level: Level,
) -> Option<(Span, Mutability, Level)> {
if let PatKind::Ref(sub_pat, _) = pat.kind {
if let TyKind::Ref(_, sub_ty, _) = ty.kind() {
return find_first_mismatch(cx, sub_pat, sub_ty, Level::Lower);
}
}
if let TyKind::Ref(_, _, mutability) = *ty.kind() {
if is_non_ref_pattern(&pat.kind) {
return Some((pat.span, mutability, level));
}
}
if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
return find_first_mismatch_in_struct(cx, field_pats, field_defs, substs_ref);
}
}
}
if let PatKind::TupleStruct(ref qpath, pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
let ty_iter = field_defs.iter().map(|field_def| field_def.ty(cx.tcx, substs_ref));
return find_first_mismatch_in_tuple(cx, pats, ty_iter);
}
}
}
if let PatKind::Tuple(pats, _) = pat.kind {
if let TyKind::Tuple(..) = ty.kind() {
return find_first_mismatch_in_tuple(cx, pats, ty.tuple_fields());
}
}
if let PatKind::Or(sub_pats) = pat.kind {
for pat in sub_pats {
let maybe_mismatch = find_first_mismatch(cx, pat, ty, level);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
}
None
}
fn get_variant<'a>(adt_def: &'a AdtDef, qpath: &QPath<'_>) -> Option<&'a VariantDef> {
if adt_def.is_struct() {
if let Some(variant) = adt_def.variants.iter().next() {
return Some(variant);
}
}
if adt_def.is_enum() {
let pat_ident = last_path_segment(qpath).ident;
for variant in &adt_def.variants {
if variant.ident == pat_ident {
return Some(variant);
}
}
}
None
}
fn find_first_mismatch_in_tuple<'tcx, I>(
cx: &LateContext<'tcx>,
pats: &[Pat<'_>],
ty_iter_src: I,
) -> Option<(Span, Mutability, Level)>
where
I: IntoIterator<Item = Ty<'tcx>>,
{
let mut field_tys = ty_iter_src.into_iter();
'fields: for pat in pats {
let field_ty = if let Some(ty) = field_tys.next() {
ty
} else {
break 'fields;
};
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
None
}
fn | <'tcx>(
cx: &LateContext<'tcx>,
field_pats: &[PatField<'_>],
field_defs: &[FieldDef],
substs_ref: SubstsRef<'tcx>,
) -> Option<(Span, Mutability, Level)> {
for field_pat in field_pats {
'definitions: for field_def in field_defs {
if field_pat.ident == field_def.ident {
let field_ty = field_def.ty(cx.tcx, substs_ref);
let pat = &field_pat.pat;
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
break 'definitions;
}
}
}
None
}
fn is_non_ref_pattern(pat_kind: &PatKind<'_>) -> bool {
match pat_kind {
PatKind::Struct(..) | PatKind::Tuple(..) | PatKind::TupleStruct(..) | PatKind::Path(..) => true,
PatKind::Or(sub_pats) => sub_pats.iter().any(|pat| is_non_ref_pattern(&pat.kind)),
_ => false,
}
}
| find_first_mismatch_in_struct | identifier_name |
pattern_type_mismatch.rs | use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::last_path_segment;
use rustc_hir::{
intravisit, Body, Expr, ExprKind, FnDecl, HirId, LocalSource, MatchSource, Mutability, Pat, PatField, PatKind,
QPath, Stmt, StmtKind,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{AdtDef, FieldDef, Ty, TyKind, VariantDef};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use std::iter;
declare_clippy_lint! {
/// ### What it does
/// Checks for patterns that aren't exact representations of the types
/// they are applied to.
///
/// To satisfy this lint, you will have to adjust either the expression that is matched
/// against or the pattern itself, as well as the bindings that are introduced by the
/// adjusted patterns. For matching you will have to either dereference the expression
/// with the `*` operator, or amend the patterns to explicitly match against `&<pattern>`
/// or `&mut <pattern>` depending on the reference mutability. For the bindings you need
/// to use the inverse. You can leave them as plain bindings if you wish for the value
/// to be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct
/// a reference into the matched structure.
///
/// If you are looking for a way to learn about ownership semantics in more detail, it
/// is recommended to look at IDE options available to you to highlight types, lifetimes
/// and reference semantics in your code. The available tooling would expose these things
/// in a general way even outside of the various pattern matching mechanics. Of course
/// this lint can still be used to highlight areas of interest and ensure a good understanding
/// of ownership semantics.
///
/// ### Why is this bad?
/// It isn't bad in general. But in some contexts it can be desirable
/// because it increases ownership hints in the code, and will guard against some changes
/// in ownership.
///
/// ### Example
/// This example shows the basic adjustments necessary to satisfy the lint. Note how
/// the matched expression is explicitly dereferenced with `*` and the `inner` variable
/// is bound to a shared borrow via `ref inner`.
///
/// ```rust,ignore
/// // Bad
/// let value = &Some(Box::new(23));
/// match value {
/// Some(inner) => println!("{}", inner),
/// None => println!("none"),
/// }
///
/// // Good
/// let value = &Some(Box::new(23));
/// match *value {
/// Some(ref inner) => println!("{}", inner),
/// None => println!("none"),
/// }
/// ```
///
/// The following example demonstrates one of the advantages of the more verbose style.
/// Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable
/// borrow, while `b` is simply taken by value. This ensures that the loop body cannot
/// accidentally modify the wrong part of the structure.
///
/// ```rust,ignore
/// // Bad
/// let mut values = vec![(2, 3), (3, 4)];
/// for (a, b) in &mut values {
/// *a += *b;
/// }
///
/// // Good
/// let mut values = vec![(2, 3), (3, 4)];
/// for &mut (ref mut a, b) in &mut values {
/// *a += b;
/// }
/// ```
pub PATTERN_TYPE_MISMATCH,
restriction,
"type of pattern does not match the expression type"
}
declare_lint_pass!(PatternTypeMismatch => [PATTERN_TYPE_MISMATCH]);
impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch {
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
if let StmtKind::Local(local) = stmt.kind {
if let Some(init) = &local.init {
if let Some(init_ty) = cx.typeck_results().node_type_opt(init.hir_id) {
let pat = &local.pat;
if in_external_macro(cx.sess(), pat.span) {
return;
}
let deref_possible = match local.source {
LocalSource::Normal => DerefPossible::Possible,
_ => DerefPossible::Impossible,
};
apply_lint(cx, pat, init_ty, deref_possible);
}
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Match(scrutinee, arms, MatchSource::Normal) = expr.kind {
if let Some(expr_ty) = cx.typeck_results().node_type_opt(scrutinee.hir_id) {
'pattern_checks: for arm in arms {
let pat = &arm.pat;
if in_external_macro(cx.sess(), pat.span) {
continue 'pattern_checks;
}
if apply_lint(cx, pat, expr_ty, DerefPossible::Possible) {
break 'pattern_checks;
}
}
}
}
if let ExprKind::Let(let_pat, let_expr, _) = expr.kind {
if let Some(ref expr_ty) = cx.typeck_results().node_type_opt(let_expr.hir_id) {
if in_external_macro(cx.sess(), let_pat.span) {
return;
}
apply_lint(cx, let_pat, expr_ty, DerefPossible::Possible);
}
}
}
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
_: Span,
hir_id: HirId,
) {
if let Some(fn_sig) = cx.typeck_results().liberated_fn_sigs().get(hir_id) {
for (param, ty) in iter::zip(body.params, fn_sig.inputs()) {
apply_lint(cx, param.pat, ty, DerefPossible::Impossible);
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum DerefPossible {
Possible,
Impossible,
}
fn apply_lint<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, expr_ty: Ty<'tcx>, deref_possible: DerefPossible) -> bool {
let maybe_mismatch = find_first_mismatch(cx, pat, expr_ty, Level::Top);
if let Some((span, mutability, level)) = maybe_mismatch {
span_lint_and_help(
cx,
PATTERN_TYPE_MISMATCH,
span,
"type of pattern does not match the expression type",
None,
&format!(
"{}explicitly match against a `{}` pattern and adjust the enclosed variable bindings",
match (deref_possible, level) {
(DerefPossible::Possible, Level::Top) => "use `*` to dereference the match expression or ",
_ => "",
},
match mutability {
Mutability::Mut => "&mut _",
Mutability::Not => "&_",
},
),
);
true
} else {
false
}
}
#[derive(Debug, Copy, Clone)]
enum Level {
Top,
Lower,
}
#[allow(rustc::usage_of_ty_tykind)]
fn find_first_mismatch<'tcx>(
cx: &LateContext<'tcx>,
pat: &Pat<'_>,
ty: Ty<'tcx>,
level: Level,
) -> Option<(Span, Mutability, Level)> {
if let PatKind::Ref(sub_pat, _) = pat.kind {
if let TyKind::Ref(_, sub_ty, _) = ty.kind() {
return find_first_mismatch(cx, sub_pat, sub_ty, Level::Lower);
}
}
if let TyKind::Ref(_, _, mutability) = *ty.kind() {
if is_non_ref_pattern(&pat.kind) {
return Some((pat.span, mutability, level));
}
}
if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
return find_first_mismatch_in_struct(cx, field_pats, field_defs, substs_ref);
}
}
}
if let PatKind::TupleStruct(ref qpath, pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
let ty_iter = field_defs.iter().map(|field_def| field_def.ty(cx.tcx, substs_ref));
return find_first_mismatch_in_tuple(cx, pats, ty_iter);
}
}
}
if let PatKind::Tuple(pats, _) = pat.kind { | if let TyKind::Tuple(..) = ty.kind() {
return find_first_mismatch_in_tuple(cx, pats, ty.tuple_fields());
}
}
if let PatKind::Or(sub_pats) = pat.kind {
for pat in sub_pats {
let maybe_mismatch = find_first_mismatch(cx, pat, ty, level);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
}
None
}
fn get_variant<'a>(adt_def: &'a AdtDef, qpath: &QPath<'_>) -> Option<&'a VariantDef> {
if adt_def.is_struct() {
if let Some(variant) = adt_def.variants.iter().next() {
return Some(variant);
}
}
if adt_def.is_enum() {
let pat_ident = last_path_segment(qpath).ident;
for variant in &adt_def.variants {
if variant.ident == pat_ident {
return Some(variant);
}
}
}
None
}
fn find_first_mismatch_in_tuple<'tcx, I>(
cx: &LateContext<'tcx>,
pats: &[Pat<'_>],
ty_iter_src: I,
) -> Option<(Span, Mutability, Level)>
where
I: IntoIterator<Item = Ty<'tcx>>,
{
let mut field_tys = ty_iter_src.into_iter();
'fields: for pat in pats {
let field_ty = if let Some(ty) = field_tys.next() {
ty
} else {
break 'fields;
};
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
None
}
fn find_first_mismatch_in_struct<'tcx>(
cx: &LateContext<'tcx>,
field_pats: &[PatField<'_>],
field_defs: &[FieldDef],
substs_ref: SubstsRef<'tcx>,
) -> Option<(Span, Mutability, Level)> {
for field_pat in field_pats {
'definitions: for field_def in field_defs {
if field_pat.ident == field_def.ident {
let field_ty = field_def.ty(cx.tcx, substs_ref);
let pat = &field_pat.pat;
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
break 'definitions;
}
}
}
None
}
fn is_non_ref_pattern(pat_kind: &PatKind<'_>) -> bool {
match pat_kind {
PatKind::Struct(..) | PatKind::Tuple(..) | PatKind::TupleStruct(..) | PatKind::Path(..) => true,
PatKind::Or(sub_pats) => sub_pats.iter().any(|pat| is_non_ref_pattern(&pat.kind)),
_ => false,
}
} | random_line_split |
|
pattern_type_mismatch.rs | use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::last_path_segment;
use rustc_hir::{
intravisit, Body, Expr, ExprKind, FnDecl, HirId, LocalSource, MatchSource, Mutability, Pat, PatField, PatKind,
QPath, Stmt, StmtKind,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{AdtDef, FieldDef, Ty, TyKind, VariantDef};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use std::iter;
declare_clippy_lint! {
/// ### What it does
/// Checks for patterns that aren't exact representations of the types
/// they are applied to.
///
/// To satisfy this lint, you will have to adjust either the expression that is matched
/// against or the pattern itself, as well as the bindings that are introduced by the
/// adjusted patterns. For matching you will have to either dereference the expression
/// with the `*` operator, or amend the patterns to explicitly match against `&<pattern>`
/// or `&mut <pattern>` depending on the reference mutability. For the bindings you need
/// to use the inverse. You can leave them as plain bindings if you wish for the value
/// to be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct
/// a reference into the matched structure.
///
/// If you are looking for a way to learn about ownership semantics in more detail, it
/// is recommended to look at IDE options available to you to highlight types, lifetimes
/// and reference semantics in your code. The available tooling would expose these things
/// in a general way even outside of the various pattern matching mechanics. Of course
/// this lint can still be used to highlight areas of interest and ensure a good understanding
/// of ownership semantics.
///
/// ### Why is this bad?
/// It isn't bad in general. But in some contexts it can be desirable
/// because it increases ownership hints in the code, and will guard against some changes
/// in ownership.
///
/// ### Example
/// This example shows the basic adjustments necessary to satisfy the lint. Note how
/// the matched expression is explicitly dereferenced with `*` and the `inner` variable
/// is bound to a shared borrow via `ref inner`.
///
/// ```rust,ignore
/// // Bad
/// let value = &Some(Box::new(23));
/// match value {
/// Some(inner) => println!("{}", inner),
/// None => println!("none"),
/// }
///
/// // Good
/// let value = &Some(Box::new(23));
/// match *value {
/// Some(ref inner) => println!("{}", inner),
/// None => println!("none"),
/// }
/// ```
///
/// The following example demonstrates one of the advantages of the more verbose style.
/// Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable
/// borrow, while `b` is simply taken by value. This ensures that the loop body cannot
/// accidentally modify the wrong part of the structure.
///
/// ```rust,ignore
/// // Bad
/// let mut values = vec![(2, 3), (3, 4)];
/// for (a, b) in &mut values {
/// *a += *b;
/// }
///
/// // Good
/// let mut values = vec![(2, 3), (3, 4)];
/// for &mut (ref mut a, b) in &mut values {
/// *a += b;
/// }
/// ```
pub PATTERN_TYPE_MISMATCH,
restriction,
"type of pattern does not match the expression type"
}
declare_lint_pass!(PatternTypeMismatch => [PATTERN_TYPE_MISMATCH]);
impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch {
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
if let StmtKind::Local(local) = stmt.kind {
if let Some(init) = &local.init {
if let Some(init_ty) = cx.typeck_results().node_type_opt(init.hir_id) {
let pat = &local.pat;
if in_external_macro(cx.sess(), pat.span) {
return;
}
let deref_possible = match local.source {
LocalSource::Normal => DerefPossible::Possible,
_ => DerefPossible::Impossible,
};
apply_lint(cx, pat, init_ty, deref_possible);
}
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Match(scrutinee, arms, MatchSource::Normal) = expr.kind {
if let Some(expr_ty) = cx.typeck_results().node_type_opt(scrutinee.hir_id) {
'pattern_checks: for arm in arms {
let pat = &arm.pat;
if in_external_macro(cx.sess(), pat.span) {
continue 'pattern_checks;
}
if apply_lint(cx, pat, expr_ty, DerefPossible::Possible) {
break 'pattern_checks;
}
}
}
}
if let ExprKind::Let(let_pat, let_expr, _) = expr.kind {
if let Some(ref expr_ty) = cx.typeck_results().node_type_opt(let_expr.hir_id) {
if in_external_macro(cx.sess(), let_pat.span) {
return;
}
apply_lint(cx, let_pat, expr_ty, DerefPossible::Possible);
}
}
}
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
_: Span,
hir_id: HirId,
) {
if let Some(fn_sig) = cx.typeck_results().liberated_fn_sigs().get(hir_id) {
for (param, ty) in iter::zip(body.params, fn_sig.inputs()) {
apply_lint(cx, param.pat, ty, DerefPossible::Impossible);
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum DerefPossible {
Possible,
Impossible,
}
fn apply_lint<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, expr_ty: Ty<'tcx>, deref_possible: DerefPossible) -> bool | );
true
} else {
false
}
}
#[derive(Debug, Copy, Clone)]
enum Level {
Top,
Lower,
}
#[allow(rustc::usage_of_ty_tykind)]
fn find_first_mismatch<'tcx>(
cx: &LateContext<'tcx>,
pat: &Pat<'_>,
ty: Ty<'tcx>,
level: Level,
) -> Option<(Span, Mutability, Level)> {
if let PatKind::Ref(sub_pat, _) = pat.kind {
if let TyKind::Ref(_, sub_ty, _) = ty.kind() {
return find_first_mismatch(cx, sub_pat, sub_ty, Level::Lower);
}
}
if let TyKind::Ref(_, _, mutability) = *ty.kind() {
if is_non_ref_pattern(&pat.kind) {
return Some((pat.span, mutability, level));
}
}
if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
return find_first_mismatch_in_struct(cx, field_pats, field_defs, substs_ref);
}
}
}
if let PatKind::TupleStruct(ref qpath, pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
let ty_iter = field_defs.iter().map(|field_def| field_def.ty(cx.tcx, substs_ref));
return find_first_mismatch_in_tuple(cx, pats, ty_iter);
}
}
}
if let PatKind::Tuple(pats, _) = pat.kind {
if let TyKind::Tuple(..) = ty.kind() {
return find_first_mismatch_in_tuple(cx, pats, ty.tuple_fields());
}
}
if let PatKind::Or(sub_pats) = pat.kind {
for pat in sub_pats {
let maybe_mismatch = find_first_mismatch(cx, pat, ty, level);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
}
None
}
fn get_variant<'a>(adt_def: &'a AdtDef, qpath: &QPath<'_>) -> Option<&'a VariantDef> {
if adt_def.is_struct() {
if let Some(variant) = adt_def.variants.iter().next() {
return Some(variant);
}
}
if adt_def.is_enum() {
let pat_ident = last_path_segment(qpath).ident;
for variant in &adt_def.variants {
if variant.ident == pat_ident {
return Some(variant);
}
}
}
None
}
fn find_first_mismatch_in_tuple<'tcx, I>(
cx: &LateContext<'tcx>,
pats: &[Pat<'_>],
ty_iter_src: I,
) -> Option<(Span, Mutability, Level)>
where
I: IntoIterator<Item = Ty<'tcx>>,
{
let mut field_tys = ty_iter_src.into_iter();
'fields: for pat in pats {
let field_ty = if let Some(ty) = field_tys.next() {
ty
} else {
break 'fields;
};
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
None
}
fn find_first_mismatch_in_struct<'tcx>(
cx: &LateContext<'tcx>,
field_pats: &[PatField<'_>],
field_defs: &[FieldDef],
substs_ref: SubstsRef<'tcx>,
) -> Option<(Span, Mutability, Level)> {
for field_pat in field_pats {
'definitions: for field_def in field_defs {
if field_pat.ident == field_def.ident {
let field_ty = field_def.ty(cx.tcx, substs_ref);
let pat = &field_pat.pat;
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
break 'definitions;
}
}
}
None
}
fn is_non_ref_pattern(pat_kind: &PatKind<'_>) -> bool {
match pat_kind {
PatKind::Struct(..) | PatKind::Tuple(..) | PatKind::TupleStruct(..) | PatKind::Path(..) => true,
PatKind::Or(sub_pats) => sub_pats.iter().any(|pat| is_non_ref_pattern(&pat.kind)),
_ => false,
}
}
| {
let maybe_mismatch = find_first_mismatch(cx, pat, expr_ty, Level::Top);
if let Some((span, mutability, level)) = maybe_mismatch {
span_lint_and_help(
cx,
PATTERN_TYPE_MISMATCH,
span,
"type of pattern does not match the expression type",
None,
&format!(
"{}explicitly match against a `{}` pattern and adjust the enclosed variable bindings",
match (deref_possible, level) {
(DerefPossible::Possible, Level::Top) => "use `*` to dereference the match expression or ",
_ => "",
},
match mutability {
Mutability::Mut => "&mut _",
Mutability::Not => "&_",
},
), | identifier_body |
pattern_type_mismatch.rs | use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::last_path_segment;
use rustc_hir::{
intravisit, Body, Expr, ExprKind, FnDecl, HirId, LocalSource, MatchSource, Mutability, Pat, PatField, PatKind,
QPath, Stmt, StmtKind,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{AdtDef, FieldDef, Ty, TyKind, VariantDef};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use std::iter;
declare_clippy_lint! {
/// ### What it does
/// Checks for patterns that aren't exact representations of the types
/// they are applied to.
///
/// To satisfy this lint, you will have to adjust either the expression that is matched
/// against or the pattern itself, as well as the bindings that are introduced by the
/// adjusted patterns. For matching you will have to either dereference the expression
/// with the `*` operator, or amend the patterns to explicitly match against `&<pattern>`
/// or `&mut <pattern>` depending on the reference mutability. For the bindings you need
/// to use the inverse. You can leave them as plain bindings if you wish for the value
/// to be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct
/// a reference into the matched structure.
///
/// If you are looking for a way to learn about ownership semantics in more detail, it
/// is recommended to look at IDE options available to you to highlight types, lifetimes
/// and reference semantics in your code. The available tooling would expose these things
/// in a general way even outside of the various pattern matching mechanics. Of course
/// this lint can still be used to highlight areas of interest and ensure a good understanding
/// of ownership semantics.
///
/// ### Why is this bad?
/// It isn't bad in general. But in some contexts it can be desirable
/// because it increases ownership hints in the code, and will guard against some changes
/// in ownership.
///
/// ### Example
/// This example shows the basic adjustments necessary to satisfy the lint. Note how
/// the matched expression is explicitly dereferenced with `*` and the `inner` variable
/// is bound to a shared borrow via `ref inner`.
///
/// ```rust,ignore
/// // Bad
/// let value = &Some(Box::new(23));
/// match value {
/// Some(inner) => println!("{}", inner),
/// None => println!("none"),
/// }
///
/// // Good
/// let value = &Some(Box::new(23));
/// match *value {
/// Some(ref inner) => println!("{}", inner),
/// None => println!("none"),
/// }
/// ```
///
/// The following example demonstrates one of the advantages of the more verbose style.
/// Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable
/// borrow, while `b` is simply taken by value. This ensures that the loop body cannot
/// accidentally modify the wrong part of the structure.
///
/// ```rust,ignore
/// // Bad
/// let mut values = vec![(2, 3), (3, 4)];
/// for (a, b) in &mut values {
/// *a += *b;
/// }
///
/// // Good
/// let mut values = vec![(2, 3), (3, 4)];
/// for &mut (ref mut a, b) in &mut values {
/// *a += b;
/// }
/// ```
pub PATTERN_TYPE_MISMATCH,
restriction,
"type of pattern does not match the expression type"
}
declare_lint_pass!(PatternTypeMismatch => [PATTERN_TYPE_MISMATCH]);
impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch {
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
if let StmtKind::Local(local) = stmt.kind {
if let Some(init) = &local.init {
if let Some(init_ty) = cx.typeck_results().node_type_opt(init.hir_id) {
let pat = &local.pat;
if in_external_macro(cx.sess(), pat.span) {
return;
}
let deref_possible = match local.source {
LocalSource::Normal => DerefPossible::Possible,
_ => DerefPossible::Impossible,
};
apply_lint(cx, pat, init_ty, deref_possible);
}
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Match(scrutinee, arms, MatchSource::Normal) = expr.kind {
if let Some(expr_ty) = cx.typeck_results().node_type_opt(scrutinee.hir_id) {
'pattern_checks: for arm in arms {
let pat = &arm.pat;
if in_external_macro(cx.sess(), pat.span) {
continue 'pattern_checks;
}
if apply_lint(cx, pat, expr_ty, DerefPossible::Possible) {
break 'pattern_checks;
}
}
}
}
if let ExprKind::Let(let_pat, let_expr, _) = expr.kind {
if let Some(ref expr_ty) = cx.typeck_results().node_type_opt(let_expr.hir_id) {
if in_external_macro(cx.sess(), let_pat.span) {
return;
}
apply_lint(cx, let_pat, expr_ty, DerefPossible::Possible);
}
}
}
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
_: Span,
hir_id: HirId,
) {
if let Some(fn_sig) = cx.typeck_results().liberated_fn_sigs().get(hir_id) {
for (param, ty) in iter::zip(body.params, fn_sig.inputs()) {
apply_lint(cx, param.pat, ty, DerefPossible::Impossible);
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum DerefPossible {
Possible,
Impossible,
}
fn apply_lint<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, expr_ty: Ty<'tcx>, deref_possible: DerefPossible) -> bool {
let maybe_mismatch = find_first_mismatch(cx, pat, expr_ty, Level::Top);
if let Some((span, mutability, level)) = maybe_mismatch {
span_lint_and_help(
cx,
PATTERN_TYPE_MISMATCH,
span,
"type of pattern does not match the expression type",
None,
&format!(
"{}explicitly match against a `{}` pattern and adjust the enclosed variable bindings",
match (deref_possible, level) {
(DerefPossible::Possible, Level::Top) => "use `*` to dereference the match expression or ",
_ => "",
},
match mutability {
Mutability::Mut => "&mut _",
Mutability::Not => "&_",
},
),
);
true
} else {
false
}
}
#[derive(Debug, Copy, Clone)]
enum Level {
Top,
Lower,
}
#[allow(rustc::usage_of_ty_tykind)]
fn find_first_mismatch<'tcx>(
cx: &LateContext<'tcx>,
pat: &Pat<'_>,
ty: Ty<'tcx>,
level: Level,
) -> Option<(Span, Mutability, Level)> {
if let PatKind::Ref(sub_pat, _) = pat.kind {
if let TyKind::Ref(_, sub_ty, _) = ty.kind() {
return find_first_mismatch(cx, sub_pat, sub_ty, Level::Lower);
}
}
if let TyKind::Ref(_, _, mutability) = *ty.kind() {
if is_non_ref_pattern(&pat.kind) {
return Some((pat.span, mutability, level));
}
}
if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
return find_first_mismatch_in_struct(cx, field_pats, field_defs, substs_ref);
}
}
}
if let PatKind::TupleStruct(ref qpath, pats, _) = pat.kind {
if let TyKind::Adt(adt_def, substs_ref) = ty.kind() {
if let Some(variant) = get_variant(adt_def, qpath) {
let field_defs = &variant.fields;
let ty_iter = field_defs.iter().map(|field_def| field_def.ty(cx.tcx, substs_ref));
return find_first_mismatch_in_tuple(cx, pats, ty_iter);
}
}
}
if let PatKind::Tuple(pats, _) = pat.kind {
if let TyKind::Tuple(..) = ty.kind() {
return find_first_mismatch_in_tuple(cx, pats, ty.tuple_fields());
}
}
if let PatKind::Or(sub_pats) = pat.kind {
for pat in sub_pats {
let maybe_mismatch = find_first_mismatch(cx, pat, ty, level);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
}
}
None
}
fn get_variant<'a>(adt_def: &'a AdtDef, qpath: &QPath<'_>) -> Option<&'a VariantDef> {
if adt_def.is_struct() {
if let Some(variant) = adt_def.variants.iter().next() {
return Some(variant);
}
}
if adt_def.is_enum() {
let pat_ident = last_path_segment(qpath).ident;
for variant in &adt_def.variants {
if variant.ident == pat_ident {
return Some(variant);
}
}
}
None
}
fn find_first_mismatch_in_tuple<'tcx, I>(
cx: &LateContext<'tcx>,
pats: &[Pat<'_>],
ty_iter_src: I,
) -> Option<(Span, Mutability, Level)>
where
I: IntoIterator<Item = Ty<'tcx>>,
{
let mut field_tys = ty_iter_src.into_iter();
'fields: for pat in pats {
let field_ty = if let Some(ty) = field_tys.next() {
ty
} else {
break 'fields;
};
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch |
}
None
}
fn find_first_mismatch_in_struct<'tcx>(
cx: &LateContext<'tcx>,
field_pats: &[PatField<'_>],
field_defs: &[FieldDef],
substs_ref: SubstsRef<'tcx>,
) -> Option<(Span, Mutability, Level)> {
for field_pat in field_pats {
'definitions: for field_def in field_defs {
if field_pat.ident == field_def.ident {
let field_ty = field_def.ty(cx.tcx, substs_ref);
let pat = &field_pat.pat;
let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
if let Some(mismatch) = maybe_mismatch {
return Some(mismatch);
}
break 'definitions;
}
}
}
None
}
fn is_non_ref_pattern(pat_kind: &PatKind<'_>) -> bool {
match pat_kind {
PatKind::Struct(..) | PatKind::Tuple(..) | PatKind::TupleStruct(..) | PatKind::Path(..) => true,
PatKind::Or(sub_pats) => sub_pats.iter().any(|pat| is_non_ref_pattern(&pat.kind)),
_ => false,
}
}
| {
return Some(mismatch);
} | conditional_block |
mod.rs | /// Type definitions and serializations of types used in the VM and in other modules
#[derive(Serialize, Deserialize, Clone)]
pub struct Instruction {
pub opcode: Opcode,
pub target: Register,
pub left: Register,
pub right: Register
}
#[derive(Serialize, Deserialize)]
pub struct Module {
pub functions: Vec<u64>,
pub constants: Vec<i64>,
pub entry_point: u64,
pub code: Vec<Instruction>
}
pub struct | <'a> {
pub functions: &'a [u64],
pub constants: &'a [i64],
pub code: &'a [Instruction],
pub registers: &'a mut [i64],
pub base: usize
}
/// Definition of the register type and a list of special registers
pub type Register = u8;
pub mod reg {
use super::*;
pub const RET: Register = 0;
pub const VAL: Register = 1;
}
/// Definition of the opcode type and a listing of valid operations
pub type Opcode = u8;
pub mod ops {
use super::*;
pub const HLT: Opcode = 0;
pub const LD: Opcode = 1;
pub const LDB: Opcode = 2;
pub const LDR: Opcode = 3;
pub const ADD: Opcode = 4;
pub const SUB: Opcode = 5;
pub const MUL: Opcode = 6;
pub const DIV: Opcode = 7;
pub const AND: Opcode = 8;
pub const OR: Opcode = 9;
pub const NOT: Opcode = 10;
pub const EQ: Opcode = 11;
pub const LT: Opcode = 12;
pub const LE: Opcode = 13;
pub const GT: Opcode = 14;
pub const GE: Opcode = 15;
pub const NEQ: Opcode = 16;
pub const CAL: Opcode = 17;
pub const TLC: Opcode = 18;
pub const RET: Opcode = 19;
pub const MOV: Opcode = 20;
pub const MVO: Opcode = 21;
pub const JMF: Opcode = 22;
pub const JMB: Opcode = 23;
pub const JTF: Opcode = 24;
pub const WRI: Opcode = 25;
pub const RDI: Opcode = 26;
}
/// A listing of possible types
pub type Type = u8;
pub mod types {
use super::*;
pub const INT: Type = 0;
//pub const FLOAT: Type = 0;
//pub const INTLIST: Type = 0;
//pub const FLOATLIST: Type = 0;
} | Thread | identifier_name |
mod.rs | /// Type definitions and serializations of types used in the VM and in other modules
#[derive(Serialize, Deserialize, Clone)]
pub struct Instruction {
pub opcode: Opcode,
pub target: Register,
pub left: Register,
pub right: Register
}
#[derive(Serialize, Deserialize)]
pub struct Module {
pub functions: Vec<u64>,
pub constants: Vec<i64>,
pub entry_point: u64,
pub code: Vec<Instruction>
}
pub struct Thread<'a> {
pub functions: &'a [u64],
pub constants: &'a [i64],
pub code: &'a [Instruction],
pub registers: &'a mut [i64],
pub base: usize
}
/// Definition of the register type and a list of special registers
pub type Register = u8;
pub mod reg {
use super::*;
pub const RET: Register = 0;
pub const VAL: Register = 1;
}
/// Definition of the opcode type and a listing of valid operations
pub type Opcode = u8;
pub mod ops {
use super::*;
pub const HLT: Opcode = 0;
pub const LD: Opcode = 1;
pub const LDB: Opcode = 2;
pub const LDR: Opcode = 3;
pub const ADD: Opcode = 4;
pub const SUB: Opcode = 5;
pub const MUL: Opcode = 6;
pub const DIV: Opcode = 7;
pub const AND: Opcode = 8;
pub const OR: Opcode = 9;
pub const NOT: Opcode = 10;
pub const EQ: Opcode = 11;
pub const LT: Opcode = 12;
pub const LE: Opcode = 13;
pub const GT: Opcode = 14;
pub const GE: Opcode = 15;
pub const NEQ: Opcode = 16;
pub const CAL: Opcode = 17;
pub const TLC: Opcode = 18;
pub const RET: Opcode = 19;
pub const MOV: Opcode = 20;
pub const MVO: Opcode = 21;
pub const JMF: Opcode = 22;
pub const JMB: Opcode = 23;
pub const JTF: Opcode = 24;
pub const WRI: Opcode = 25;
pub const RDI: Opcode = 26;
}
/// A listing of possible types
pub type Type = u8;
pub mod types {
use super::*;
pub const INT: Type = 0;
//pub const FLOAT: Type = 0;
//pub const INTLIST: Type = 0;
//pub const FLOATLIST: Type = 0; | } | random_line_split |
|
panic_in_result_fn_assertions.rs | #![warn(clippy::panic_in_result_fn)]
#![allow(clippy::unnecessary_wraps)]
struct A;
impl A {
fn result_with_assert_with_message(x: i32) -> Result<bool, String> // should emit lint
{
assert!(x == 5, "wrong argument");
Ok(true)
}
fn result_with_assert_eq(x: i32) -> Result<bool, String> // should emit lint
{
assert_eq!(x, 5);
Ok(true)
}
fn result_with_assert_ne(x: i32) -> Result<bool, String> // should emit lint
{
assert_ne!(x, 1);
Ok(true)
}
fn other_with_assert_with_message(x: i32) // should not emit lint | assert!(x == 5, "wrong argument");
}
fn other_with_assert_eq(x: i32) // should not emit lint
{
assert_eq!(x, 5);
}
fn other_with_assert_ne(x: i32) // should not emit lint
{
assert_ne!(x, 1);
}
fn result_without_banned_functions() -> Result<bool, String> // should not emit lint
{
let assert = "assert!";
println!("No {}", assert);
Ok(true)
}
}
fn main() {} | { | random_line_split |
panic_in_result_fn_assertions.rs | #![warn(clippy::panic_in_result_fn)]
#![allow(clippy::unnecessary_wraps)]
struct A;
impl A {
fn result_with_assert_with_message(x: i32) -> Result<bool, String> // should emit lint
{
assert!(x == 5, "wrong argument");
Ok(true)
}
fn result_with_assert_eq(x: i32) -> Result<bool, String> // should emit lint
|
fn result_with_assert_ne(x: i32) -> Result<bool, String> // should emit lint
{
assert_ne!(x, 1);
Ok(true)
}
fn other_with_assert_with_message(x: i32) // should not emit lint
{
assert!(x == 5, "wrong argument");
}
fn other_with_assert_eq(x: i32) // should not emit lint
{
assert_eq!(x, 5);
}
fn other_with_assert_ne(x: i32) // should not emit lint
{
assert_ne!(x, 1);
}
fn result_without_banned_functions() -> Result<bool, String> // should not emit lint
{
let assert = "assert!";
println!("No {}", assert);
Ok(true)
}
}
fn main() {}
| {
assert_eq!(x, 5);
Ok(true)
} | identifier_body |
panic_in_result_fn_assertions.rs | #![warn(clippy::panic_in_result_fn)]
#![allow(clippy::unnecessary_wraps)]
struct A;
impl A {
fn result_with_assert_with_message(x: i32) -> Result<bool, String> // should emit lint
{
assert!(x == 5, "wrong argument");
Ok(true)
}
fn | (x: i32) -> Result<bool, String> // should emit lint
{
assert_eq!(x, 5);
Ok(true)
}
fn result_with_assert_ne(x: i32) -> Result<bool, String> // should emit lint
{
assert_ne!(x, 1);
Ok(true)
}
fn other_with_assert_with_message(x: i32) // should not emit lint
{
assert!(x == 5, "wrong argument");
}
fn other_with_assert_eq(x: i32) // should not emit lint
{
assert_eq!(x, 5);
}
fn other_with_assert_ne(x: i32) // should not emit lint
{
assert_ne!(x, 1);
}
fn result_without_banned_functions() -> Result<bool, String> // should not emit lint
{
let assert = "assert!";
println!("No {}", assert);
Ok(true)
}
}
fn main() {}
| result_with_assert_eq | identifier_name |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() {
return; |
--frames_left;
x += dx;
y += dy;
}
fn in_use(&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if!particles[i].in_use() {
particles[i]
}
}
}
fn animate() {
for particle in particles {
particle.animate();
}
}
} | } | random_line_split |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() |
--frames_left;
x += dx;
y += dy;
}
fn in_use(&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if!particles[i].in_use() {
particles[i]
}
}
}
fn animate() {
for particle in particles {
particle.animate();
}
}
}
| {
return;
} | conditional_block |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() {
return;
}
--frames_left;
x += dx;
y += dy;
}
fn | (&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if!particles[i].in_use() {
particles[i]
}
}
}
fn animate() {
for particle in particles {
particle.animate();
}
}
}
| in_use | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.