repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/snapshot_map/test.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.
use super::SnapshotMap;
#[test]
fn basic() {
let mut map = SnapshotMap::new();
map.insert(22, "twenty-two");
let snapshot = map.snapshot();
map.insert(22, "thirty-three");
assert_eq!(map[&22], "thirty-three");
map.insert(44, "fourty-four");
assert_eq!(map[&44], "fourty-four");
assert_eq!(map.get(&33), None);
map.rollback_to(&snapshot);
assert_eq!(map[&22], "twenty-two");
assert_eq!(map.get(&33), None);
assert_eq!(map.get(&44), None);
}
#[test]
#[should_panic]
fn out_of_order() {
let mut map = SnapshotMap::new();
map.insert(22, "twenty-two");
let snapshot1 = map.snapshot();
let _snapshot2 = map.snapshot();
map.rollback_to(&snapshot1);
}
#[test]
fn nested_commit_then_rollback() {
let mut map = SnapshotMap::new();
map.insert(22, "twenty-two");
let snapshot1 = map.snapshot();
let snapshot2 = map.snapshot();
map.insert(22, "thirty-three");
map.commit(&snapshot2);
assert_eq!(map[&22], "thirty-three");
map.rollback_to(&snapshot1);
assert_eq!(map[&22], "twenty-two");
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/snapshot_map/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.
use fx::FxHashMap;
use std::hash::Hash;
use std::ops;
use std::mem;
#[cfg(test)]
mod test;
pub struct SnapshotMap<K, V>
where K: Hash + Clone + Eq
{
map: FxHashMap<K, V>,
undo_log: Vec<UndoLog<K, V>>,
}
pub struct Snapshot {
len: usize,
}
enum UndoLog<K, V> {
OpenSnapshot,
CommittedSnapshot,
Inserted(K),
Overwrite(K, V),
Noop,
}
impl<K, V> SnapshotMap<K, V>
where K: Hash + Clone + Eq
{
pub fn new() -> Self {
SnapshotMap {
map: FxHashMap(),
undo_log: vec![],
}
}
pub fn clear(&mut self) {
self.map.clear();
self.undo_log.clear();
}
pub fn insert(&mut self, key: K, value: V) -> bool {
match self.map.insert(key.clone(), value) {
None => {
if !self.undo_log.is_empty() {
self.undo_log.push(UndoLog::Inserted(key));
}
true
}
Some(old_value) => {
if !self.undo_log.is_empty() {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
}
false
}
}
}
pub fn insert_noop(&mut self) {
if !self.undo_log.is_empty() {
self.undo_log.push(UndoLog::Noop);
}
}
pub fn remove(&mut self, key: K) -> bool {
match self.map.remove(&key) {
Some(old_value) => {
if !self.undo_log.is_empty() {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
}
true
}
None => false,
}
}
pub fn get(&self, key: &K) -> Option<&V> {
self.map.get(key)
}
pub fn snapshot(&mut self) -> Snapshot {
self.undo_log.push(UndoLog::OpenSnapshot);
let len = self.undo_log.len() - 1;
Snapshot { len }
}
fn assert_open_snapshot(&self, snapshot: &Snapshot) {
assert!(snapshot.len < self.undo_log.len());
assert!(match self.undo_log[snapshot.len] {
UndoLog::OpenSnapshot => true,
_ => false,
});
}
pub fn commit(&mut self, snapshot: &Snapshot) {
self.assert_open_snapshot(snapshot);
if snapshot.len == 0 {
// The root snapshot.
self.undo_log.truncate(0);
} else {
self.undo_log[snapshot.len] = UndoLog::CommittedSnapshot;
}
}
pub fn partial_rollback<F>(&mut self,
snapshot: &Snapshot,
should_revert_key: &F)
where F: Fn(&K) -> bool
{
self.assert_open_snapshot(snapshot);
for i in (snapshot.len + 1..self.undo_log.len()).rev() {
let reverse = match self.undo_log[i] {
UndoLog::OpenSnapshot => false,
UndoLog::CommittedSnapshot => false,
UndoLog::Noop => false,
UndoLog::Inserted(ref k) => should_revert_key(k),
UndoLog::Overwrite(ref k, _) => should_revert_key(k),
};
if reverse {
let entry = mem::replace(&mut self.undo_log[i], UndoLog::Noop);
self.reverse(entry);
}
}
}
pub fn rollback_to(&mut self, snapshot: &Snapshot) {
self.assert_open_snapshot(snapshot);
while self.undo_log.len() > snapshot.len + 1 {
let entry = self.undo_log.pop().unwrap();
self.reverse(entry);
}
let v = self.undo_log.pop().unwrap();
assert!(match v {
UndoLog::OpenSnapshot => true,
_ => false,
});
assert!(self.undo_log.len() == snapshot.len);
}
fn reverse(&mut self, entry: UndoLog<K, V>) {
match entry {
UndoLog::OpenSnapshot => {
panic!("cannot rollback an uncommitted snapshot");
}
UndoLog::CommittedSnapshot => {}
UndoLog::Inserted(key) => {
self.map.remove(&key);
}
UndoLog::Overwrite(key, old_value) => {
self.map.insert(key, old_value);
}
UndoLog::Noop => {}
}
}
}
impl<'k, K, V> ops::Index<&'k K> for SnapshotMap<K, V>
where K: Hash + Clone + Eq
{
type Output = V;
fn index(&self, key: &'k K) -> &V {
&self.map[key]
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/test.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.
use std::collections::HashMap;
use std::cmp::max;
use std::slice;
use std::iter;
use super::*;
pub struct TestGraph {
num_nodes: usize,
start_node: usize,
successors: HashMap<usize, Vec<usize>>,
predecessors: HashMap<usize, Vec<usize>>,
}
impl TestGraph {
pub fn new(start_node: usize, edges: &[(usize, usize)]) -> Self {
let mut graph = TestGraph {
num_nodes: start_node + 1,
start_node,
successors: HashMap::new(),
predecessors: HashMap::new(),
};
for &(source, target) in edges {
graph.num_nodes = max(graph.num_nodes, source + 1);
graph.num_nodes = max(graph.num_nodes, target + 1);
graph.successors.entry(source).or_default().push(target);
graph.predecessors.entry(target).or_default().push(source);
}
for node in 0..graph.num_nodes {
graph.successors.entry(node).or_default();
graph.predecessors.entry(node).or_default();
}
graph
}
}
impl DirectedGraph for TestGraph {
type Node = usize;
}
impl WithStartNode for TestGraph {
fn start_node(&self) -> usize {
self.start_node
}
}
impl WithNumNodes for TestGraph {
fn num_nodes(&self) -> usize {
self.num_nodes
}
}
impl WithPredecessors for TestGraph {
fn predecessors<'graph>(&'graph self,
node: usize)
-> <Self as GraphPredecessors<'graph>>::Iter {
self.predecessors[&node].iter().cloned()
}
}
impl WithSuccessors for TestGraph {
fn successors<'graph>(&'graph self, node: usize) -> <Self as GraphSuccessors<'graph>>::Iter {
self.successors[&node].iter().cloned()
}
}
impl<'graph> GraphPredecessors<'graph> for TestGraph {
type Item = usize;
type Iter = iter::Cloned<slice::Iter<'graph, usize>>;
}
impl<'graph> GraphSuccessors<'graph> for TestGraph {
type Item = usize;
type Iter = iter::Cloned<slice::Iter<'graph, usize>>;
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/mod.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.
use super::indexed_vec::Idx;
pub mod dominators;
pub mod implementation;
pub mod iterate;
mod reference;
pub mod scc;
#[cfg(test)]
mod test;
pub trait DirectedGraph {
type Node: Idx;
}
pub trait WithNumNodes: DirectedGraph {
fn num_nodes(&self) -> usize;
}
pub trait WithSuccessors: DirectedGraph
where
Self: for<'graph> GraphSuccessors<'graph, Item = <Self as DirectedGraph>::Node>,
{
fn successors<'graph>(
&'graph self,
node: Self::Node,
) -> <Self as GraphSuccessors<'graph>>::Iter;
}
pub trait GraphSuccessors<'graph> {
type Item;
type Iter: Iterator<Item = Self::Item>;
}
pub trait WithPredecessors: DirectedGraph
where
Self: for<'graph> GraphPredecessors<'graph, Item = <Self as DirectedGraph>::Node>,
{
fn predecessors<'graph>(
&'graph self,
node: Self::Node,
) -> <Self as GraphPredecessors<'graph>>::Iter;
}
pub trait GraphPredecessors<'graph> {
type Item;
type Iter: Iterator<Item = Self::Item>;
}
pub trait WithStartNode: DirectedGraph {
fn start_node(&self) -> Self::Node;
}
pub trait ControlFlowGraph:
DirectedGraph + WithStartNode + WithPredecessors + WithStartNode + WithSuccessors + WithNumNodes
{
// convenient trait
}
impl<T> ControlFlowGraph for T
where
T: DirectedGraph
+ WithStartNode
+ WithPredecessors
+ WithStartNode
+ WithSuccessors
+ WithNumNodes,
{
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/reference.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.
use super::*;
impl<'graph, G: DirectedGraph> DirectedGraph for &'graph G {
type Node = G::Node;
}
impl<'graph, G: WithNumNodes> WithNumNodes for &'graph G {
fn num_nodes(&self) -> usize {
(**self).num_nodes()
}
}
impl<'graph, G: WithStartNode> WithStartNode for &'graph G {
fn start_node(&self) -> Self::Node {
(**self).start_node()
}
}
impl<'graph, G: WithSuccessors> WithSuccessors for &'graph G {
fn successors<'iter>(&'iter self, node: Self::Node) -> <Self as GraphSuccessors<'iter>>::Iter {
(**self).successors(node)
}
}
impl<'graph, G: WithPredecessors> WithPredecessors for &'graph G {
fn predecessors<'iter>(&'iter self,
node: Self::Node)
-> <Self as GraphPredecessors<'iter>>::Iter {
(**self).predecessors(node)
}
}
impl<'iter, 'graph, G: WithPredecessors> GraphPredecessors<'iter> for &'graph G {
type Item = G::Node;
type Iter = <G as GraphPredecessors<'iter>>::Iter;
}
impl<'iter, 'graph, G: WithSuccessors> GraphSuccessors<'iter> for &'graph G {
type Item = G::Node;
type Iter = <G as GraphSuccessors<'iter>>::Iter;
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/iterate/test.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.
use super::super::test::TestGraph;
use super::*;
#[test]
fn diamond_post_order() {
let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
let result = post_order_from(&graph, 0);
assert_eq!(result, vec![3, 1, 2, 0]);
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/iterate/mod.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.
use super::super::indexed_vec::IndexVec;
use super::{DirectedGraph, WithSuccessors, WithNumNodes};
#[cfg(test)]
mod test;
pub fn post_order_from<G: DirectedGraph + WithSuccessors + WithNumNodes>(
graph: &G,
start_node: G::Node,
) -> Vec<G::Node> {
post_order_from_to(graph, start_node, None)
}
pub fn post_order_from_to<G: DirectedGraph + WithSuccessors + WithNumNodes>(
graph: &G,
start_node: G::Node,
end_node: Option<G::Node>,
) -> Vec<G::Node> {
let mut visited: IndexVec<G::Node, bool> = IndexVec::from_elem_n(false, graph.num_nodes());
let mut result: Vec<G::Node> = Vec::with_capacity(graph.num_nodes());
if let Some(end_node) = end_node {
visited[end_node] = true;
}
post_order_walk(graph, start_node, &mut result, &mut visited);
result
}
fn post_order_walk<G: DirectedGraph + WithSuccessors + WithNumNodes>(
graph: &G,
node: G::Node,
result: &mut Vec<G::Node>,
visited: &mut IndexVec<G::Node, bool>,
) {
if visited[node] {
return;
}
visited[node] = true;
for successor in graph.successors(node) {
post_order_walk(graph, successor, result, visited);
}
result.push(node);
}
pub fn reverse_post_order<G: DirectedGraph + WithSuccessors + WithNumNodes>(
graph: &G,
start_node: G::Node,
) -> Vec<G::Node> {
let mut vec = post_order_from(graph, start_node);
vec.reverse();
vec
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/implementation/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.
//! A graph module for use in dataflow, region resolution, and elsewhere.
//!
//! # Interface details
//!
//! You customize the graph by specifying a "node data" type `N` and an
//! "edge data" type `E`. You can then later gain access (mutable or
//! immutable) to these "user-data" bits. Currently, you can only add
//! nodes or edges to the graph. You cannot remove or modify them once
//! added. This could be changed if we have a need.
//!
//! # Implementation details
//!
//! The main tricky thing about this code is the way that edges are
//! stored. The edges are stored in a central array, but they are also
//! threaded onto two linked lists for each node, one for incoming edges
//! and one for outgoing edges. Note that every edge is a member of some
//! incoming list and some outgoing list. Basically you can load the
//! first index of the linked list from the node data structures (the
//! field `first_edge`) and then, for each edge, load the next index from
//! the field `next_edge`). Each of those fields is an array that should
//! be indexed by the direction (see the type `Direction`).
use bitvec::BitArray;
use std::fmt::Debug;
use std::usize;
use snapshot_vec::{SnapshotVec, SnapshotVecDelegate};
#[cfg(test)]
mod tests;
pub struct Graph<N, E> {
nodes: SnapshotVec<Node<N>>,
edges: SnapshotVec<Edge<E>>,
}
pub struct Node<N> {
first_edge: [EdgeIndex; 2], // see module comment
pub data: N,
}
#[derive(Debug)]
pub struct Edge<E> {
next_edge: [EdgeIndex; 2], // see module comment
source: NodeIndex,
target: NodeIndex,
pub data: E,
}
impl<N> SnapshotVecDelegate for Node<N> {
type Value = Node<N>;
type Undo = ();
fn reverse(_: &mut Vec<Node<N>>, _: ()) {}
}
impl<N> SnapshotVecDelegate for Edge<N> {
type Value = Edge<N>;
type Undo = ();
fn reverse(_: &mut Vec<Edge<N>>, _: ()) {}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct NodeIndex(pub usize);
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct EdgeIndex(pub usize);
pub const INVALID_EDGE_INDEX: EdgeIndex = EdgeIndex(usize::MAX);
// Use a private field here to guarantee no more instances are created:
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Direction {
repr: usize,
}
pub const OUTGOING: Direction = Direction { repr: 0 };
pub const INCOMING: Direction = Direction { repr: 1 };
impl NodeIndex {
/// Returns unique id (unique with respect to the graph holding associated node).
pub fn node_id(self) -> usize {
self.0
}
}
impl<N: Debug, E: Debug> Graph<N, E> {
pub fn new() -> Graph<N, E> {
Graph {
nodes: SnapshotVec::new(),
edges: SnapshotVec::new(),
}
}
pub fn with_capacity(nodes: usize, edges: usize) -> Graph<N, E> {
Graph {
nodes: SnapshotVec::with_capacity(nodes),
edges: SnapshotVec::with_capacity(edges),
}
}
// # Simple accessors
#[inline]
pub fn all_nodes(&self) -> &[Node<N>] {
&self.nodes
}
#[inline]
pub fn len_nodes(&self) -> usize {
self.nodes.len()
}
#[inline]
pub fn all_edges(&self) -> &[Edge<E>] {
&self.edges
}
#[inline]
pub fn len_edges(&self) -> usize {
self.edges.len()
}
// # Node construction
pub fn next_node_index(&self) -> NodeIndex {
NodeIndex(self.nodes.len())
}
pub fn add_node(&mut self, data: N) -> NodeIndex {
let idx = self.next_node_index();
self.nodes.push(Node {
first_edge: [INVALID_EDGE_INDEX, INVALID_EDGE_INDEX],
data,
});
idx
}
pub fn mut_node_data(&mut self, idx: NodeIndex) -> &mut N {
&mut self.nodes[idx.0].data
}
pub fn node_data(&self, idx: NodeIndex) -> &N {
&self.nodes[idx.0].data
}
pub fn node(&self, idx: NodeIndex) -> &Node<N> {
&self.nodes[idx.0]
}
// # Edge construction and queries
pub fn next_edge_index(&self) -> EdgeIndex {
EdgeIndex(self.edges.len())
}
pub fn add_edge(&mut self, source: NodeIndex, target: NodeIndex, data: E) -> EdgeIndex {
debug!("graph: add_edge({:?}, {:?}, {:?})", source, target, data);
let idx = self.next_edge_index();
// read current first of the list of edges from each node
let source_first = self.nodes[source.0].first_edge[OUTGOING.repr];
let target_first = self.nodes[target.0].first_edge[INCOMING.repr];
// create the new edge, with the previous firsts from each node
// as the next pointers
self.edges.push(Edge {
next_edge: [source_first, target_first],
source,
target,
data,
});
// adjust the firsts for each node target be the next object.
self.nodes[source.0].first_edge[OUTGOING.repr] = idx;
self.nodes[target.0].first_edge[INCOMING.repr] = idx;
idx
}
pub fn edge(&self, idx: EdgeIndex) -> &Edge<E> {
&self.edges[idx.0]
}
// # Iterating over nodes, edges
pub fn enumerated_nodes(&self) -> impl Iterator<Item = (NodeIndex, &Node<N>)> {
self.nodes
.iter()
.enumerate()
.map(|(idx, n)| (NodeIndex(idx), n))
}
pub fn enumerated_edges(&self) -> impl Iterator<Item = (EdgeIndex, &Edge<E>)> {
self.edges
.iter()
.enumerate()
.map(|(idx, e)| (EdgeIndex(idx), e))
}
pub fn each_node<'a>(&'a self, mut f: impl FnMut(NodeIndex, &'a Node<N>) -> bool) -> bool {
//! Iterates over all edges defined in the graph.
self.enumerated_nodes()
.all(|(node_idx, node)| f(node_idx, node))
}
pub fn each_edge<'a>(&'a self, mut f: impl FnMut(EdgeIndex, &'a Edge<E>) -> bool) -> bool {
//! Iterates over all edges defined in the graph
self.enumerated_edges()
.all(|(edge_idx, edge)| f(edge_idx, edge))
}
pub fn outgoing_edges(&self, source: NodeIndex) -> AdjacentEdges<N, E> {
self.adjacent_edges(source, OUTGOING)
}
pub fn incoming_edges(&self, source: NodeIndex) -> AdjacentEdges<N, E> {
self.adjacent_edges(source, INCOMING)
}
pub fn adjacent_edges(&self, source: NodeIndex, direction: Direction) -> AdjacentEdges<N, E> {
let first_edge = self.node(source).first_edge[direction.repr];
AdjacentEdges {
graph: self,
direction,
next: first_edge,
}
}
pub fn successor_nodes<'a>(
&'a self,
source: NodeIndex,
) -> impl Iterator<Item = NodeIndex> + 'a {
self.outgoing_edges(source).targets()
}
pub fn predecessor_nodes<'a>(
&'a self,
target: NodeIndex,
) -> impl Iterator<Item = NodeIndex> + 'a {
self.incoming_edges(target).sources()
}
pub fn depth_traverse<'a>(
&'a self,
start: NodeIndex,
direction: Direction,
) -> DepthFirstTraversal<'a, N, E> {
DepthFirstTraversal::with_start_node(self, start, direction)
}
pub fn nodes_in_postorder(
&self,
direction: Direction,
entry_node: NodeIndex,
) -> Vec<NodeIndex> {
let mut visited = BitArray::new(self.len_nodes());
let mut stack = vec![];
let mut result = Vec::with_capacity(self.len_nodes());
let mut push_node = |stack: &mut Vec<_>, node: NodeIndex| {
if visited.insert(node.0) {
stack.push((node, self.adjacent_edges(node, direction)));
}
};
for node in Some(entry_node)
.into_iter()
.chain(self.enumerated_nodes().map(|(node, _)| node))
{
push_node(&mut stack, node);
while let Some((node, mut iter)) = stack.pop() {
if let Some((_, child)) = iter.next() {
let target = child.source_or_target(direction);
// the current node needs more processing, so
// add it back to the stack
stack.push((node, iter));
// and then push the new node
push_node(&mut stack, target);
} else {
result.push(node);
}
}
}
assert_eq!(result.len(), self.len_nodes());
result
}
}
// # Iterators
pub struct AdjacentEdges<'g, N, E>
where
N: 'g,
E: 'g,
{
graph: &'g Graph<N, E>,
direction: Direction,
next: EdgeIndex,
}
impl<'g, N: Debug, E: Debug> AdjacentEdges<'g, N, E> {
fn targets(self) -> impl Iterator<Item = NodeIndex> + 'g {
self.into_iter().map(|(_, edge)| edge.target)
}
fn sources(self) -> impl Iterator<Item = NodeIndex> + 'g {
self.into_iter().map(|(_, edge)| edge.source)
}
}
impl<'g, N: Debug, E: Debug> Iterator for AdjacentEdges<'g, N, E> {
type Item = (EdgeIndex, &'g Edge<E>);
fn next(&mut self) -> Option<(EdgeIndex, &'g Edge<E>)> {
let edge_index = self.next;
if edge_index == INVALID_EDGE_INDEX {
return None;
}
let edge = self.graph.edge(edge_index);
self.next = edge.next_edge[self.direction.repr];
Some((edge_index, edge))
}
fn size_hint(&self) -> (usize, Option<usize>) {
// At most, all the edges in the graph.
(0, Some(self.graph.len_edges()))
}
}
pub struct DepthFirstTraversal<'g, N, E>
where
N: 'g,
E: 'g,
{
graph: &'g Graph<N, E>,
stack: Vec<NodeIndex>,
visited: BitArray<usize>,
direction: Direction,
}
impl<'g, N: Debug, E: Debug> DepthFirstTraversal<'g, N, E> {
pub fn with_start_node(
graph: &'g Graph<N, E>,
start_node: NodeIndex,
direction: Direction,
) -> Self {
let mut visited = BitArray::new(graph.len_nodes());
visited.insert(start_node.node_id());
DepthFirstTraversal {
graph,
stack: vec![start_node],
visited,
direction,
}
}
fn visit(&mut self, node: NodeIndex) {
if self.visited.insert(node.node_id()) {
self.stack.push(node);
}
}
}
impl<'g, N: Debug, E: Debug> Iterator for DepthFirstTraversal<'g, N, E> {
type Item = NodeIndex;
fn next(&mut self) -> Option<NodeIndex> {
let next = self.stack.pop();
if let Some(idx) = next {
for (_, edge) in self.graph.adjacent_edges(idx, self.direction) {
let target = edge.source_or_target(self.direction);
self.visit(target);
}
}
next
}
fn size_hint(&self) -> (usize, Option<usize>) {
// We will visit every node in the graph exactly once.
let remaining = self.graph.len_nodes() - self.visited.count();
(remaining, Some(remaining))
}
}
impl<'g, N: Debug, E: Debug> ExactSizeIterator for DepthFirstTraversal<'g, N, E> {}
impl<E> Edge<E> {
pub fn source(&self) -> NodeIndex {
self.source
}
pub fn target(&self) -> NodeIndex {
self.target
}
pub fn source_or_target(&self, direction: Direction) -> NodeIndex {
if direction == OUTGOING {
self.target
} else {
self.source
}
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/implementation/tests.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use graph::implementation::*;
use std::fmt::Debug;
type TestGraph = Graph<&'static str, &'static str>;
fn create_graph() -> TestGraph {
let mut graph = Graph::new();
// Create a simple graph
//
// F
// |
// V
// A --> B --> C
// | ^
// v |
// D --> E
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
let d = graph.add_node("D");
let e = graph.add_node("E");
let f = graph.add_node("F");
graph.add_edge(a, b, "AB");
graph.add_edge(b, c, "BC");
graph.add_edge(b, d, "BD");
graph.add_edge(d, e, "DE");
graph.add_edge(e, c, "EC");
graph.add_edge(f, b, "FB");
return graph;
}
#[test]
fn each_node() {
let graph = create_graph();
let expected = ["A", "B", "C", "D", "E", "F"];
graph.each_node(|idx, node| {
assert_eq!(&expected[idx.0], graph.node_data(idx));
assert_eq!(expected[idx.0], node.data);
true
});
}
#[test]
fn each_edge() {
let graph = create_graph();
let expected = ["AB", "BC", "BD", "DE", "EC", "FB"];
graph.each_edge(|idx, edge| {
assert_eq!(expected[idx.0], edge.data);
true
});
}
fn test_adjacent_edges<N: PartialEq + Debug, E: PartialEq + Debug>(graph: &Graph<N, E>,
start_index: NodeIndex,
start_data: N,
expected_incoming: &[(E, N)],
expected_outgoing: &[(E, N)]) {
assert!(graph.node_data(start_index) == &start_data);
let mut counter = 0;
for (edge_index, edge) in graph.incoming_edges(start_index) {
assert!(counter < expected_incoming.len());
debug!("counter={:?} expected={:?} edge_index={:?} edge={:?}",
counter,
expected_incoming[counter],
edge_index,
edge);
match expected_incoming[counter] {
(ref e, ref n) => {
assert!(e == &edge.data);
assert!(n == graph.node_data(edge.source()));
assert!(start_index == edge.target);
}
}
counter += 1;
}
assert_eq!(counter, expected_incoming.len());
let mut counter = 0;
for (edge_index, edge) in graph.outgoing_edges(start_index) {
assert!(counter < expected_outgoing.len());
debug!("counter={:?} expected={:?} edge_index={:?} edge={:?}",
counter,
expected_outgoing[counter],
edge_index,
edge);
match expected_outgoing[counter] {
(ref e, ref n) => {
assert!(e == &edge.data);
assert!(start_index == edge.source);
assert!(n == graph.node_data(edge.target));
}
}
counter += 1;
}
assert_eq!(counter, expected_outgoing.len());
}
#[test]
fn each_adjacent_from_a() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(0), "A", &[], &[("AB", "B")]);
}
#[test]
fn each_adjacent_from_b() {
let graph = create_graph();
test_adjacent_edges(&graph,
NodeIndex(1),
"B",
&[("FB", "F"), ("AB", "A")],
&[("BD", "D"), ("BC", "C")]);
}
#[test]
fn each_adjacent_from_c() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(2), "C", &[("EC", "E"), ("BC", "B")], &[]);
}
#[test]
fn each_adjacent_from_d() {
let graph = create_graph();
test_adjacent_edges(&graph, NodeIndex(3), "D", &[("BD", "B")], &[("DE", "E")]);
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/scc/test.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.
#![cfg(test)]
use graph::test::TestGraph;
use super::*;
#[test]
fn diamond() {
let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 4);
assert_eq!(sccs.num_sccs(), 4);
}
#[test]
fn test_big_scc() {
// The order in which things will be visited is important to this
// test.
//
// We will visit:
//
// 0 -> 1 -> 2 -> 0
//
// and at this point detect a cycle. 2 will return back to 1 which
// will visit 3. 3 will visit 2 before the cycle is complete, and
// hence it too will return a cycle.
/*
+-> 0
| |
| v
| 1 -> 3
| | |
| v |
+-- 2 <--+
*/
let graph = TestGraph::new(0, &[
(0, 1),
(1, 2),
(1, 3),
(2, 0),
(3, 2),
]);
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 1);
}
#[test]
fn test_three_sccs() {
/*
0
|
v
+-> 1 3
| | |
| v |
+-- 2 <--+
*/
let graph = TestGraph::new(0, &[
(0, 1),
(1, 2),
(2, 1),
(3, 2),
]);
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 3);
assert_eq!(sccs.scc(0), 1);
assert_eq!(sccs.scc(1), 0);
assert_eq!(sccs.scc(2), 0);
assert_eq!(sccs.scc(3), 2);
assert_eq!(sccs.successors(0), &[]);
assert_eq!(sccs.successors(1), &[0]);
assert_eq!(sccs.successors(2), &[0]);
}
#[test]
fn test_find_state_2() {
// The order in which things will be visited is important to this
// test. It tests part of the `find_state` behavior. Here is the
// graph:
//
//
// /----+
// 0 <--+ |
// | | |
// v | |
// +-> 1 -> 3 4
// | | |
// | v |
// +-- 2 <----+
let graph = TestGraph::new(0, &[
(0, 1),
(0, 4),
(1, 2),
(1, 3),
(2, 1),
(3, 0),
(4, 2),
]);
// For this graph, we will start in our DFS by visiting:
//
// 0 -> 1 -> 2 -> 1
//
// and at this point detect a cycle. The state of 2 will thus be
// `InCycleWith { 1 }`. We will then visit the 1 -> 3 edge, which
// will attempt to visit 0 as well, thus going to the state
// `InCycleWith { 0 }`. Finally, node 1 will complete; the lowest
// depth of any successor was 3 which had depth 0, and thus it
// will be in the state `InCycleWith { 3 }`.
//
// When we finally traverse the `0 -> 4` edge and then visit node 2,
// the states of the nodes are:
//
// 0 BeingVisited { 0 }
// 1 InCycleWith { 3 }
// 2 InCycleWith { 1 }
// 3 InCycleWith { 0 }
//
// and hence 4 will traverse the links, finding an ultimate depth of 0.
// If will also collapse the states to the following:
//
// 0 BeingVisited { 0 }
// 1 InCycleWith { 3 }
// 2 InCycleWith { 1 }
// 3 InCycleWith { 0 }
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 1);
assert_eq!(sccs.scc(0), 0);
assert_eq!(sccs.scc(1), 0);
assert_eq!(sccs.scc(2), 0);
assert_eq!(sccs.scc(3), 0);
assert_eq!(sccs.scc(4), 0);
assert_eq!(sccs.successors(0), &[]);
}
#[test]
fn test_find_state_3() {
/*
/----+
0 <--+ |
| | |
v | |
+-> 1 -> 3 4 5
| | | |
| v | |
+-- 2 <----+-+
*/
let graph = TestGraph::new(0, &[
(0, 1),
(0, 4),
(1, 2),
(1, 3),
(2, 1),
(3, 0),
(4, 2),
(5, 2),
]);
let sccs: Sccs<_, usize> = Sccs::new(&graph);
assert_eq!(sccs.num_sccs(), 2);
assert_eq!(sccs.scc(0), 0);
assert_eq!(sccs.scc(1), 0);
assert_eq!(sccs.scc(2), 0);
assert_eq!(sccs.scc(3), 0);
assert_eq!(sccs.scc(4), 0);
assert_eq!(sccs.scc(5), 1);
assert_eq!(sccs.successors(0), &[]);
assert_eq!(sccs.successors(1), &[0]);
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/scc/mod.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.
//! Routine to compute the strongly connected components (SCCs) of a
//! graph, as well as the resulting DAG if each SCC is replaced with a
//! node in the graph. This uses Tarjan's algorithm that completes in
//! O(n) time.
use fx::FxHashSet;
use graph::{DirectedGraph, WithNumNodes, WithSuccessors};
use indexed_vec::{Idx, IndexVec};
use std::ops::Range;
mod test;
/// Strongly connected components (SCC) of a graph. The type `N` is
/// the index type for the graph nodes and `S` is the index type for
/// the SCCs. We can map from each node to the SCC that it
/// participates in, and we also have the successors of each SCC.
pub struct Sccs<N: Idx, S: Idx> {
/// For each node, what is the SCC index of the SCC to which it
/// belongs.
scc_indices: IndexVec<N, S>,
/// Data about each SCC.
scc_data: SccData<S>,
}
struct SccData<S: Idx> {
/// For each SCC, the range of `all_successors` where its
/// successors can be found.
ranges: IndexVec<S, Range<usize>>,
/// Contains the succcessors for all the Sccs, concatenated. The
/// range of indices corresponding to a given SCC is found in its
/// SccData.
all_successors: Vec<S>,
}
impl<N: Idx, S: Idx> Sccs<N, S> {
pub fn new(graph: &(impl DirectedGraph<Node = N> + WithNumNodes + WithSuccessors)) -> Self {
SccsConstruction::construct(graph)
}
/// Returns the number of SCCs in the graph.
pub fn num_sccs(&self) -> usize {
self.scc_data.len()
}
/// Returns an iterator over the SCCs in the graph.
pub fn all_sccs(&self) -> impl Iterator<Item = S> {
(0 .. self.scc_data.len()).map(S::new)
}
/// Returns the SCC to which a node `r` belongs.
pub fn scc(&self, r: N) -> S {
self.scc_indices[r]
}
/// Returns the successors of the given SCC.
pub fn successors(&self, scc: S) -> &[S] {
self.scc_data.successors(scc)
}
}
impl<S: Idx> SccData<S> {
/// Number of SCCs,
fn len(&self) -> usize {
self.ranges.len()
}
/// Returns the successors of the given SCC.
fn successors(&self, scc: S) -> &[S] {
// Annoyingly, `range` does not implement `Copy`, so we have
// to do `range.start..range.end`:
let range = &self.ranges[scc];
&self.all_successors[range.start..range.end]
}
/// Creates a new SCC with `successors` as its successors and
/// returns the resulting index.
fn create_scc(&mut self, successors: impl IntoIterator<Item = S>) -> S {
// Store the successors on `scc_successors_vec`, remembering
// the range of indices.
let all_successors_start = self.all_successors.len();
self.all_successors.extend(successors);
let all_successors_end = self.all_successors.len();
debug!(
"create_scc({:?}) successors={:?}",
self.ranges.len(),
&self.all_successors[all_successors_start..all_successors_end],
);
self.ranges.push(all_successors_start..all_successors_end)
}
}
struct SccsConstruction<'c, G: DirectedGraph + WithNumNodes + WithSuccessors + 'c, S: Idx> {
graph: &'c G,
/// The state of each node; used during walk to record the stack
/// and after walk to record what cycle each node ended up being
/// in.
node_states: IndexVec<G::Node, NodeState<G::Node, S>>,
/// The stack of nodes that we are visiting as part of the DFS.
node_stack: Vec<G::Node>,
/// The stack of successors: as we visit a node, we mark our
/// position in this stack, and when we encounter a successor SCC,
/// we push it on the stack. When we complete an SCC, we can pop
/// everything off the stack that was found along the way.
successors_stack: Vec<S>,
/// A set used to strip duplicates. As we accumulate successors
/// into the successors_stack, we sometimes get duplicate entries.
/// We use this set to remove those -- we also keep its storage
/// around between successors to amortize memory allocation costs.
duplicate_set: FxHashSet<S>,
scc_data: SccData<S>,
}
#[derive(Copy, Clone, Debug)]
enum NodeState<N, S> {
/// This node has not yet been visited as part of the DFS.
///
/// After SCC construction is complete, this state ought to be
/// impossible.
NotVisited,
/// This node is currently being walk as part of our DFS. It is on
/// the stack at the depth `depth`.
///
/// After SCC construction is complete, this state ought to be
/// impossible.
BeingVisited { depth: usize },
/// Indicates that this node is a member of the given cycle.
InCycle { scc_index: S },
/// Indicates that this node is a member of whatever cycle
/// `parent` is a member of. This state is transient: whenever we
/// see it, we try to overwrite it with the current state of
/// `parent` (this is the "path compression" step of a union-find
/// algorithm).
InCycleWith { parent: N },
}
#[derive(Copy, Clone, Debug)]
enum WalkReturn<S> {
Cycle { min_depth: usize },
Complete { scc_index: S },
}
impl<'c, G, S> SccsConstruction<'c, G, S>
where
G: DirectedGraph + WithNumNodes + WithSuccessors,
S: Idx,
{
/// Identifies SCCs in the graph `G` and computes the resulting
/// DAG. This uses a variant of [Tarjan's
/// algorithm][wikipedia]. The high-level summary of the algorithm
/// is that we do a depth-first search. Along the way, we keep a
/// stack of each node whose successors are being visited. We
/// track the depth of each node on this stack (there is no depth
/// if the node is not on the stack). When we find that some node
/// N with depth D can reach some other node N' with lower depth
/// D' (i.e., D' < D), we know that N, N', and all nodes in
/// between them on the stack are part of an SCC.
///
/// [wikipedia]: https://bit.ly/2EZIx84
fn construct(graph: &'c G) -> Sccs<G::Node, S> {
let num_nodes = graph.num_nodes();
let mut this = Self {
graph,
node_states: IndexVec::from_elem_n(NodeState::NotVisited, num_nodes),
node_stack: Vec::with_capacity(num_nodes),
successors_stack: Vec::new(),
scc_data: SccData {
ranges: IndexVec::new(),
all_successors: Vec::new(),
},
duplicate_set: FxHashSet::default(),
};
let scc_indices = (0..num_nodes)
.map(G::Node::new)
.map(|node| match this.walk_node(0, node) {
WalkReturn::Complete { scc_index } => scc_index,
WalkReturn::Cycle { min_depth } => panic!(
"`walk_node(0, {:?})` returned cycle with depth {:?}",
node, min_depth
),
})
.collect();
Sccs {
scc_indices,
scc_data: this.scc_data,
}
}
/// Visit a node during the DFS. We first examine its current
/// state -- if it is not yet visited (`NotVisited`), we can push
/// it onto the stack and start walking its successors.
///
/// If it is already on the DFS stack it will be in the state
/// `BeingVisited`. In that case, we have found a cycle and we
/// return the depth from the stack.
///
/// Otherwise, we are looking at a node that has already been
/// completely visited. We therefore return `WalkReturn::Complete`
/// with its associated SCC index.
fn walk_node(&mut self, depth: usize, node: G::Node) -> WalkReturn<S> {
debug!("walk_node(depth = {:?}, node = {:?})", depth, node);
match self.find_state(node) {
NodeState::InCycle { scc_index } => WalkReturn::Complete { scc_index },
NodeState::BeingVisited { depth: min_depth } => WalkReturn::Cycle { min_depth },
NodeState::NotVisited => self.walk_unvisited_node(depth, node),
NodeState::InCycleWith { parent } => panic!(
"`find_state` returned `InCycleWith({:?})`, which ought to be impossible",
parent
),
}
}
/// Fetches the state of the node `r`. If `r` is recorded as being
/// in a cycle with some other node `r2`, then fetches the state
/// of `r2` (and updates `r` to reflect current result). This is
/// basically the "find" part of a standard union-find algorithm
/// (with path compression).
fn find_state(&mut self, r: G::Node) -> NodeState<G::Node, S> {
debug!("find_state(r = {:?} in state {:?})", r, self.node_states[r]);
match self.node_states[r] {
NodeState::InCycle { scc_index } => NodeState::InCycle { scc_index },
NodeState::BeingVisited { depth } => NodeState::BeingVisited { depth },
NodeState::NotVisited => NodeState::NotVisited,
NodeState::InCycleWith { parent } => {
let parent_state = self.find_state(parent);
debug!("find_state: parent_state = {:?}", parent_state);
match parent_state {
NodeState::InCycle { .. } => {
self.node_states[r] = parent_state;
parent_state
}
NodeState::BeingVisited { depth } => {
self.node_states[r] = NodeState::InCycleWith {
parent: self.node_stack[depth],
};
parent_state
}
NodeState::NotVisited | NodeState::InCycleWith { .. } => {
panic!("invalid parent state: {:?}", parent_state)
}
}
}
}
}
/// Walks a node that has never been visited before.
fn walk_unvisited_node(&mut self, depth: usize, node: G::Node) -> WalkReturn<S> {
debug!(
"walk_unvisited_node(depth = {:?}, node = {:?})",
depth, node
);
debug_assert!(match self.node_states[node] {
NodeState::NotVisited => true,
_ => false,
});
// Push `node` onto the stack.
self.node_states[node] = NodeState::BeingVisited { depth };
self.node_stack.push(node);
// Walk each successor of the node, looking to see if any of
// them can reach a node that is presently on the stack. If
// so, that means they can also reach us.
let mut min_depth = depth;
let mut min_cycle_root = node;
let successors_len = self.successors_stack.len();
for successor_node in self.graph.successors(node) {
debug!(
"walk_unvisited_node: node = {:?} successor_ode = {:?}",
node, successor_node
);
match self.walk_node(depth + 1, successor_node) {
WalkReturn::Cycle {
min_depth: successor_min_depth,
} => {
// Track the minimum depth we can reach.
assert!(successor_min_depth <= depth);
if successor_min_depth < min_depth {
debug!(
"walk_unvisited_node: node = {:?} successor_min_depth = {:?}",
node, successor_min_depth
);
min_depth = successor_min_depth;
min_cycle_root = successor_node;
}
}
WalkReturn::Complete {
scc_index: successor_scc_index,
} => {
// Push the completed SCC indices onto
// the `successors_stack` for later.
debug!(
"walk_unvisited_node: node = {:?} successor_scc_index = {:?}",
node, successor_scc_index
);
self.successors_stack.push(successor_scc_index);
}
}
}
// Completed walk, remove `node` from the stack.
let r = self.node_stack.pop();
debug_assert_eq!(r, Some(node));
// If `min_depth == depth`, then we are the root of the
// cycle: we can't reach anyone further down the stack.
if min_depth == depth {
// Note that successor stack may have duplicates, so we
// want to remove those:
let deduplicated_successors = {
let duplicate_set = &mut self.duplicate_set;
duplicate_set.clear();
self.successors_stack
.drain(successors_len..)
.filter(move |&i| duplicate_set.insert(i))
};
let scc_index = self.scc_data.create_scc(deduplicated_successors);
self.node_states[node] = NodeState::InCycle { scc_index };
WalkReturn::Complete { scc_index }
} else {
// We are not the head of the cycle. Return back to our
// caller. They will take ownership of the
// `self.successors` data that we pushed.
self.node_states[node] = NodeState::InCycleWith {
parent: min_cycle_root,
};
WalkReturn::Cycle { min_depth }
}
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/dominators/test.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.
use super::super::test::TestGraph;
use super::*;
#[test]
fn diamond() {
let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
let dominators = dominators(&graph);
let immediate_dominators = dominators.all_immediate_dominators();
assert_eq!(immediate_dominators[0], Some(0));
assert_eq!(immediate_dominators[1], Some(0));
assert_eq!(immediate_dominators[2], Some(0));
assert_eq!(immediate_dominators[3], Some(0));
}
#[test]
fn paper() {
// example from the paper:
let graph = TestGraph::new(6,
&[(6, 5), (6, 4), (5, 1), (4, 2), (4, 3), (1, 2), (2, 3), (3, 2),
(2, 1)]);
let dominators = dominators(&graph);
let immediate_dominators = dominators.all_immediate_dominators();
assert_eq!(immediate_dominators[0], None); // <-- note that 0 is not in graph
assert_eq!(immediate_dominators[1], Some(6));
assert_eq!(immediate_dominators[2], Some(6));
assert_eq!(immediate_dominators[3], Some(6));
assert_eq!(immediate_dominators[4], Some(6));
assert_eq!(immediate_dominators[5], Some(6));
assert_eq!(immediate_dominators[6], Some(6));
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/graph/dominators/mod.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.
//! Algorithm citation:
//! A Simple, Fast Dominance Algorithm.
//! Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
//! Rice Computer Science TS-06-33870
//! <https://www.cs.rice.edu/~keith/EMBED/dom.pdf>
use super::super::indexed_vec::{Idx, IndexVec};
use super::iterate::reverse_post_order;
use super::ControlFlowGraph;
use std::fmt;
#[cfg(test)]
mod test;
pub fn dominators<G: ControlFlowGraph>(graph: &G) -> Dominators<G::Node> {
let start_node = graph.start_node();
let rpo = reverse_post_order(graph, start_node);
dominators_given_rpo(graph, &rpo)
}
pub fn dominators_given_rpo<G: ControlFlowGraph>(
graph: &G,
rpo: &[G::Node],
) -> Dominators<G::Node> {
let start_node = graph.start_node();
assert_eq!(rpo[0], start_node);
// compute the post order index (rank) for each node
let mut post_order_rank: IndexVec<G::Node, usize> =
IndexVec::from_elem_n(usize::default(), graph.num_nodes());
for (index, node) in rpo.iter().rev().cloned().enumerate() {
post_order_rank[node] = index;
}
let mut immediate_dominators: IndexVec<G::Node, Option<G::Node>> =
IndexVec::from_elem_n(Option::default(), graph.num_nodes());
immediate_dominators[start_node] = Some(start_node);
let mut changed = true;
while changed {
changed = false;
for &node in &rpo[1..] {
let mut new_idom = None;
for pred in graph.predecessors(node) {
if immediate_dominators[pred].is_some() {
// (*)
// (*) dominators for `pred` have been calculated
new_idom = intersect_opt(
&post_order_rank,
&immediate_dominators,
new_idom,
Some(pred),
);
}
}
if new_idom != immediate_dominators[node] {
immediate_dominators[node] = new_idom;
changed = true;
}
}
}
Dominators {
post_order_rank,
immediate_dominators,
}
}
fn intersect_opt<Node: Idx>(
post_order_rank: &IndexVec<Node, usize>,
immediate_dominators: &IndexVec<Node, Option<Node>>,
node1: Option<Node>,
node2: Option<Node>,
) -> Option<Node> {
match (node1, node2) {
(None, None) => None,
(Some(n), None) | (None, Some(n)) => Some(n),
(Some(n1), Some(n2)) => Some(intersect(post_order_rank, immediate_dominators, n1, n2)),
}
}
fn intersect<Node: Idx>(
post_order_rank: &IndexVec<Node, usize>,
immediate_dominators: &IndexVec<Node, Option<Node>>,
mut node1: Node,
mut node2: Node,
) -> Node {
while node1 != node2 {
while post_order_rank[node1] < post_order_rank[node2] {
node1 = immediate_dominators[node1].unwrap();
}
while post_order_rank[node2] < post_order_rank[node1] {
node2 = immediate_dominators[node2].unwrap();
}
}
node1
}
#[derive(Clone, Debug)]
pub struct Dominators<N: Idx> {
post_order_rank: IndexVec<N, usize>,
immediate_dominators: IndexVec<N, Option<N>>,
}
impl<Node: Idx> Dominators<Node> {
pub fn is_reachable(&self, node: Node) -> bool {
self.immediate_dominators[node].is_some()
}
pub fn immediate_dominator(&self, node: Node) -> Node {
assert!(self.is_reachable(node), "node {:?} is not reachable", node);
self.immediate_dominators[node].unwrap()
}
pub fn dominators(&self, node: Node) -> Iter<Node> {
assert!(self.is_reachable(node), "node {:?} is not reachable", node);
Iter {
dominators: self,
node: Some(node),
}
}
pub fn is_dominated_by(&self, node: Node, dom: Node) -> bool {
// FIXME -- could be optimized by using post-order-rank
self.dominators(node).any(|n| n == dom)
}
#[cfg(test)]
fn all_immediate_dominators(&self) -> &IndexVec<Node, Option<Node>> {
&self.immediate_dominators
}
}
pub struct Iter<'dom, Node: Idx + 'dom> {
dominators: &'dom Dominators<Node>,
node: Option<Node>,
}
impl<'dom, Node: Idx> Iterator for Iter<'dom, Node> {
type Item = Node;
fn next(&mut self) -> Option<Self::Item> {
if let Some(node) = self.node {
let dom = self.dominators.immediate_dominator(node);
if dom == node {
self.node = None; // reached the root
} else {
self.node = Some(dom);
}
return Some(node);
} else {
return None;
}
}
}
pub struct DominatorTree<N: Idx> {
root: N,
children: IndexVec<N, Vec<N>>,
}
impl<Node: Idx> DominatorTree<Node> {
pub fn children(&self, node: Node) -> &[Node] {
&self.children[node]
}
}
impl<Node: Idx> fmt::Debug for DominatorTree<Node> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(
&DominatorTreeNode {
tree: self,
node: self.root,
},
fmt,
)
}
}
struct DominatorTreeNode<'tree, Node: Idx> {
tree: &'tree DominatorTree<Node>,
node: Node,
}
impl<'tree, Node: Idx> fmt::Debug for DominatorTreeNode<'tree, Node> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let subtrees: Vec<_> = self.tree
.children(self.node)
.iter()
.map(|&child| DominatorTreeNode {
tree: self.tree,
node: child,
})
.collect();
fmt.debug_tuple("")
.field(&self.node)
.field(&subtrees)
.finish()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/obligation_forest/test.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.
#![cfg(test)]
use super::{Error, ObligationForest, ObligationProcessor, Outcome, ProcessResult};
use std::fmt;
use std::marker::PhantomData;
impl<'a> super::ForestObligation for &'a str {
type Predicate = &'a str;
fn as_predicate(&self) -> &Self::Predicate {
self
}
}
struct ClosureObligationProcessor<OF, BF, O, E> {
process_obligation: OF,
_process_backedge: BF,
marker: PhantomData<(O, E)>,
}
#[allow(non_snake_case)]
fn C<OF, BF, O>(of: OF, bf: BF) -> ClosureObligationProcessor<OF, BF, O, &'static str>
where OF: FnMut(&mut O) -> ProcessResult<O, &'static str>,
BF: FnMut(&[O])
{
ClosureObligationProcessor {
process_obligation: of,
_process_backedge: bf,
marker: PhantomData
}
}
impl<OF, BF, O, E> ObligationProcessor for ClosureObligationProcessor<OF, BF, O, E>
where O: super::ForestObligation + fmt::Debug,
E: fmt::Debug,
OF: FnMut(&mut O) -> ProcessResult<O, E>,
BF: FnMut(&[O])
{
type Obligation = O;
type Error = E;
fn process_obligation(&mut self,
obligation: &mut Self::Obligation)
-> ProcessResult<Self::Obligation, Self::Error>
{
(self.process_obligation)(obligation)
}
fn process_backedge<'c, I>(&mut self, _cycle: I,
_marker: PhantomData<&'c Self::Obligation>)
where I: Clone + Iterator<Item=&'c Self::Obligation> {
}
}
#[test]
fn push_pop() {
let mut forest = ObligationForest::new();
forest.register_obligation("A");
forest.register_obligation("B");
forest.register_obligation("C");
// first round, B errors out, A has subtasks, and C completes, creating this:
// A |-> A.1
// |-> A.2
// |-> A.3
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Changed(vec!["A.1", "A.2", "A.3"]),
"B" => ProcessResult::Error("B is for broken"),
"C" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["C"]);
assert_eq!(err,
vec![Error {
error: "B is for broken",
backtrace: vec!["B"],
}]);
// second round: two delays, one success, creating an uneven set of subtasks:
// A |-> A.1
// |-> A.2
// |-> A.3 |-> A.3.i
// D |-> D.1
// |-> D.2
forest.register_obligation("D");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A.1" => ProcessResult::Unchanged,
"A.2" => ProcessResult::Unchanged,
"A.3" => ProcessResult::Changed(vec!["A.3.i"]),
"D" => ProcessResult::Changed(vec!["D.1", "D.2"]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, Vec::<&'static str>::new());
assert_eq!(err, Vec::new());
// third round: ok in A.1 but trigger an error in A.2. Check that it
// propagates to A, but not D.1 or D.2.
// D |-> D.1 |-> D.1.i
// |-> D.2 |-> D.2.i
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A.1" => ProcessResult::Changed(vec![]),
"A.2" => ProcessResult::Error("A is for apple"),
"A.3.i" => ProcessResult::Changed(vec![]),
"D.1" => ProcessResult::Changed(vec!["D.1.i"]),
"D.2" => ProcessResult::Changed(vec!["D.2.i"]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.3", "A.1", "A.3.i"]);
assert_eq!(err,
vec![Error {
error: "A is for apple",
backtrace: vec!["A.2", "A"],
}]);
// fourth round: error in D.1.i
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"D.1.i" => ProcessResult::Error("D is for dumb"),
"D.2.i" => ProcessResult::Changed(vec![]),
_ => panic!("unexpected obligation {:?}", obligation),
}
}, |_| {}));
assert_eq!(ok, vec!["D.2.i", "D.2"]);
assert_eq!(err,
vec![Error {
error: "D is for dumb",
backtrace: vec!["D.1.i", "D.1", "D"],
}]);
}
// Test that if a tree with grandchildren succeeds, everything is
// reported as expected:
// A
// A.1
// A.2
// A.2.i
// A.2.ii
// A.3
#[test]
fn success_in_grandchildren() {
let mut forest = ObligationForest::new();
forest.register_obligation("A");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Changed(vec!["A.1", "A.2", "A.3"]),
_ => unreachable!(),
}
}, |_| {}));
assert!(ok.is_empty());
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A.1" => ProcessResult::Changed(vec![]),
"A.2" => ProcessResult::Changed(vec!["A.2.i", "A.2.ii"]),
"A.3" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.3", "A.1"]);
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A.2.i" => ProcessResult::Changed(vec!["A.2.i.a"]),
"A.2.ii" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.2.ii"]);
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A.2.i.a" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.2.i.a", "A.2.i", "A.2", "A"]);
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|_| unreachable!(), |_| {}));
assert!(ok.is_empty());
assert!(err.is_empty());
}
#[test]
fn to_errors_no_throw() {
// check that converting multiple children with common parent (A)
// yields to correct errors (and does not panic, in particular).
let mut forest = ObligationForest::new();
forest.register_obligation("A");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Changed(vec!["A.1", "A.2", "A.3"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err.len(), 0);
let errors = forest.to_errors(());
assert_eq!(errors[0].backtrace, vec!["A.1", "A"]);
assert_eq!(errors[1].backtrace, vec!["A.2", "A"]);
assert_eq!(errors[2].backtrace, vec!["A.3", "A"]);
assert_eq!(errors.len(), 3);
}
#[test]
fn diamond() {
// check that diamond dependencies are handled correctly
let mut forest = ObligationForest::new();
forest.register_obligation("A");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Changed(vec!["A.1", "A.2"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A.1" => ProcessResult::Changed(vec!["D"]),
"A.2" => ProcessResult::Changed(vec!["D"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err.len(), 0);
let mut d_count = 0;
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"D" => { d_count += 1; ProcessResult::Changed(vec![]) },
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(d_count, 1);
assert_eq!(ok, vec!["D", "A.2", "A.1", "A"]);
assert_eq!(err.len(), 0);
let errors = forest.to_errors(());
assert_eq!(errors.len(), 0);
forest.register_obligation("A'");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A'" => ProcessResult::Changed(vec!["A'.1", "A'.2"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A'.1" => ProcessResult::Changed(vec!["D'", "A'"]),
"A'.2" => ProcessResult::Changed(vec!["D'"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err.len(), 0);
let mut d_count = 0;
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"D'" => { d_count += 1; ProcessResult::Error("operation failed") },
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(d_count, 1);
assert_eq!(ok.len(), 0);
assert_eq!(err, vec![super::Error {
error: "operation failed",
backtrace: vec!["D'", "A'.1", "A'"]
}]);
let errors = forest.to_errors(());
assert_eq!(errors.len(), 0);
}
#[test]
fn done_dependency() {
// check that the local cache works
let mut forest = ObligationForest::new();
forest.register_obligation("A: Sized");
forest.register_obligation("B: Sized");
forest.register_obligation("C: Sized");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A: Sized" | "B: Sized" | "C: Sized" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok, vec!["C: Sized", "B: Sized", "A: Sized"]);
assert_eq!(err.len(), 0);
forest.register_obligation("(A,B,C): Sized");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"(A,B,C): Sized" => ProcessResult::Changed(vec![
"A: Sized",
"B: Sized",
"C: Sized"
]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok, vec!["(A,B,C): Sized"]);
assert_eq!(err.len(), 0);
}
#[test]
fn orphan() {
// check that orphaned nodes are handled correctly
let mut forest = ObligationForest::new();
forest.register_obligation("A");
forest.register_obligation("B");
forest.register_obligation("C1");
forest.register_obligation("C2");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Changed(vec!["D", "E"]),
"B" => ProcessResult::Unchanged,
"C1" => ProcessResult::Changed(vec![]),
"C2" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok, vec!["C2", "C1"]);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"D" | "E" => ProcessResult::Unchanged,
"B" => ProcessResult::Changed(vec!["D"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"D" => ProcessResult::Unchanged,
"E" => ProcessResult::Error("E is for error"),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err, vec![super::Error {
error: "E is for error",
backtrace: vec!["E", "A"]
}]);
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"D" => ProcessResult::Error("D is dead"),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err, vec![super::Error {
error: "D is dead",
backtrace: vec!["D"]
}]);
let errors = forest.to_errors(());
assert_eq!(errors.len(), 0);
}
#[test]
fn simultaneous_register_and_error() {
// check that registering a failed obligation works correctly
let mut forest = ObligationForest::new();
forest.register_obligation("A");
forest.register_obligation("B");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Error("An error"),
"B" => ProcessResult::Changed(vec!["A"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err, vec![super::Error {
error: "An error",
backtrace: vec!["A"]
}]);
let mut forest = ObligationForest::new();
forest.register_obligation("B");
forest.register_obligation("A");
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|obligation| {
match *obligation {
"A" => ProcessResult::Error("An error"),
"B" => ProcessResult::Changed(vec!["A"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
assert_eq!(err, vec![super::Error {
error: "An error",
backtrace: vec!["A"]
}]);
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/obligation_forest/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.
//! The `ObligationForest` is a utility data structure used in trait
//! matching to track the set of outstanding obligations (those not
//! yet resolved to success or error). It also tracks the "backtrace"
//! of each pending obligation (why we are trying to figure this out
//! in the first place). See README.md for a general overview of how
//! to use this class.
use fx::{FxHashMap, FxHashSet};
use std::cell::Cell;
use std::collections::hash_map::Entry;
use std::fmt::Debug;
use std::hash;
use std::marker::PhantomData;
mod node_index;
use self::node_index::NodeIndex;
#[cfg(test)]
mod test;
pub trait ForestObligation : Clone + Debug {
type Predicate : Clone + hash::Hash + Eq + Debug;
fn as_predicate(&self) -> &Self::Predicate;
}
pub trait ObligationProcessor {
type Obligation : ForestObligation;
type Error : Debug;
fn process_obligation(&mut self,
obligation: &mut Self::Obligation)
-> ProcessResult<Self::Obligation, Self::Error>;
/// As we do the cycle check, we invoke this callback when we
/// encounter an actual cycle. `cycle` is an iterator that starts
/// at the start of the cycle in the stack and walks **toward the
/// top**.
///
/// In other words, if we had O1 which required O2 which required
/// O3 which required O1, we would give an iterator yielding O1,
/// O2, O3 (O1 is not yielded twice).
fn process_backedge<'c, I>(&mut self,
cycle: I,
_marker: PhantomData<&'c Self::Obligation>)
where I: Clone + Iterator<Item=&'c Self::Obligation>;
}
/// The result type used by `process_obligation`.
#[derive(Debug)]
pub enum ProcessResult<O, E> {
Unchanged,
Changed(Vec<O>),
Error(E),
}
pub struct ObligationForest<O: ForestObligation> {
/// The list of obligations. In between calls to
/// `process_obligations`, this list only contains nodes in the
/// `Pending` or `Success` state (with a non-zero number of
/// incomplete children). During processing, some of those nodes
/// may be changed to the error state, or we may find that they
/// are completed (That is, `num_incomplete_children` drops to 0).
/// At the end of processing, those nodes will be removed by a
/// call to `compress`.
///
/// At all times we maintain the invariant that every node appears
/// at a higher index than its parent. This is needed by the
/// backtrace iterator (which uses `split_at`).
nodes: Vec<Node<O>>,
/// A cache of predicates that have been successfully completed.
done_cache: FxHashSet<O::Predicate>,
/// An cache of the nodes in `nodes`, indexed by predicate.
waiting_cache: FxHashMap<O::Predicate, NodeIndex>,
scratch: Option<Vec<usize>>,
}
#[derive(Debug)]
struct Node<O> {
obligation: O,
state: Cell<NodeState>,
/// The parent of a node - the original obligation of
/// which it is a subobligation. Except for error reporting,
/// it is just like any member of `dependents`.
parent: Option<NodeIndex>,
/// Obligations that depend on this obligation for their
/// completion. They must all be in a non-pending state.
dependents: Vec<NodeIndex>,
}
/// The state of one node in some tree within the forest. This
/// represents the current state of processing for the obligation (of
/// type `O`) associated with this node.
///
/// Outside of ObligationForest methods, nodes should be either Pending
/// or Waiting.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum NodeState {
/// Obligations for which selection had not yet returned a
/// non-ambiguous result.
Pending,
/// This obligation was selected successfully, but may or
/// may not have subobligations.
Success,
/// This obligation was selected successfully, but it has
/// a pending subobligation.
Waiting,
/// This obligation, along with its subobligations, are complete,
/// and will be removed in the next collection.
Done,
/// This obligation was resolved to an error. Error nodes are
/// removed from the vector by the compression step.
Error,
/// This is a temporary state used in DFS loops to detect cycles,
/// it should not exist outside of these DFSes.
OnDfsStack,
}
#[derive(Debug)]
pub struct Outcome<O, E> {
/// Obligations that were completely evaluated, including all
/// (transitive) subobligations.
pub completed: Vec<O>,
/// Backtrace of obligations that were found to be in error.
pub errors: Vec<Error<O, E>>,
/// If true, then we saw no successful obligations, which means
/// there is no point in further iteration. This is based on the
/// assumption that when trait matching returns `Error` or
/// `Unchanged`, those results do not affect environmental
/// inference state. (Note that if we invoke `process_obligations`
/// with no pending obligations, stalled will be true.)
pub stalled: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Error<O, E> {
pub error: E,
pub backtrace: Vec<O>,
}
impl<O: ForestObligation> ObligationForest<O> {
pub fn new() -> ObligationForest<O> {
ObligationForest {
nodes: vec![],
done_cache: FxHashSet(),
waiting_cache: FxHashMap(),
scratch: Some(vec![]),
}
}
/// Return the total number of nodes in the forest that have not
/// yet been fully resolved.
pub fn len(&self) -> usize {
self.nodes.len()
}
/// Registers an obligation
///
/// This CAN be done in a snapshot
pub fn register_obligation(&mut self, obligation: O) {
// Ignore errors here - there is no guarantee of success.
let _ = self.register_obligation_at(obligation, None);
}
// returns Err(()) if we already know this obligation failed.
fn register_obligation_at(&mut self, obligation: O, parent: Option<NodeIndex>)
-> Result<(), ()>
{
if self.done_cache.contains(obligation.as_predicate()) {
return Ok(())
}
match self.waiting_cache.entry(obligation.as_predicate().clone()) {
Entry::Occupied(o) => {
debug!("register_obligation_at({:?}, {:?}) - duplicate of {:?}!",
obligation, parent, o.get());
let node = &mut self.nodes[o.get().get()];
if let Some(parent) = parent {
// If the node is already in `waiting_cache`, it's already
// been marked with a parent. (It's possible that parent
// has been cleared by `apply_rewrites`, though.) So just
// dump `parent` into `node.dependents`... unless it's
// already in `node.dependents` or `node.parent`.
if !node.dependents.contains(&parent) && Some(parent) != node.parent {
node.dependents.push(parent);
}
}
if let NodeState::Error = node.state.get() {
Err(())
} else {
Ok(())
}
}
Entry::Vacant(v) => {
debug!("register_obligation_at({:?}, {:?}) - ok, new index is {}",
obligation, parent, self.nodes.len());
v.insert(NodeIndex::new(self.nodes.len()));
self.nodes.push(Node::new(parent, obligation));
Ok(())
}
}
}
/// Convert all remaining obligations to the given error.
///
/// This cannot be done during a snapshot.
pub fn to_errors<E: Clone>(&mut self, error: E) -> Vec<Error<O, E>> {
let mut errors = vec![];
for index in 0..self.nodes.len() {
if let NodeState::Pending = self.nodes[index].state.get() {
let backtrace = self.error_at(index);
errors.push(Error {
error: error.clone(),
backtrace,
});
}
}
let successful_obligations = self.compress();
assert!(successful_obligations.is_empty());
errors
}
/// Returns the set of obligations that are in a pending state.
pub fn map_pending_obligations<P, F>(&self, f: F) -> Vec<P>
where F: Fn(&O) -> P
{
self.nodes
.iter()
.filter(|n| n.state.get() == NodeState::Pending)
.map(|n| f(&n.obligation))
.collect()
}
/// Perform a pass through the obligation list. This must
/// be called in a loop until `outcome.stalled` is false.
///
/// This CANNOT be unrolled (presently, at least).
pub fn process_obligations<P>(&mut self, processor: &mut P) -> Outcome<O, P::Error>
where P: ObligationProcessor<Obligation=O>
{
debug!("process_obligations(len={})", self.nodes.len());
let mut errors = vec![];
let mut stalled = true;
for index in 0..self.nodes.len() {
debug!("process_obligations: node {} == {:?}",
index,
self.nodes[index]);
let result = match self.nodes[index] {
Node { state: ref _state, ref mut obligation, .. }
if _state.get() == NodeState::Pending =>
{
processor.process_obligation(obligation)
}
_ => continue
};
debug!("process_obligations: node {} got result {:?}",
index,
result);
match result {
ProcessResult::Unchanged => {
// No change in state.
}
ProcessResult::Changed(children) => {
// We are not (yet) stalled.
stalled = false;
self.nodes[index].state.set(NodeState::Success);
for child in children {
let st = self.register_obligation_at(
child,
Some(NodeIndex::new(index))
);
if let Err(()) = st {
// error already reported - propagate it
// to our node.
self.error_at(index);
}
}
}
ProcessResult::Error(err) => {
stalled = false;
let backtrace = self.error_at(index);
errors.push(Error {
error: err,
backtrace,
});
}
}
}
if stalled {
// There's no need to perform marking, cycle processing and compression when nothing
// changed.
return Outcome {
completed: vec![],
errors,
stalled,
};
}
self.mark_as_waiting();
self.process_cycles(processor);
// Now we have to compress the result
let completed_obligations = self.compress();
debug!("process_obligations: complete");
Outcome {
completed: completed_obligations,
errors,
stalled,
}
}
/// Mark all NodeState::Success nodes as NodeState::Done and
/// report all cycles between them. This should be called
/// after `mark_as_waiting` marks all nodes with pending
/// subobligations as NodeState::Waiting.
fn process_cycles<P>(&mut self, processor: &mut P)
where P: ObligationProcessor<Obligation=O>
{
let mut stack = self.scratch.take().unwrap();
debug_assert!(stack.is_empty());
debug!("process_cycles()");
for index in 0..self.nodes.len() {
// For rustc-benchmarks/inflate-0.1.0 this state test is extremely
// hot and the state is almost always `Pending` or `Waiting`. It's
// a win to handle the no-op cases immediately to avoid the cost of
// the function call.
let state = self.nodes[index].state.get();
match state {
NodeState::Waiting | NodeState::Pending | NodeState::Done | NodeState::Error => {},
_ => self.find_cycles_from_node(&mut stack, processor, index),
}
}
debug!("process_cycles: complete");
debug_assert!(stack.is_empty());
self.scratch = Some(stack);
}
fn find_cycles_from_node<P>(&self, stack: &mut Vec<usize>,
processor: &mut P, index: usize)
where P: ObligationProcessor<Obligation=O>
{
let node = &self.nodes[index];
let state = node.state.get();
match state {
NodeState::OnDfsStack => {
let index =
stack.iter().rposition(|n| *n == index).unwrap();
processor.process_backedge(stack[index..].iter().map(GetObligation(&self.nodes)),
PhantomData);
}
NodeState::Success => {
node.state.set(NodeState::OnDfsStack);
stack.push(index);
for dependent in node.parent.iter().chain(node.dependents.iter()) {
self.find_cycles_from_node(stack, processor, dependent.get());
}
stack.pop();
node.state.set(NodeState::Done);
},
NodeState::Waiting | NodeState::Pending => {
// this node is still reachable from some pending node. We
// will get to it when they are all processed.
}
NodeState::Done | NodeState::Error => {
// already processed that node
}
};
}
/// Returns a vector of obligations for `p` and all of its
/// ancestors, putting them into the error state in the process.
fn error_at(&mut self, p: usize) -> Vec<O> {
let mut error_stack = self.scratch.take().unwrap();
let mut trace = vec![];
let mut n = p;
loop {
self.nodes[n].state.set(NodeState::Error);
trace.push(self.nodes[n].obligation.clone());
error_stack.extend(self.nodes[n].dependents.iter().map(|x| x.get()));
// loop to the parent
match self.nodes[n].parent {
Some(q) => n = q.get(),
None => break
}
}
while let Some(i) = error_stack.pop() {
let node = &self.nodes[i];
match node.state.get() {
NodeState::Error => continue,
_ => node.state.set(NodeState::Error)
}
error_stack.extend(
node.parent.iter().chain(node.dependents.iter()).map(|x| x.get())
);
}
self.scratch = Some(error_stack);
trace
}
#[inline]
fn mark_neighbors_as_waiting_from(&self, node: &Node<O>) {
for dependent in node.parent.iter().chain(node.dependents.iter()) {
self.mark_as_waiting_from(&self.nodes[dependent.get()]);
}
}
/// Marks all nodes that depend on a pending node as NodeState::Waiting.
fn mark_as_waiting(&self) {
for node in &self.nodes {
if node.state.get() == NodeState::Waiting {
node.state.set(NodeState::Success);
}
}
for node in &self.nodes {
if node.state.get() == NodeState::Pending {
self.mark_neighbors_as_waiting_from(node);
}
}
}
fn mark_as_waiting_from(&self, node: &Node<O>) {
match node.state.get() {
NodeState::Waiting | NodeState::Error | NodeState::OnDfsStack => return,
NodeState::Success => node.state.set(NodeState::Waiting),
NodeState::Pending | NodeState::Done => {},
}
self.mark_neighbors_as_waiting_from(node);
}
/// Compresses the vector, removing all popped nodes. This adjusts
/// the indices and hence invalidates any outstanding
/// indices. Cannot be used during a transaction.
///
/// Beforehand, all nodes must be marked as `Done` and no cycles
/// on these nodes may be present. This is done by e.g. `process_cycles`.
#[inline(never)]
fn compress(&mut self) -> Vec<O> {
let nodes_len = self.nodes.len();
let mut node_rewrites: Vec<_> = self.scratch.take().unwrap();
node_rewrites.extend(0..nodes_len);
let mut dead_nodes = 0;
// Now move all popped nodes to the end. Try to keep the order.
//
// LOOP INVARIANT:
// self.nodes[0..i - dead_nodes] are the first remaining nodes
// self.nodes[i - dead_nodes..i] are all dead
// self.nodes[i..] are unchanged
for i in 0..self.nodes.len() {
match self.nodes[i].state.get() {
NodeState::Pending | NodeState::Waiting => {
if dead_nodes > 0 {
self.nodes.swap(i, i - dead_nodes);
node_rewrites[i] -= dead_nodes;
}
}
NodeState::Done => {
// Avoid cloning the key (predicate) in case it exists in the waiting cache
if let Some((predicate, _)) = self.waiting_cache
.remove_entry(self.nodes[i].obligation.as_predicate())
{
self.done_cache.insert(predicate);
} else {
self.done_cache.insert(self.nodes[i].obligation.as_predicate().clone());
}
node_rewrites[i] = nodes_len;
dead_nodes += 1;
}
NodeState::Error => {
// We *intentionally* remove the node from the cache at this point. Otherwise
// tests must come up with a different type on every type error they
// check against.
self.waiting_cache.remove(self.nodes[i].obligation.as_predicate());
node_rewrites[i] = nodes_len;
dead_nodes += 1;
}
NodeState::OnDfsStack | NodeState::Success => unreachable!()
}
}
// No compression needed.
if dead_nodes == 0 {
node_rewrites.truncate(0);
self.scratch = Some(node_rewrites);
return vec![];
}
// Pop off all the nodes we killed and extract the success
// stories.
let successful = (0..dead_nodes)
.map(|_| self.nodes.pop().unwrap())
.flat_map(|node| {
match node.state.get() {
NodeState::Error => None,
NodeState::Done => Some(node.obligation),
_ => unreachable!()
}
})
.collect();
self.apply_rewrites(&node_rewrites);
node_rewrites.truncate(0);
self.scratch = Some(node_rewrites);
successful
}
fn apply_rewrites(&mut self, node_rewrites: &[usize]) {
let nodes_len = node_rewrites.len();
for node in &mut self.nodes {
if let Some(index) = node.parent {
let new_index = node_rewrites[index.get()];
if new_index >= nodes_len {
// parent dead due to error
node.parent = None;
} else {
node.parent = Some(NodeIndex::new(new_index));
}
}
let mut i = 0;
while i < node.dependents.len() {
let new_index = node_rewrites[node.dependents[i].get()];
if new_index >= nodes_len {
node.dependents.swap_remove(i);
} else {
node.dependents[i] = NodeIndex::new(new_index);
i += 1;
}
}
}
let mut kill_list = vec![];
for (predicate, index) in &mut self.waiting_cache {
let new_index = node_rewrites[index.get()];
if new_index >= nodes_len {
kill_list.push(predicate.clone());
} else {
*index = NodeIndex::new(new_index);
}
}
for predicate in kill_list { self.waiting_cache.remove(&predicate); }
}
}
impl<O> Node<O> {
fn new(parent: Option<NodeIndex>, obligation: O) -> Node<O> {
Node {
obligation,
state: Cell::new(NodeState::Pending),
parent,
dependents: vec![],
}
}
}
// I need a Clone closure
#[derive(Clone)]
struct GetObligation<'a, O: 'a>(&'a [Node<O>]);
impl<'a, 'b, O> FnOnce<(&'b usize,)> for GetObligation<'a, O> {
type Output = &'a O;
extern "rust-call" fn call_once(self, args: (&'b usize,)) -> &'a O {
&self.0[*args.0].obligation
}
}
impl<'a, 'b, O> FnMut<(&'b usize,)> for GetObligation<'a, O> {
extern "rust-call" fn call_mut(&mut self, args: (&'b usize,)) -> &'a O {
&self.0[*args.0].obligation
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/obligation_forest/node_index.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.
use std::num::NonZeroU32;
use std::u32;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct NodeIndex {
index: NonZeroU32,
}
impl NodeIndex {
#[inline]
pub fn new(value: usize) -> NodeIndex {
assert!(value < (u32::MAX as usize));
NodeIndex { index: NonZeroU32::new((value as u32) + 1).unwrap() }
}
#[inline]
pub fn get(self) -> usize {
(self.index.get() - 1) as usize
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/owning_ref/LICENSE
|
The MIT License (MIT)
Copyright (c) 2015 Marvin Löbel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_data_structures/owning_ref/mod.rs
|
#![warn(missing_docs)]
/*!
# An owning reference.
This crate provides the _owning reference_ types `OwningRef` and `OwningRefMut`
that enables it to bundle a reference together with the owner of the data it points to.
This allows moving and dropping of a `OwningRef` without needing to recreate the reference.
This can sometimes be useful because Rust borrowing rules normally prevent
moving a type that has been moved from. For example, this kind of code gets rejected:
```rust,ignore
fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) {
let v = vec![1, 2, 3, 4];
let s = &v[1..3];
(v, s)
}
```
Even though, from a memory-layout point of view, this can be entirely safe
if the new location of the vector still lives longer than the lifetime `'a`
of the reference because the backing allocation of the vector does not change.
This library enables this safe usage by keeping the owner and the reference
bundled together in a wrapper type that ensure that lifetime constraint:
```rust
# extern crate owning_ref;
# use owning_ref::OwningRef;
# fn main() {
fn return_owned_and_referenced() -> OwningRef<Vec<u8>, [u8]> {
let v = vec![1, 2, 3, 4];
let or = OwningRef::new(v);
let or = or.map(|v| &v[1..3]);
or
}
# }
```
It works by requiring owner types to dereference to stable memory locations
and preventing mutable access to root containers, which in practice requires heap allocation
as provided by `Box<T>`, `Rc<T>`, etc.
Also provided are typedefs for common owner type combinations,
which allow for less verbose type signatures. For example, `BoxRef<T>` instead of `OwningRef<Box<T>, T>`.
The crate also provides the more advanced `OwningHandle` type,
which allows more freedom in bundling a dependent handle object
along with the data it depends on, at the cost of some unsafe needed in the API.
See the documentation around `OwningHandle` for more details.
# Examples
## Basics
```
extern crate owning_ref;
use owning_ref::BoxRef;
fn main() {
// Create an array owned by a Box.
let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>;
// Transfer into a BoxRef.
let arr: BoxRef<[i32]> = BoxRef::new(arr);
assert_eq!(&*arr, &[1, 2, 3, 4]);
// We can slice the array without losing ownership or changing type.
let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]);
assert_eq!(&*arr, &[2, 3]);
// Also works for Arc, Rc, String and Vec!
}
```
## Caching a reference to a struct field
```
extern crate owning_ref;
use owning_ref::BoxRef;
fn main() {
struct Foo {
tag: u32,
x: u16,
y: u16,
z: u16,
}
let foo = Foo { tag: 1, x: 100, y: 200, z: 300 };
let or = BoxRef::new(Box::new(foo)).map(|foo| {
match foo.tag {
0 => &foo.x,
1 => &foo.y,
2 => &foo.z,
_ => panic!(),
}
});
assert_eq!(*or, 200);
}
```
## Caching a reference to an entry in a vector
```
extern crate owning_ref;
use owning_ref::VecRef;
fn main() {
let v = VecRef::new(vec![1, 2, 3, 4, 5]).map(|v| &v[3]);
assert_eq!(*v, 4);
}
```
## Caching a subslice of a String
```
extern crate owning_ref;
use owning_ref::StringRef;
fn main() {
let s = StringRef::new("hello world".to_owned())
.map(|s| s.split(' ').nth(1).unwrap());
assert_eq!(&*s, "world");
}
```
## Reference counted slices that share ownership of the backing storage
```
extern crate owning_ref;
use owning_ref::RcRef;
use std::rc::Rc;
fn main() {
let rc: RcRef<[i32]> = RcRef::new(Rc::new([1, 2, 3, 4]) as Rc<[i32]>);
assert_eq!(&*rc, &[1, 2, 3, 4]);
let rc_a: RcRef<[i32]> = rc.clone().map(|s| &s[0..2]);
let rc_b = rc.clone().map(|s| &s[1..3]);
let rc_c = rc.clone().map(|s| &s[2..4]);
assert_eq!(&*rc_a, &[1, 2]);
assert_eq!(&*rc_b, &[2, 3]);
assert_eq!(&*rc_c, &[3, 4]);
let rc_c_a = rc_c.clone().map(|s| &s[1]);
assert_eq!(&*rc_c_a, &4);
}
```
## Atomic reference counted slices that share ownership of the backing storage
```
extern crate owning_ref;
use owning_ref::ArcRef;
use std::sync::Arc;
fn main() {
use std::thread;
fn par_sum(rc: ArcRef<[i32]>) -> i32 {
if rc.len() == 0 {
return 0;
} else if rc.len() == 1 {
return rc[0];
}
let mid = rc.len() / 2;
let left = rc.clone().map(|s| &s[..mid]);
let right = rc.map(|s| &s[mid..]);
let left = thread::spawn(move || par_sum(left));
let right = thread::spawn(move || par_sum(right));
left.join().unwrap() + right.join().unwrap()
}
let rc: Arc<[i32]> = Arc::new([1, 2, 3, 4]);
let rc: ArcRef<[i32]> = rc.into();
assert_eq!(par_sum(rc), 10);
}
```
## References into RAII locks
```
extern crate owning_ref;
use owning_ref::RefRef;
use std::cell::{RefCell, Ref};
fn main() {
let refcell = RefCell::new((1, 2, 3, 4));
// Also works with Mutex and RwLock
let refref = {
let refref = RefRef::new(refcell.borrow()).map(|x| &x.3);
assert_eq!(*refref, 4);
// We move the RAII lock and the reference to one of
// the subfields in the data it guards here:
refref
};
assert_eq!(*refref, 4);
drop(refref);
assert_eq!(*refcell.borrow(), (1, 2, 3, 4));
}
```
## Mutable reference
When the owned container implements `DerefMut`, it is also possible to make
a _mutable owning reference_. (E.g. with `Box`, `RefMut`, `MutexGuard`)
```
extern crate owning_ref;
use owning_ref::RefMutRefMut;
use std::cell::{RefCell, RefMut};
fn main() {
let refcell = RefCell::new((1, 2, 3, 4));
let mut refmut_refmut = {
let mut refmut_refmut = RefMutRefMut::new(refcell.borrow_mut()).map_mut(|x| &mut x.3);
assert_eq!(*refmut_refmut, 4);
*refmut_refmut *= 2;
refmut_refmut
};
assert_eq!(*refmut_refmut, 8);
*refmut_refmut *= 2;
drop(refmut_refmut);
assert_eq!(*refcell.borrow(), (1, 2, 3, 16));
}
```
*/
use std::mem;
pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
/// An owning reference.
///
/// This wraps an owner `O` and a reference `&T` pointing
/// at something reachable from `O::Target` while keeping
/// the ability to move `self` around.
///
/// The owner is usually a pointer that points at some base type.
///
/// For more details and examples, see the module and method docs.
pub struct OwningRef<O, T: ?Sized> {
owner: O,
reference: *const T,
}
/// An mutable owning reference.
///
/// This wraps an owner `O` and a reference `&mut T` pointing
/// at something reachable from `O::Target` while keeping
/// the ability to move `self` around.
///
/// The owner is usually a pointer that points at some base type.
///
/// For more details and examples, see the module and method docs.
pub struct OwningRefMut<O, T: ?Sized> {
owner: O,
reference: *mut T,
}
/// Helper trait for an erased concrete type an owner dereferences to.
/// This is used in form of a trait object for keeping
/// something around to (virtually) call the destructor.
pub trait Erased {}
impl<T> Erased for T {}
/// Helper trait for erasing the concrete type of what an owner dereferences to,
/// for example `Box<T> -> Box<Erased>`. This would be unneeded with
/// higher kinded types support in the language.
pub unsafe trait IntoErased<'a> {
/// Owner with the dereference type substituted to `Erased`.
type Erased;
/// Perform the type erasure.
fn into_erased(self) -> Self::Erased;
}
/// Helper trait for erasing the concrete type of what an owner dereferences to,
/// for example `Box<T> -> Box<Erased + Send>`. This would be unneeded with
/// higher kinded types support in the language.
pub unsafe trait IntoErasedSend<'a> {
/// Owner with the dereference type substituted to `Erased + Send`.
type Erased: Send;
/// Perform the type erasure.
fn into_erased_send(self) -> Self::Erased;
}
/// Helper trait for erasing the concrete type of what an owner dereferences to,
/// for example `Box<T> -> Box<Erased + Send + Sync>`. This would be unneeded with
/// higher kinded types support in the language.
pub unsafe trait IntoErasedSendSync<'a> {
/// Owner with the dereference type substituted to `Erased + Send + Sync`.
type Erased: Send + Sync;
/// Perform the type erasure.
fn into_erased_send_sync(self) -> Self::Erased;
}
/////////////////////////////////////////////////////////////////////////////
// OwningRef
/////////////////////////////////////////////////////////////////////////////
impl<O, T: ?Sized> OwningRef<O, T> {
/// Creates a new owning reference from a owner
/// initialized to the direct dereference of it.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRef;
///
/// fn main() {
/// let owning_ref = OwningRef::new(Box::new(42));
/// assert_eq!(*owning_ref, 42);
/// }
/// ```
pub fn new(o: O) -> Self
where O: StableAddress,
O: Deref<Target = T>,
{
OwningRef {
reference: &*o,
owner: o,
}
}
/// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait.
/// Instead, the caller is responsible to make the same promises as implementing the trait.
///
/// This is useful for cases where coherence rules prevents implementing the trait
/// without adding a dependency to this crate in a third-party library.
pub unsafe fn new_assert_stable_address(o: O) -> Self
where O: Deref<Target = T>,
{
OwningRef {
reference: &*o,
owner: o,
}
}
/// Converts `self` into a new owning reference that points at something reachable
/// from the previous one.
///
/// This can be a reference to a field of `U`, something reachable from a field of
/// `U`, or even something unrelated with a `'static` lifetime.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRef;
///
/// fn main() {
/// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
///
/// // create a owning reference that points at the
/// // third element of the array.
/// let owning_ref = owning_ref.map(|array| &array[2]);
/// assert_eq!(*owning_ref, 3);
/// }
/// ```
pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
where O: StableAddress,
F: FnOnce(&T) -> &U
{
OwningRef {
reference: f(&self),
owner: self.owner,
}
}
/// Tries to convert `self` into a new owning reference that points
/// at something reachable from the previous one.
///
/// This can be a reference to a field of `U`, something reachable from a field of
/// `U`, or even something unrelated with a `'static` lifetime.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRef;
///
/// fn main() {
/// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
///
/// // create a owning reference that points at the
/// // third element of the array.
/// let owning_ref = owning_ref.try_map(|array| {
/// if array[2] == 3 { Ok(&array[2]) } else { Err(()) }
/// });
/// assert_eq!(*owning_ref.unwrap(), 3);
/// }
/// ```
pub fn try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E>
where O: StableAddress,
F: FnOnce(&T) -> Result<&U, E>
{
Ok(OwningRef {
reference: f(&self)?,
owner: self.owner,
})
}
/// Converts `self` into a new owning reference with a different owner type.
///
/// The new owner type needs to still contain the original owner in some way
/// so that the reference into it remains valid. This function is marked unsafe
/// because the user needs to manually uphold this guarantee.
pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRef<P, T>
where O: StableAddress,
P: StableAddress,
F: FnOnce(O) -> P
{
OwningRef {
reference: self.reference,
owner: f(self.owner),
}
}
/// Converts `self` into a new owning reference where the owner is wrapped
/// in an additional `Box<O>`.
///
/// This can be used to safely erase the owner of any `OwningRef<O, T>`
/// to a `OwningRef<Box<Erased>, T>`.
pub fn map_owner_box(self) -> OwningRef<Box<O>, T> {
OwningRef {
reference: self.reference,
owner: Box::new(self.owner),
}
}
/// Erases the concrete base type of the owner with a trait object.
///
/// This allows mixing of owned references with different owner base types.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::{OwningRef, Erased};
///
/// fn main() {
/// // NB: Using the concrete types here for explicitnes.
/// // For less verbose code type aliases like `BoxRef` are provided.
///
/// let owning_ref_a: OwningRef<Box<[i32; 4]>, [i32; 4]>
/// = OwningRef::new(Box::new([1, 2, 3, 4]));
///
/// let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
/// = OwningRef::new(Box::new(vec![(0, false), (1, true)]));
///
/// let owning_ref_a: OwningRef<Box<[i32; 4]>, i32>
/// = owning_ref_a.map(|a| &a[0]);
///
/// let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, i32>
/// = owning_ref_b.map(|a| &a[1].0);
///
/// let owning_refs: [OwningRef<Box<Erased>, i32>; 2]
/// = [owning_ref_a.erase_owner(), owning_ref_b.erase_owner()];
///
/// assert_eq!(*owning_refs[0], 1);
/// assert_eq!(*owning_refs[1], 1);
/// }
/// ```
pub fn erase_owner<'a>(self) -> OwningRef<O::Erased, T>
where O: IntoErased<'a>,
{
OwningRef {
reference: self.reference,
owner: self.owner.into_erased(),
}
}
/// Erases the concrete base type of the owner with a trait object which implements `Send`.
///
/// This allows mixing of owned references with different owner base types.
pub fn erase_send_owner<'a>(self) -> OwningRef<O::Erased, T>
where O: IntoErasedSend<'a>,
{
OwningRef {
reference: self.reference,
owner: self.owner.into_erased_send(),
}
}
/// Erases the concrete base type of the owner with a trait object which implements `Send` and `Sync`.
///
/// This allows mixing of owned references with different owner base types.
pub fn erase_send_sync_owner<'a>(self) -> OwningRef<O::Erased, T>
where O: IntoErasedSendSync<'a>,
{
OwningRef {
reference: self.reference,
owner: self.owner.into_erased_send_sync(),
}
}
// TODO: wrap_owner
// FIXME: Naming convention?
/// A getter for the underlying owner.
pub fn owner(&self) -> &O {
&self.owner
}
// FIXME: Naming convention?
/// Discards the reference and retrieves the owner.
pub fn into_inner(self) -> O {
self.owner
}
}
impl<O, T: ?Sized> OwningRefMut<O, T> {
/// Creates a new owning reference from a owner
/// initialized to the direct dereference of it.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRefMut;
///
/// fn main() {
/// let owning_ref_mut = OwningRefMut::new(Box::new(42));
/// assert_eq!(*owning_ref_mut, 42);
/// }
/// ```
pub fn new(mut o: O) -> Self
where O: StableAddress,
O: DerefMut<Target = T>,
{
OwningRefMut {
reference: &mut *o,
owner: o,
}
}
/// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait.
/// Instead, the caller is responsible to make the same promises as implementing the trait.
///
/// This is useful for cases where coherence rules prevents implementing the trait
/// without adding a dependency to this crate in a third-party library.
pub unsafe fn new_assert_stable_address(mut o: O) -> Self
where O: DerefMut<Target = T>,
{
OwningRefMut {
reference: &mut *o,
owner: o,
}
}
/// Converts `self` into a new _shared_ owning reference that points at
/// something reachable from the previous one.
///
/// This can be a reference to a field of `U`, something reachable from a field of
/// `U`, or even something unrelated with a `'static` lifetime.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRefMut;
///
/// fn main() {
/// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
///
/// // create a owning reference that points at the
/// // third element of the array.
/// let owning_ref = owning_ref_mut.map(|array| &array[2]);
/// assert_eq!(*owning_ref, 3);
/// }
/// ```
pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U>
where O: StableAddress,
F: FnOnce(&mut T) -> &U
{
OwningRef {
reference: f(&mut self),
owner: self.owner,
}
}
/// Converts `self` into a new _mutable_ owning reference that points at
/// something reachable from the previous one.
///
/// This can be a reference to a field of `U`, something reachable from a field of
/// `U`, or even something unrelated with a `'static` lifetime.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRefMut;
///
/// fn main() {
/// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
///
/// // create a owning reference that points at the
/// // third element of the array.
/// let owning_ref_mut = owning_ref_mut.map_mut(|array| &mut array[2]);
/// assert_eq!(*owning_ref_mut, 3);
/// }
/// ```
pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U>
where O: StableAddress,
F: FnOnce(&mut T) -> &mut U
{
OwningRefMut {
reference: f(&mut self),
owner: self.owner,
}
}
/// Tries to convert `self` into a new _shared_ owning reference that points
/// at something reachable from the previous one.
///
/// This can be a reference to a field of `U`, something reachable from a field of
/// `U`, or even something unrelated with a `'static` lifetime.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRefMut;
///
/// fn main() {
/// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
///
/// // create a owning reference that points at the
/// // third element of the array.
/// let owning_ref = owning_ref_mut.try_map(|array| {
/// if array[2] == 3 { Ok(&array[2]) } else { Err(()) }
/// });
/// assert_eq!(*owning_ref.unwrap(), 3);
/// }
/// ```
pub fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E>
where O: StableAddress,
F: FnOnce(&mut T) -> Result<&U, E>
{
Ok(OwningRef {
reference: f(&mut self)?,
owner: self.owner,
})
}
/// Tries to convert `self` into a new _mutable_ owning reference that points
/// at something reachable from the previous one.
///
/// This can be a reference to a field of `U`, something reachable from a field of
/// `U`, or even something unrelated with a `'static` lifetime.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::OwningRefMut;
///
/// fn main() {
/// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
///
/// // create a owning reference that points at the
/// // third element of the array.
/// let owning_ref_mut = owning_ref_mut.try_map_mut(|array| {
/// if array[2] == 3 { Ok(&mut array[2]) } else { Err(()) }
/// });
/// assert_eq!(*owning_ref_mut.unwrap(), 3);
/// }
/// ```
pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E>
where O: StableAddress,
F: FnOnce(&mut T) -> Result<&mut U, E>
{
Ok(OwningRefMut {
reference: f(&mut self)?,
owner: self.owner,
})
}
/// Converts `self` into a new owning reference with a different owner type.
///
/// The new owner type needs to still contain the original owner in some way
/// so that the reference into it remains valid. This function is marked unsafe
/// because the user needs to manually uphold this guarantee.
pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<P, T>
where O: StableAddress,
P: StableAddress,
F: FnOnce(O) -> P
{
OwningRefMut {
reference: self.reference,
owner: f(self.owner),
}
}
/// Converts `self` into a new owning reference where the owner is wrapped
/// in an additional `Box<O>`.
///
/// This can be used to safely erase the owner of any `OwningRefMut<O, T>`
/// to a `OwningRefMut<Box<Erased>, T>`.
pub fn map_owner_box(self) -> OwningRefMut<Box<O>, T> {
OwningRefMut {
reference: self.reference,
owner: Box::new(self.owner),
}
}
/// Erases the concrete base type of the owner with a trait object.
///
/// This allows mixing of owned references with different owner base types.
///
/// # Example
/// ```
/// extern crate owning_ref;
/// use owning_ref::{OwningRefMut, Erased};
///
/// fn main() {
/// // NB: Using the concrete types here for explicitnes.
/// // For less verbose code type aliases like `BoxRef` are provided.
///
/// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]>
/// = OwningRefMut::new(Box::new([1, 2, 3, 4]));
///
/// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
/// = OwningRefMut::new(Box::new(vec![(0, false), (1, true)]));
///
/// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, i32>
/// = owning_ref_mut_a.map_mut(|a| &mut a[0]);
///
/// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, i32>
/// = owning_ref_mut_b.map_mut(|a| &mut a[1].0);
///
/// let owning_refs_mut: [OwningRefMut<Box<Erased>, i32>; 2]
/// = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()];
///
/// assert_eq!(*owning_refs_mut[0], 1);
/// assert_eq!(*owning_refs_mut[1], 1);
/// }
/// ```
pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T>
where O: IntoErased<'a>,
{
OwningRefMut {
reference: self.reference,
owner: self.owner.into_erased(),
}
}
// TODO: wrap_owner
// FIXME: Naming convention?
/// A getter for the underlying owner.
pub fn owner(&self) -> &O {
&self.owner
}
// FIXME: Naming convention?
/// Discards the reference and retrieves the owner.
pub fn into_inner(self) -> O {
self.owner
}
}
/////////////////////////////////////////////////////////////////////////////
// OwningHandle
/////////////////////////////////////////////////////////////////////////////
use std::ops::{Deref, DerefMut};
/// `OwningHandle` is a complement to `OwningRef`. Where `OwningRef` allows
/// consumers to pass around an owned object and a dependent reference,
/// `OwningHandle` contains an owned object and a dependent _object_.
///
/// `OwningHandle` can encapsulate a `RefMut` along with its associated
/// `RefCell`, or an `RwLockReadGuard` along with its associated `RwLock`.
/// However, the API is completely generic and there are no restrictions on
/// what types of owning and dependent objects may be used.
///
/// `OwningHandle` is created by passing an owner object (which dereferences
/// to a stable address) along with a callback which receives a pointer to
/// that stable location. The callback may then dereference the pointer and
/// mint a dependent object, with the guarantee that the returned object will
/// not outlive the referent of the pointer.
///
/// Since the callback needs to dereference a raw pointer, it requires `unsafe`
/// code. To avoid forcing this unsafety on most callers, the `ToHandle` trait is
/// implemented for common data structures. Types that implement `ToHandle` can
/// be wrapped into an `OwningHandle` without passing a callback.
pub struct OwningHandle<O, H>
where O: StableAddress, H: Deref,
{
handle: H,
_owner: O,
}
impl<O, H> Deref for OwningHandle<O, H>
where O: StableAddress, H: Deref,
{
type Target = H::Target;
fn deref(&self) -> &H::Target {
self.handle.deref()
}
}
unsafe impl<O, H> StableAddress for OwningHandle<O, H>
where O: StableAddress, H: StableAddress,
{}
impl<O, H> DerefMut for OwningHandle<O, H>
where O: StableAddress, H: DerefMut,
{
fn deref_mut(&mut self) -> &mut H::Target {
self.handle.deref_mut()
}
}
/// Trait to implement the conversion of owner to handle for common types.
pub trait ToHandle {
/// The type of handle to be encapsulated by the OwningHandle.
type Handle: Deref;
/// Given an appropriately-long-lived pointer to ourselves, create a
/// handle to be encapsulated by the `OwningHandle`.
unsafe fn to_handle(x: *const Self) -> Self::Handle;
}
/// Trait to implement the conversion of owner to mutable handle for common types.
pub trait ToHandleMut {
/// The type of handle to be encapsulated by the OwningHandle.
type HandleMut: DerefMut;
/// Given an appropriately-long-lived pointer to ourselves, create a
/// mutable handle to be encapsulated by the `OwningHandle`.
unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut;
}
impl<O, H> OwningHandle<O, H>
where O: StableAddress, O::Target: ToHandle<Handle = H>, H: Deref,
{
/// Create a new `OwningHandle` for a type that implements `ToHandle`. For types
/// that don't implement `ToHandle`, callers may invoke `new_with_fn`, which accepts
/// a callback to perform the conversion.
pub fn new(o: O) -> Self {
OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) })
}
}
impl<O, H> OwningHandle<O, H>
where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut,
{
/// Create a new mutable `OwningHandle` for a type that implements `ToHandleMut`.
pub fn new_mut(o: O) -> Self {
OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) })
}
}
impl<O, H> OwningHandle<O, H>
where O: StableAddress, H: Deref,
{
/// Create a new OwningHandle. The provided callback will be invoked with
/// a pointer to the object owned by `o`, and the returned value is stored
/// as the object to which this `OwningHandle` will forward `Deref` and
/// `DerefMut`.
pub fn new_with_fn<F>(o: O, f: F) -> Self
where F: FnOnce(*const O::Target) -> H
{
let h: H;
{
h = f(o.deref() as *const O::Target);
}
OwningHandle {
handle: h,
_owner: o,
}
}
/// Create a new OwningHandle. The provided callback will be invoked with
/// a pointer to the object owned by `o`, and the returned value is stored
/// as the object to which this `OwningHandle` will forward `Deref` and
/// `DerefMut`.
pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E>
where F: FnOnce(*const O::Target) -> Result<H, E>
{
let h: H;
{
h = f(o.deref() as *const O::Target)?;
}
Ok(OwningHandle {
handle: h,
_owner: o,
})
}
}
/////////////////////////////////////////////////////////////////////////////
// std traits
/////////////////////////////////////////////////////////////////////////////
use std::convert::From;
use std::fmt::{self, Debug};
use std::marker::{Send, Sync};
use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};
use std::hash::{Hash, Hasher};
use std::borrow::Borrow;
impl<O, T: ?Sized> Deref for OwningRef<O, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
&*self.reference
}
}
}
impl<O, T: ?Sized> Deref for OwningRefMut<O, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
&*self.reference
}
}
}
impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe {
&mut *self.reference
}
}
}
unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {}
impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> {
fn as_ref(&self) -> &T {
&*self
}
}
impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> {
fn as_ref(&self) -> &T {
&*self
}
}
impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> {
fn as_mut(&mut self) -> &mut T {
&mut *self
}
}
impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> {
fn borrow(&self) -> &T {
&*self
}
}
impl<O, T: ?Sized> From<O> for OwningRef<O, T>
where O: StableAddress,
O: Deref<Target = T>,
{
fn from(owner: O) -> Self {
OwningRef::new(owner)
}
}
impl<O, T: ?Sized> From<O> for OwningRefMut<O, T>
where O: StableAddress,
O: DerefMut<Target = T>
{
fn from(owner: O) -> Self {
OwningRefMut::new(owner)
}
}
impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T>
where O: StableAddress,
O: DerefMut<Target = T>
{
fn from(other: OwningRefMut<O, T>) -> Self {
OwningRef {
owner: other.owner,
reference: other.reference,
}
}
}
// ^ FIXME: Is a Into impl for calling into_inner() possible as well?
impl<O, T: ?Sized> Debug for OwningRef<O, T>
where O: Debug,
T: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"OwningRef {{ owner: {:?}, reference: {:?} }}",
self.owner(),
&**self)
}
}
impl<O, T: ?Sized> Debug for OwningRefMut<O, T>
where O: Debug,
T: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"OwningRefMut {{ owner: {:?}, reference: {:?} }}",
self.owner(),
&**self)
}
}
impl<O, T: ?Sized> Clone for OwningRef<O, T>
where O: CloneStableAddress,
{
fn clone(&self) -> Self {
OwningRef {
owner: self.owner.clone(),
reference: self.reference,
}
}
}
unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T>
where O: CloneStableAddress {}
unsafe impl<O, T: ?Sized> Send for OwningRef<O, T>
where O: Send, for<'a> (&'a T): Send {}
unsafe impl<O, T: ?Sized> Sync for OwningRef<O, T>
where O: Sync, for<'a> (&'a T): Sync {}
unsafe impl<O, T: ?Sized> Send for OwningRefMut<O, T>
where O: Send, for<'a> (&'a mut T): Send {}
unsafe impl<O, T: ?Sized> Sync for OwningRefMut<O, T>
where O: Sync, for<'a> (&'a mut T): Sync {}
impl Debug for dyn Erased {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Erased>",)
}
}
impl<O, T: ?Sized> PartialEq for OwningRef<O, T> where T: PartialEq {
fn eq(&self, other: &Self) -> bool {
(&*self as &T).eq(&*other as &T)
}
}
impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {}
impl<O, T: ?Sized> PartialOrd for OwningRef<O, T> where T: PartialOrd {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(&*self as &T).partial_cmp(&*other as &T)
}
}
impl<O, T: ?Sized> Ord for OwningRef<O, T> where T: Ord {
fn cmp(&self, other: &Self) -> Ordering {
(&*self as &T).cmp(&*other as &T)
}
}
impl<O, T: ?Sized> Hash for OwningRef<O, T> where T: Hash {
fn hash<H: Hasher>(&self, state: &mut H) {
(&*self as &T).hash(state);
}
}
impl<O, T: ?Sized> PartialEq for OwningRefMut<O, T> where T: PartialEq {
fn eq(&self, other: &Self) -> bool {
(&*self as &T).eq(&*other as &T)
}
}
impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {}
impl<O, T: ?Sized> PartialOrd for OwningRefMut<O, T> where T: PartialOrd {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(&*self as &T).partial_cmp(&*other as &T)
}
}
impl<O, T: ?Sized> Ord for OwningRefMut<O, T> where T: Ord {
fn cmp(&self, other: &Self) -> Ordering {
(&*self as &T).cmp(&*other as &T)
}
}
impl<O, T: ?Sized> Hash for OwningRefMut<O, T> where T: Hash {
fn hash<H: Hasher>(&self, state: &mut H) {
(&*self as &T).hash(state);
}
}
/////////////////////////////////////////////////////////////////////////////
// std types integration and convenience type defs
/////////////////////////////////////////////////////////////////////////////
use std::boxed::Box;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
use std::cell::{Ref, RefCell, RefMut};
impl<T: 'static> ToHandle for RefCell<T> {
type Handle = Ref<'static, T>;
unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() }
}
impl<T: 'static> ToHandleMut for RefCell<T> {
type HandleMut = RefMut<'static, T>;
unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() }
}
// NB: Implementing ToHandle{,Mut} for Mutex and RwLock requires a decision
// about which handle creation to use (i.e. read() vs try_read()) as well as
// what to do with error results.
/// Typedef of a owning reference that uses a `Box` as the owner.
pub type BoxRef<T, U = T> = OwningRef<Box<T>, U>;
/// Typedef of a owning reference that uses a `Vec` as the owner.
pub type VecRef<T, U = T> = OwningRef<Vec<T>, U>;
/// Typedef of a owning reference that uses a `String` as the owner.
pub type StringRef = OwningRef<String, str>;
/// Typedef of a owning reference that uses a `Rc` as the owner.
pub type RcRef<T, U = T> = OwningRef<Rc<T>, U>;
/// Typedef of a owning reference that uses a `Arc` as the owner.
pub type ArcRef<T, U = T> = OwningRef<Arc<T>, U>;
/// Typedef of a owning reference that uses a `Ref` as the owner.
pub type RefRef<'a, T, U = T> = OwningRef<Ref<'a, T>, U>;
/// Typedef of a owning reference that uses a `RefMut` as the owner.
pub type RefMutRef<'a, T, U = T> = OwningRef<RefMut<'a, T>, U>;
/// Typedef of a owning reference that uses a `MutexGuard` as the owner.
pub type MutexGuardRef<'a, T, U = T> = OwningRef<MutexGuard<'a, T>, U>;
/// Typedef of a owning reference that uses a `RwLockReadGuard` as the owner.
pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<RwLockReadGuard<'a, T>, U>;
/// Typedef of a owning reference that uses a `RwLockWriteGuard` as the owner.
pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>;
/// Typedef of a mutable owning reference that uses a `Box` as the owner.
pub type BoxRefMut<T, U = T> = OwningRefMut<Box<T>, U>;
/// Typedef of a mutable owning reference that uses a `Vec` as the owner.
pub type VecRefMut<T, U = T> = OwningRefMut<Vec<T>, U>;
/// Typedef of a mutable owning reference that uses a `String` as the owner.
pub type StringRefMut = OwningRefMut<String, str>;
/// Typedef of a mutable owning reference that uses a `RefMut` as the owner.
pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<RefMut<'a, T>, U>;
/// Typedef of a mutable owning reference that uses a `MutexGuard` as the owner.
pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<MutexGuard<'a, T>, U>;
/// Typedef of a mutable owning reference that uses a `RwLockWriteGuard` as the owner.
pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>;
unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> {
type Erased = Box<dyn Erased + 'a>;
fn into_erased(self) -> Self::Erased {
self
}
}
unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> {
type Erased = Rc<dyn Erased + 'a>;
fn into_erased(self) -> Self::Erased {
self
}
}
unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> {
type Erased = Arc<dyn Erased + 'a>;
fn into_erased(self) -> Self::Erased {
self
}
}
unsafe impl<'a, T: Send + 'a> IntoErasedSend<'a> for Box<T> {
type Erased = Box<dyn Erased + Send + 'a>;
fn into_erased_send(self) -> Self::Erased {
self
}
}
unsafe impl<'a, T: Send + 'a> IntoErasedSendSync<'a> for Box<T> {
type Erased = Box<dyn Erased + Sync + Send + 'a>;
fn into_erased_send_sync(self) -> Self::Erased {
let result: Box<dyn Erased + Send + 'a> = self;
// This is safe since Erased can always implement Sync
// Only the destructor is available and it takes &mut self
unsafe {
mem::transmute(result)
}
}
}
unsafe impl<'a, T: Send + Sync + 'a> IntoErasedSendSync<'a> for Arc<T> {
type Erased = Arc<dyn Erased + Send + Sync + 'a>;
fn into_erased_send_sync(self) -> Self::Erased {
self
}
}
/// Typedef of a owning reference that uses an erased `Box` as the owner.
pub type ErasedBoxRef<U> = OwningRef<Box<dyn Erased>, U>;
/// Typedef of a owning reference that uses an erased `Rc` as the owner.
pub type ErasedRcRef<U> = OwningRef<Rc<dyn Erased>, U>;
/// Typedef of a owning reference that uses an erased `Arc` as the owner.
pub type ErasedArcRef<U> = OwningRef<Arc<dyn Erased>, U>;
/// Typedef of a mutable owning reference that uses an erased `Box` as the owner.
pub type ErasedBoxRefMut<U> = OwningRefMut<Box<dyn Erased>, U>;
#[cfg(test)]
mod tests {
mod owning_ref {
use super::super::OwningRef;
use super::super::{RcRef, BoxRef, Erased, ErasedBoxRef};
use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Debug, PartialEq)]
struct Example(u32, String, [u8; 3]);
fn example() -> Example {
Example(42, "hello world".to_string(), [1, 2, 3])
}
#[test]
fn new_deref() {
let or: OwningRef<Box<()>, ()> = OwningRef::new(Box::new(()));
assert_eq!(&*or, &());
}
#[test]
fn into() {
let or: OwningRef<Box<()>, ()> = Box::new(()).into();
assert_eq!(&*or, &());
}
#[test]
fn map_offset_ref() {
let or: BoxRef<Example> = Box::new(example()).into();
let or: BoxRef<_, u32> = or.map(|x| &x.0);
assert_eq!(&*or, &42);
let or: BoxRef<Example> = Box::new(example()).into();
let or: BoxRef<_, u8> = or.map(|x| &x.2[1]);
assert_eq!(&*or, &2);
}
#[test]
fn map_heap_ref() {
let or: BoxRef<Example> = Box::new(example()).into();
let or: BoxRef<_, str> = or.map(|x| &x.1[..5]);
assert_eq!(&*or, "hello");
}
#[test]
fn map_static_ref() {
let or: BoxRef<()> = Box::new(()).into();
let or: BoxRef<_, str> = or.map(|_| "hello");
assert_eq!(&*or, "hello");
}
#[test]
fn map_chained() {
let or: BoxRef<String> = Box::new(example().1).into();
let or: BoxRef<_, str> = or.map(|x| &x[1..5]);
let or: BoxRef<_, str> = or.map(|x| &x[..2]);
assert_eq!(&*or, "el");
}
#[test]
fn map_chained_inference() {
let or = BoxRef::new(Box::new(example().1))
.map(|x| &x[..5])
.map(|x| &x[1..3]);
assert_eq!(&*or, "el");
}
#[test]
fn owner() {
let or: BoxRef<String> = Box::new(example().1).into();
let or = or.map(|x| &x[..5]);
assert_eq!(&*or, "hello");
assert_eq!(&**or.owner(), "hello world");
}
#[test]
fn into_inner() {
let or: BoxRef<String> = Box::new(example().1).into();
let or = or.map(|x| &x[..5]);
assert_eq!(&*or, "hello");
let s = *or.into_inner();
assert_eq!(&s, "hello world");
}
#[test]
fn fmt_debug() {
let or: BoxRef<String> = Box::new(example().1).into();
let or = or.map(|x| &x[..5]);
let s = format!("{:?}", or);
assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }");
}
#[test]
fn erased_owner() {
let o1: BoxRef<Example, str> = BoxRef::new(Box::new(example()))
.map(|x| &x.1[..]);
let o2: BoxRef<String, str> = BoxRef::new(Box::new(example().1))
.map(|x| &x[..]);
let os: Vec<ErasedBoxRef<str>> = vec![o1.erase_owner(), o2.erase_owner()];
assert!(os.iter().all(|e| &e[..] == "hello world"));
}
#[test]
fn raii_locks() {
use super::super::{RefRef, RefMutRef};
use std::cell::RefCell;
use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef};
use std::sync::{Mutex, RwLock};
{
let a = RefCell::new(1);
let a = {
let a = RefRef::new(a.borrow());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
{
let a = RefCell::new(1);
let a = {
let a = RefMutRef::new(a.borrow_mut());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
{
let a = Mutex::new(1);
let a = {
let a = MutexGuardRef::new(a.lock().unwrap());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
{
let a = RwLock::new(1);
let a = {
let a = RwLockReadGuardRef::new(a.read().unwrap());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
{
let a = RwLock::new(1);
let a = {
let a = RwLockWriteGuardRef::new(a.write().unwrap());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
}
#[test]
fn eq() {
let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
assert_eq!(or1.eq(&or2), true);
}
#[test]
fn cmp() {
let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
let or2: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
assert_eq!(or1.cmp(&or2), Ordering::Less);
}
#[test]
fn partial_cmp() {
let or1: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
}
#[test]
fn hash() {
let mut h1 = DefaultHasher::new();
let mut h2 = DefaultHasher::new();
let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
or1.hash(&mut h1);
or2.hash(&mut h2);
assert_eq!(h1.finish(), h2.finish());
}
#[test]
fn borrow() {
let mut hash = HashMap::new();
let key = RcRef::<String>::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]);
hash.insert(key.clone().map(|s| &s[..3]), 42);
hash.insert(key.clone().map(|s| &s[4..]), 23);
assert_eq!(hash.get("foo"), Some(&42));
assert_eq!(hash.get("bar"), Some(&23));
}
#[test]
fn total_erase() {
let a: OwningRef<Vec<u8>, [u8]>
= OwningRef::new(vec![]).map(|x| &x[..]);
let b: OwningRef<Box<[u8]>, [u8]>
= OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
let c: OwningRef<Rc<Vec<u8>>, [u8]> = unsafe {a.map_owner(Rc::new)};
let d: OwningRef<Rc<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Rc::new)};
let e: OwningRef<Rc<dyn Erased>, [u8]> = c.erase_owner();
let f: OwningRef<Rc<dyn Erased>, [u8]> = d.erase_owner();
let _g = e.clone();
let _h = f.clone();
}
#[test]
fn total_erase_box() {
let a: OwningRef<Vec<u8>, [u8]>
= OwningRef::new(vec![]).map(|x| &x[..]);
let b: OwningRef<Box<[u8]>, [u8]>
= OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
let c: OwningRef<Box<Vec<u8>>, [u8]> = a.map_owner_box();
let d: OwningRef<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
let _e: OwningRef<Box<dyn Erased>, [u8]> = c.erase_owner();
let _f: OwningRef<Box<dyn Erased>, [u8]> = d.erase_owner();
}
#[test]
fn try_map1() {
use std::any::Any;
let x = Box::new(123_i32);
let y: Box<dyn Any> = x;
OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_ok();
}
#[test]
fn try_map2() {
use std::any::Any;
let x = Box::new(123_i32);
let y: Box<dyn Any> = x;
OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_err();
}
}
mod owning_handle {
use super::super::OwningHandle;
use super::super::RcRef;
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::RwLock;
#[test]
fn owning_handle() {
use std::cell::RefCell;
let cell = Rc::new(RefCell::new(2));
let cell_ref = RcRef::new(cell);
let mut handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
assert_eq!(*handle, 2);
*handle = 3;
assert_eq!(*handle, 3);
}
#[test]
fn try_owning_handle_ok() {
use std::cell::RefCell;
let cell = Rc::new(RefCell::new(2));
let cell_ref = RcRef::new(cell);
let mut handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
Ok(unsafe {
x.as_ref()
}.unwrap().borrow_mut())
}).unwrap();
assert_eq!(*handle, 2);
*handle = 3;
assert_eq!(*handle, 3);
}
#[test]
fn try_owning_handle_err() {
use std::cell::RefCell;
let cell = Rc::new(RefCell::new(2));
let cell_ref = RcRef::new(cell);
let handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
if false {
return Ok(unsafe {
x.as_ref()
}.unwrap().borrow_mut())
}
Err(())
});
assert!(handle.is_err());
}
#[test]
fn nested() {
use std::cell::RefCell;
use std::sync::{Arc, RwLock};
let result = {
let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
let curr = RcRef::new(complex);
let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
assert_eq!(*curr, "someString");
*curr = "someOtherString";
curr
};
assert_eq!(*result, "someOtherString");
}
#[test]
fn owning_handle_safe() {
use std::cell::RefCell;
let cell = Rc::new(RefCell::new(2));
let cell_ref = RcRef::new(cell);
let handle = OwningHandle::new(cell_ref);
assert_eq!(*handle, 2);
}
#[test]
fn owning_handle_mut_safe() {
use std::cell::RefCell;
let cell = Rc::new(RefCell::new(2));
let cell_ref = RcRef::new(cell);
let mut handle = OwningHandle::new_mut(cell_ref);
assert_eq!(*handle, 2);
*handle = 3;
assert_eq!(*handle, 3);
}
#[test]
fn owning_handle_safe_2() {
let result = {
let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
let curr = RcRef::new(complex);
let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
assert_eq!(*curr, "someString");
*curr = "someOtherString";
curr
};
assert_eq!(*result, "someOtherString");
}
}
mod owning_ref_mut {
use super::super::{OwningRefMut, BoxRefMut, Erased, ErasedBoxRefMut};
use super::super::BoxRef;
use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
#[derive(Debug, PartialEq)]
struct Example(u32, String, [u8; 3]);
fn example() -> Example {
Example(42, "hello world".to_string(), [1, 2, 3])
}
#[test]
fn new_deref() {
let or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
assert_eq!(&*or, &());
}
#[test]
fn new_deref_mut() {
let mut or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
assert_eq!(&mut *or, &mut ());
}
#[test]
fn mutate() {
let mut or: OwningRefMut<Box<usize>, usize> = OwningRefMut::new(Box::new(0));
assert_eq!(&*or, &0);
*or = 1;
assert_eq!(&*or, &1);
}
#[test]
fn into() {
let or: OwningRefMut<Box<()>, ()> = Box::new(()).into();
assert_eq!(&*or, &());
}
#[test]
fn map_offset_ref() {
let or: BoxRefMut<Example> = Box::new(example()).into();
let or: BoxRef<_, u32> = or.map(|x| &mut x.0);
assert_eq!(&*or, &42);
let or: BoxRefMut<Example> = Box::new(example()).into();
let or: BoxRef<_, u8> = or.map(|x| &mut x.2[1]);
assert_eq!(&*or, &2);
}
#[test]
fn map_heap_ref() {
let or: BoxRefMut<Example> = Box::new(example()).into();
let or: BoxRef<_, str> = or.map(|x| &mut x.1[..5]);
assert_eq!(&*or, "hello");
}
#[test]
fn map_static_ref() {
let or: BoxRefMut<()> = Box::new(()).into();
let or: BoxRef<_, str> = or.map(|_| "hello");
assert_eq!(&*or, "hello");
}
#[test]
fn map_mut_offset_ref() {
let or: BoxRefMut<Example> = Box::new(example()).into();
let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0);
assert_eq!(&*or, &42);
let or: BoxRefMut<Example> = Box::new(example()).into();
let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]);
assert_eq!(&*or, &2);
}
#[test]
fn map_mut_heap_ref() {
let or: BoxRefMut<Example> = Box::new(example()).into();
let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]);
assert_eq!(&*or, "hello");
}
#[test]
fn map_mut_static_ref() {
static mut MUT_S: [u8; 5] = *b"hello";
let mut_s: &'static mut [u8] = unsafe { &mut MUT_S };
let or: BoxRefMut<()> = Box::new(()).into();
let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s);
assert_eq!(&*or, b"hello");
}
#[test]
fn map_mut_chained() {
let or: BoxRefMut<String> = Box::new(example().1).into();
let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[1..5]);
let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[..2]);
assert_eq!(&*or, "el");
}
#[test]
fn map_chained_inference() {
let or = BoxRefMut::new(Box::new(example().1))
.map_mut(|x| &mut x[..5])
.map_mut(|x| &mut x[1..3]);
assert_eq!(&*or, "el");
}
#[test]
fn try_map_mut() {
let or: BoxRefMut<String> = Box::new(example().1).into();
let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|x| Ok(&mut x[1..5]));
assert_eq!(&*or.unwrap(), "ello");
let or: BoxRefMut<String> = Box::new(example().1).into();
let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|_| Err(()));
assert!(or.is_err());
}
#[test]
fn owner() {
let or: BoxRefMut<String> = Box::new(example().1).into();
let or = or.map_mut(|x| &mut x[..5]);
assert_eq!(&*or, "hello");
assert_eq!(&**or.owner(), "hello world");
}
#[test]
fn into_inner() {
let or: BoxRefMut<String> = Box::new(example().1).into();
let or = or.map_mut(|x| &mut x[..5]);
assert_eq!(&*or, "hello");
let s = *or.into_inner();
assert_eq!(&s, "hello world");
}
#[test]
fn fmt_debug() {
let or: BoxRefMut<String> = Box::new(example().1).into();
let or = or.map_mut(|x| &mut x[..5]);
let s = format!("{:?}", or);
assert_eq!(&s,
"OwningRefMut { owner: \"hello world\", reference: \"hello\" }");
}
#[test]
fn erased_owner() {
let o1: BoxRefMut<Example, str> = BoxRefMut::new(Box::new(example()))
.map_mut(|x| &mut x.1[..]);
let o2: BoxRefMut<String, str> = BoxRefMut::new(Box::new(example().1))
.map_mut(|x| &mut x[..]);
let os: Vec<ErasedBoxRefMut<str>> = vec![o1.erase_owner(), o2.erase_owner()];
assert!(os.iter().all(|e| &e[..] == "hello world"));
}
#[test]
fn raii_locks() {
use super::super::RefMutRefMut;
use std::cell::RefCell;
use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut};
use std::sync::{Mutex, RwLock};
{
let a = RefCell::new(1);
let a = {
let a = RefMutRefMut::new(a.borrow_mut());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
{
let a = Mutex::new(1);
let a = {
let a = MutexGuardRefMut::new(a.lock().unwrap());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
{
let a = RwLock::new(1);
let a = {
let a = RwLockWriteGuardRefMut::new(a.write().unwrap());
assert_eq!(*a, 1);
a
};
assert_eq!(*a, 1);
drop(a);
}
}
#[test]
fn eq() {
let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
assert_eq!(or1.eq(&or2), true);
}
#[test]
fn cmp() {
let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
assert_eq!(or1.cmp(&or2), Ordering::Less);
}
#[test]
fn partial_cmp() {
let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
}
#[test]
fn hash() {
let mut h1 = DefaultHasher::new();
let mut h2 = DefaultHasher::new();
let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
or1.hash(&mut h1);
or2.hash(&mut h2);
assert_eq!(h1.finish(), h2.finish());
}
#[test]
fn borrow() {
let mut hash = HashMap::new();
let key1 = BoxRefMut::<String>::new(Box::new("foo".to_string())).map(|s| &s[..]);
let key2 = BoxRefMut::<String>::new(Box::new("bar".to_string())).map(|s| &s[..]);
hash.insert(key1, 42);
hash.insert(key2, 23);
assert_eq!(hash.get("foo"), Some(&42));
assert_eq!(hash.get("bar"), Some(&23));
}
#[test]
fn total_erase() {
let a: OwningRefMut<Vec<u8>, [u8]>
= OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
let b: OwningRefMut<Box<[u8]>, [u8]>
= OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
let c: OwningRefMut<Box<Vec<u8>>, [u8]> = unsafe {a.map_owner(Box::new)};
let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Box::new)};
let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
}
#[test]
fn total_erase_box() {
let a: OwningRefMut<Vec<u8>, [u8]>
= OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
let b: OwningRefMut<Box<[u8]>, [u8]>
= OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
let c: OwningRefMut<Box<Vec<u8>>, [u8]> = a.map_owner_box();
let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
}
#[test]
fn try_map1() {
use std::any::Any;
let x = Box::new(123_i32);
let y: Box<dyn Any> = x;
OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).is_ok();
}
#[test]
fn try_map2() {
use std::any::Any;
let x = Box::new(123_i32);
let y: Box<dyn Any> = x;
OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).is_err();
}
#[test]
fn try_map3() {
use std::any::Any;
let x = Box::new(123_i32);
let y: Box<dyn Any> = x;
OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_ok();
}
#[test]
fn try_map4() {
use std::any::Any;
let x = Box::new(123_i32);
let y: Box<dyn Any> = x;
OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_err();
}
#[test]
fn into_owning_ref() {
use super::super::BoxRef;
let or: BoxRefMut<()> = Box::new(()).into();
let or: BoxRef<()> = or.into();
assert_eq!(&*or, &());
}
struct Foo {
u: u32,
}
struct Bar {
f: Foo,
}
#[test]
fn ref_mut() {
use std::cell::RefCell;
let a = RefCell::new(Bar { f: Foo { u: 42 } });
let mut b = OwningRefMut::new(a.borrow_mut());
assert_eq!(b.f.u, 42);
b.f.u = 43;
let mut c = b.map_mut(|x| &mut x.f);
assert_eq!(c.u, 43);
c.u = 44;
let mut d = c.map_mut(|x| &mut x.u);
assert_eq!(*d, 44);
*d = 45;
assert_eq!(*d, 45);
}
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/Cargo.toml
|
[package]
authors = ["The Rust Project Developers"]
name = "rustc_target"
version = "0.0.0"
[lib]
name = "rustc_target"
path = "lib.rs"
[dependencies]
bitflags = "1.0"
log = "0.4"
rustc_cratesio_shim = { path = "../librustc_cratesio_shim" }
serialize = { path = "../libserialize" }
[features]
jemalloc = []
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/lib.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Some stuff used by rustc that doesn't have many dependencies
//!
//! Originally extracted from rustc::back, which was nominally the
//! compiler 'backend', though LLVM is rustc's backend, so rustc_target
//! is really just odds-and-ends relating to code gen and linking.
//! This crate mostly exists to make rustc smaller, so we might put
//! more 'stuff' here in the future. It does not have a dependency on
//! LLVM.
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(box_syntax)]
#![feature(const_fn)]
#![cfg_attr(not(stage0), feature(nll))]
#![feature(slice_patterns)]
#[macro_use]
extern crate bitflags;
extern crate serialize;
#[macro_use] extern crate log;
extern crate serialize as rustc_serialize; // used by deriving
// See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
#[allow(unused_extern_crates)]
extern crate rustc_cratesio_shim;
pub mod abi;
pub mod spec;
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/build.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() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=CFG_DEFAULT_LINKER");
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_sun_solaris.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::solaris_base::opts();
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-pc-solaris".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "solaris".to_string(),
target_env: "".to_string(),
target_vendor: "sun".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs
|
// Copyright 2012-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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "ppc64le".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.max_atomic_width = Some(64);
// see #36994
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "powerpc64le-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-n32:64".to_string(),
arch: "powerpc64".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_unknown_dragonfly.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::dragonfly_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "i686-unknown-dragonfly".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "dragonfly".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/mipsel_unknown_linux_uclibc.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "mipsel-unknown-linux-uclibc".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64".to_string(),
arch: "mips".to_string(),
target_os: "linux".to_string(),
target_env: "uclibc".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
cpu: "mips32r2".to_string(),
features: "+mips32r2,+soft-float".to_string(),
max_atomic_width: Some(32),
// see #36994
exe_allocation_crate: None,
..super::linux_base::opts()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/thumbv7em_none_eabihf.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.
// Targets the Cortex-M4F and Cortex-M7F processors (ARMv7E-M)
//
// This target assumes that the device does have a FPU (Floating Point Unit) and lowers all (single
// precision) floating point operations to hardware instructions.
//
// Additionally, this target uses the "hard" floating convention (ABI) where floating point values
// are passed to/from subroutines via FPU registers (S0, S1, D0, D1, etc.).
//
// To opt into double precision hardware support, use the `-C target-feature=-fp-only-sp` flag.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "thumbv7em-none-eabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "none".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
// `+vfp4` is the lowest common denominator between the Cortex-M4 (vfp4-16) and the
// Cortex-M7 (vfp5)
// `+d16` both the Cortex-M4 and the Cortex-M7 only have 16 double-precision registers
// available
// `+fp-only-sp` The Cortex-M4 only supports single precision floating point operations
// whereas in the Cortex-M7 double precision is optional
//
// Reference:
// ARMv7-M Architecture Reference Manual - A2.5 The optional floating-point extension
features: "+vfp4,+d16,+fp-only-sp".to_string(),
max_atomic_width: Some(32),
.. super::thumb_base::opts()
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armv4t_unknown_linux_gnueabi.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let base = super::linux_base::opts();
Ok(Target {
llvm_target: "armv4t-unknown-linux-gnueabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+soft-float,+strict-align".to_string(),
// Atomic operations provided by compiler-builtins
max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/arm_unknown_linux_musleabi.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_musl_base::opts();
// Most of these settings are copied from the arm_unknown_linux_gnueabi
// target.
base.features = "+strict-align,+v6".to_string();
base.max_atomic_width = Some(64);
Ok(Target {
// It's important we use "gnueabi" and not "musleabi" here. LLVM uses it
// to determine the calling convention and float ABI, and it doesn't
// support the "musleabi" value.
llvm_target: "arm-unknown-linux-gnueabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_unknown_freebsd.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::freebsd_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "i686-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "freebsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/haiku_base.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
TargetOptions {
dynamic_linking: true,
executables: true,
has_rpath: false,
target_family: Some("unix".to_string()),
relro_level: RelroLevel::Full,
linker_is_gnu: true,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_unknown_cloudabi.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::cloudabi_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
base.linker = Some("aarch64-unknown-cloudabi-cc".to_string());
Ok(Target {
llvm_target: "aarch64-unknown-cloudabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "cloudabi".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_apple_darwin.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::apple_base::opts();
base.cpu = "core2".to_string();
base.max_atomic_width = Some(128); // core2 support cmpxchg16b
base.eliminate_frame_pointer = false;
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-apple-darwin".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:o-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "macos".to_string(),
target_env: "".to_string(),
target_vendor: "apple".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/powerpc64_unknown_linux_gnu.rs
|
// Copyright 2012-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.
use spec::{LinkerFlavor, Target, TargetResult, RelroLevel};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "ppc64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.max_atomic_width = Some(64);
// ld.so in at least RHEL6 on ppc64 has a bug related to BIND_NOW, so only enable partial RELRO
// for now. https://github.com/rust-lang/rust/pull/43170#issuecomment-315411474
base.relro_level = RelroLevel::Partial;
// see #36994
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "powerpc64-unknown-linux-gnu".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-i64:64-n32:64".to_string(),
arch: "powerpc64".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_hermit.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::hermit_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-hermit-gcc".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "x86_64-unknown-hermit".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "hermit".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_unknown_netbsd.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
Ok(Target {
llvm_target: "aarch64-unknown-netbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "netbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_unknown_openbsd.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::openbsd_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
Ok(Target {
llvm_target: "aarch64-unknown-openbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "openbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/arm_linux_androideabi.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::android_base::opts();
// https://developer.android.com/ndk/guides/abis.html#armeabi
base.features = "+strict-align,+v5te".to_string();
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "arm-linux-androideabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "android".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_unknown_hermit.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::hermit_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
base.linker = Some("aarch64-hermit-gcc".to_string());
Ok(Target {
llvm_target: "aarch64-unknown-hermit".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "hermit".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_netbsd.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-netbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "netbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/mips64_unknown_linux_gnuabi64.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "mips64-unknown-linux-gnuabi64".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-i8:8:32-i16:16:32-i64:64-n32:64-S128".to_string(),
arch: "mips64".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
// NOTE(mips64r2) matches C toolchain
cpu: "mips64r2".to_string(),
features: "+mips64r2".to_string(),
max_atomic_width: Some(64),
// see #36994
exe_allocation_crate: None,
..super::linux_base::opts()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armv7_linux_androideabi.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
// See https://developer.android.com/ndk/guides/abis.html#v7a
// for target ABI requirements.
pub fn target() -> TargetResult {
let mut base = super::android_base::opts();
base.features = "+v7,+thumb-mode,+thumb2,+vfp3,+d16,-neon".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args
.get_mut(&LinkerFlavor::Gcc).unwrap().push("-march=armv7-a".to_string());
Ok(Target {
llvm_target: "armv7-none-linux-android".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "android".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armv5te_unknown_linux_musleabi.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let base = super::linux_musl_base::opts();
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv5te-unknown-linux-gnueabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+soft-float,+strict-align".to_string(),
// Atomic operations provided by compiler-builtins
max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/openbsd_base.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc, vec![
// GNU-style linkers will use this to omit linking to libraries
// which don't actually fulfill any relocations, but only for
// libraries which follow this flag. Thus, use it before
// specifying libraries to link to.
"-Wl,--as-needed".to_string(),
// Always enable NX protection when it is available
"-Wl,-z,noexecstack".to_string(),
]);
TargetOptions {
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
abi_return_struct_as_int: true,
pre_link_args: args,
position_independent_executables: true,
eliminate_frame_pointer: false, // FIXME 43575
relro_level: RelroLevel::Full,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_openbsd.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::openbsd_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-openbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "openbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/linux_base.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.
use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc, vec![
// We want to be able to strip as much executable code as possible
// from the linker command line, and this flag indicates to the
// linker that it can avoid linking in dynamic libraries that don't
// actually satisfy any symbols up to that point (as with many other
// resolutions the linker does). This option only applies to all
// following libraries so we're sure to pass it as one of the first
// arguments.
"-Wl,--as-needed".to_string(),
// Always enable NX protection when it is available
"-Wl,-z,noexecstack".to_string(),
]);
TargetOptions {
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
pre_link_args: args,
position_independent_executables: true,
relro_level: RelroLevel::Full,
exe_allocation_crate: super::maybe_jemalloc(),
has_elf_tls: true,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/riscv32imac_unknown_none_elf.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
use spec::abi::{Abi};
pub fn target() -> TargetResult {
Ok(Target {
data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(),
llvm_target: "riscv32".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
target_os: "none".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
arch: "riscv32".to_string(),
linker_flavor: LinkerFlavor::Ld,
options: TargetOptions {
linker: Some("riscv32-unknown-elf-ld".to_string()),
cpu: "generic-rv32".to_string(),
max_atomic_width: Some(32),
atomic_cas: false, // incomplete +a extension
features: "+m,+a".to_string(), // disable +c extension
executables: true,
panic_strategy: PanicStrategy::Abort,
relocation_model: "static".to_string(),
emit_debug_gdb_scripts: false,
abi_blacklist: vec![
Abi::Cdecl,
Abi::Stdcall,
Abi::Fastcall,
Abi::Vectorcall,
Abi::Thiscall,
Abi::Aapcs,
Abi::Win64,
Abi::SysV64,
Abi::PtxKernel,
Abi::Msp430Interrupt,
Abi::X86Interrupt,
],
.. Default::default()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_redox.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::redox_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-redox".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "redox".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/windows_base.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.
use spec::{LinkArgs, LinkerFlavor, TargetOptions};
use std::default::Default;
pub fn opts() -> TargetOptions {
let mut pre_link_args = LinkArgs::new();
pre_link_args.insert(LinkerFlavor::Gcc, vec![
// And here, we see obscure linker flags #45. On windows, it has been
// found to be necessary to have this flag to compile liblibc.
//
// First a bit of background. On Windows, the file format is not ELF,
// but COFF (at least according to LLVM). COFF doesn't officially allow
// for section names over 8 characters, apparently. Our metadata
// section, ".note.rustc", you'll note is over 8 characters.
//
// On more recent versions of gcc on mingw, apparently the section name
// is *not* truncated, but rather stored elsewhere in a separate lookup
// table. On older versions of gcc, they apparently always truncated th
// section names (at least in some cases). Truncating the section name
// actually creates "invalid" objects [1] [2], but only for some
// introspection tools, not in terms of whether it can be loaded.
//
// Long story short, passing this flag forces the linker to *not*
// truncate section names (so we can find the metadata section after
// it's compiled). The real kicker is that rust compiled just fine on
// windows for quite a long time *without* this flag, so I have no idea
// why it suddenly started failing for liblibc. Regardless, we
// definitely don't want section name truncation, so we're keeping this
// flag for windows.
//
// [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
// [2] - https://code.google.com/p/go/issues/detail?id=2139
"-Wl,--enable-long-section-names".to_string(),
// Tell GCC to avoid linker plugins, because we are not bundling
// them with Windows installer, and Rust does its own LTO anyways.
"-fno-use-linker-plugin".to_string(),
// Always enable DEP (NX bit) when it is available
"-Wl,--nxcompat".to_string(),
// Do not use the standard system startup files or libraries when linking
"-nostdlib".to_string(),
]);
let mut late_link_args = LinkArgs::new();
late_link_args.insert(LinkerFlavor::Gcc, vec![
"-lmingwex".to_string(),
"-lmingw32".to_string(),
"-lgcc".to_string(), // alas, mingw* libraries above depend on libgcc
"-lmsvcrt".to_string(),
// mingw's msvcrt is a weird hybrid import library and static library.
// And it seems that the linker fails to use import symbols from msvcrt
// that are required from functions in msvcrt in certain cases. For example
// `_fmode` that is used by an implementation of `__p__fmode` in x86_64.
// Listing the library twice seems to fix that, and seems to also be done
// by mingw's gcc (Though not sure if it's done on purpose, or by mistake).
//
// See https://github.com/rust-lang/rust/pull/47483
"-lmsvcrt".to_string(),
"-luser32".to_string(),
"-lkernel32".to_string(),
]);
TargetOptions {
// FIXME(#13846) this should be enabled for windows
function_sections: false,
linker: Some("gcc".to_string()),
dynamic_linking: true,
executables: true,
dll_prefix: "".to_string(),
dll_suffix: ".dll".to_string(),
exe_suffix: ".exe".to_string(),
staticlib_prefix: "".to_string(),
staticlib_suffix: ".lib".to_string(),
no_default_libraries: true,
target_family: Some("windows".to_string()),
is_like_windows: true,
allows_weak_linkage: false,
pre_link_args,
pre_link_objects_exe: vec![
"crt2.o".to_string(), // mingw C runtime initialization for executables
"rsbegin.o".to_string(), // Rust compiler runtime initialization, see rsbegin.rs
],
pre_link_objects_dll: vec![
"dllcrt2.o".to_string(), // mingw C runtime initialization for dlls
"rsbegin.o".to_string(),
],
late_link_args,
post_link_objects: vec![
"rsend.o".to_string()
],
custom_unwind_resume: true,
abi_return_struct_as_int: true,
emit_debug_gdb_scripts: false,
requires_uwtable: true,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_pc_windows_gnu.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::windows_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.eliminate_frame_pointer = false; // Required for backtraces
// Mark all dynamic libraries and executables as compatible with the larger 4GiB address
// space available to x86 Windows binaries on x86_64.
base.pre_link_args
.get_mut(&LinkerFlavor::Gcc).unwrap().push("-Wl,--large-address-aware".to_string());
Ok(Target {
llvm_target: "i686-pc-windows-gnu".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32".to_string(),
arch: "x86".to_string(),
target_os: "windows".to_string(),
target_env: "gnu".to_string(),
target_vendor: "pc".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/arm_unknown_linux_gnueabi.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "arm-unknown-linux-gnueabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+strict-align,+v6".to_string(),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/mips_unknown_linux_gnu.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "mips-unknown-linux-gnu".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64".to_string(),
arch: "mips".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
cpu: "mips32r2".to_string(),
features: "+mips32r2,+fpxx,+nooddspreg".to_string(),
max_atomic_width: Some(32),
// see #36994
exe_allocation_crate: None,
..super::linux_base::opts()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/arm_unknown_linux_musleabihf.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_musl_base::opts();
// Most of these settings are copied from the arm_unknown_linux_gnueabihf
// target.
base.features = "+strict-align,+v6,+vfp2".to_string();
base.max_atomic_width = Some(64);
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and it
// doesn't support the "musleabihf" value.
llvm_target: "arm-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i586_unknown_linux_gnu.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.
use spec::TargetResult;
pub fn target() -> TargetResult {
let mut base = super::i686_unknown_linux_gnu::target()?;
base.options.cpu = "pentium".to_string();
base.llvm_target = "i586-unknown-linux-gnu".to_string();
Ok(base)
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_linux_android.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::android_base::opts();
base.cpu = "x86-64".to_string();
// https://developer.android.com/ndk/guides/abis.html#86-64
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-linux-android".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "android".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/powerpc64le_unknown_linux_musl.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_musl_base::opts();
base.cpu = "ppc64le".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.max_atomic_width = Some(64);
// see #36994
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "powerpc64le-unknown-linux-musl".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-n32:64".to_string(),
arch: "powerpc64".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/arm_base.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.
use spec::abi::Abi;
// All the calling conventions trigger an assertion(Unsupported calling convention) in llvm on arm
pub fn abi_blacklist() -> Vec<Abi> {
vec![Abi::Stdcall, Abi::Fastcall, Abi::Vectorcall, Abi::Thiscall, Abi::Win64, Abi::SysV64]
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/thumb_base.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.
// These 4 `thumbv*` targets cover the ARM Cortex-M family of processors which are widely used in
// microcontrollers. Namely, all these processors:
//
// - Cortex-M0
// - Cortex-M0+
// - Cortex-M1
// - Cortex-M3
// - Cortex-M4(F)
// - Cortex-M7(F)
//
// We have opted for 4 targets instead of one target per processor (e.g. `cortex-m0`, `cortex-m3`,
// etc) because the differences between some processors like the cortex-m0 and cortex-m1 are almost
// non-existent from the POV of codegen so it doesn't make sense to have separate targets for them.
// And if differences exist between two processors under the same target, rustc flags can be used to
// optimize for one processor or the other.
//
// Also, we have not chosen a single target (`arm-none-eabi`) like GCC does because this makes
// difficult to integrate Rust code and C code. Targeting the Cortex-M4 requires different gcc flags
// than the ones you would use for the Cortex-M0 and with a single target it'd be impossible to
// differentiate one processor from the other.
//
// About arm vs thumb in the name. The Cortex-M devices only support the Thumb instruction set,
// which is more compact (higher code density), and not the ARM instruction set. That's why LLVM
// triples use thumb instead of arm. We follow suit because having thumb in the name let us
// differentiate these targets from our other `arm(v7)-*-*-gnueabi(hf)` targets in the context of
// build scripts / gcc flags.
use std::default::Default;
use spec::{PanicStrategy, TargetOptions};
pub fn opts() -> TargetOptions {
// See rust-lang/rfcs#1645 for a discussion about these defaults
TargetOptions {
executables: true,
// In 99%+ of cases, we want to use the `arm-none-eabi-gcc` compiler (there aren't many
// options around)
linker: Some("arm-none-eabi-gcc".to_string()),
// Because these devices have very little resources having an unwinder is too onerous so we
// default to "abort" because the "unwind" strategy is very rare.
panic_strategy: PanicStrategy::Abort,
// Similarly, one almost always never wants to use relocatable code because of the extra
// costs it involves.
relocation_model: "static".to_string(),
abi_blacklist: super::arm_base::abi_blacklist(),
// When this section is added a volatile load to its start address is also generated. This
// volatile load is a footgun as it can end up loading an invalid memory address, depending
// on how the user set up their linker scripts. This section adds pretty printer for stuff
// like std::Vec, which is not that used in no-std context, so it's best to left it out
// until we figure a way to add the pretty printers without requiring a volatile load cf.
// rust-lang/rust#44993.
emit_debug_gdb_scripts: false,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/solaris_base.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::TargetOptions;
use std::default::Default;
pub fn opts() -> TargetOptions {
TargetOptions {
dynamic_linking: true,
executables: true,
has_rpath: true,
target_family: Some("unix".to_string()),
is_like_solaris: true,
exe_allocation_crate: super::maybe_jemalloc(),
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_unknown_haiku.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::haiku_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m32".to_string()]);
base.stack_probes = true;
Ok(Target {
llvm_target: "i686-unknown-haiku".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "haiku".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/freebsd_base.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.
use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc, vec![
// GNU-style linkers will use this to omit linking to libraries
// which don't actually fulfill any relocations, but only for
// libraries which follow this flag. Thus, use it before
// specifying libraries to link to.
"-Wl,--as-needed".to_string(),
// Always enable NX protection when it is available
"-Wl,-z,noexecstack".to_string(),
]);
TargetOptions {
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
pre_link_args: args,
position_independent_executables: true,
eliminate_frame_pointer: false, // FIXME 43575
relro_level: RelroLevel::Full,
exe_allocation_crate: super::maybe_jemalloc(),
abi_return_struct_as_int: true,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_unknown_openbsd.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::openbsd_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-fuse-ld=lld".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "i686-unknown-openbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "openbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/sparc_unknown_linux_gnu.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "v9".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-mv8plus".to_string());
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "sparc-unknown-linux-gnu".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-p:32:32-i64:64-f128:64-n32-S64".to_string(),
arch: "sparc".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_apple_darwin.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::apple_base::opts();
base.cpu = "yonah".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m32".to_string()]);
base.stack_probes = true;
base.eliminate_frame_pointer = false;
Ok(Target {
llvm_target: "i686-apple-darwin".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:o-p:32:32-f64:32:64-f80:128-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "macos".to_string(),
target_env: "".to_string(),
target_vendor: "apple".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armv7s_apple_ios.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
use super::apple_ios_base::{opts, Arch};
pub fn target() -> TargetResult {
let base = opts(Arch::Armv7s)?;
Ok(Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
target_vendor: "apple".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+v7,+vfp4,+neon".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/dragonfly_base.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.
use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc, vec![
// GNU-style linkers will use this to omit linking to libraries
// which don't actually fulfill any relocations, but only for
// libraries which follow this flag. Thus, use it before
// specifying libraries to link to.
"-Wl,--as-needed".to_string(),
// Always enable NX protection when it is available
"-Wl,-z,noexecstack".to_string(),
]);
TargetOptions {
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
pre_link_args: args,
position_independent_executables: true,
relro_level: RelroLevel::Full,
exe_allocation_crate: super::maybe_jemalloc(),
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/mips64el_unknown_linux_gnuabi64.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "mips64el-unknown-linux-gnuabi64".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-n32:64-S128".to_string(),
arch: "mips64".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
// NOTE(mips64r2) matches C toolchain
cpu: "mips64r2".to_string(),
features: "+mips64r2".to_string(),
max_atomic_width: Some(64),
// see #36994
exe_allocation_crate: None,
..super::linux_base::opts()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_cloudabi.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::cloudabi_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.linker = Some("x86_64-unknown-cloudabi-cc".to_string());
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-cloudabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "cloudabi".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_fuchsia.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::fuchsia_base::opts();
base.max_atomic_width = Some(128);
Ok(Target {
llvm_target: "aarch64-fuchsia".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "fuchsia".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_unknown_linux_gnu.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "i686-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_unknown_freebsd.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::freebsd_base::opts();
base.max_atomic_width = Some(128);
// see #36994
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "aarch64-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "freebsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armebv7r_none_eabihf.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.
// Targets the Cortex-R4F/R5F processor (ARMv7-R)
use std::default::Default;
use spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "armebv7r-none-eabihf".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "none".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
executables: true,
relocation_model: "static".to_string(),
panic_strategy: PanicStrategy::Abort,
features: "+v7,+vfp3,+d16,+fp-only-sp".to_string(),
max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(),
emit_debug_gdb_scripts: false,
.. Default::default()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/wasm32_unknown_unknown.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.
// The wasm32-unknown-unknown target is currently an experimental version of a
// wasm-based target which does *not* use the Emscripten toolchain. Instead
// this toolchain is based purely on LLVM's own toolchain, using LLVM's native
// WebAssembly backend as well as LLD for a native linker.
//
// There's some trickery below on crate types supported and various defaults
// (aka panic=abort by default), but otherwise this is in general a relatively
// standard target.
use super::{LldFlavor, LinkerFlavor, Target, TargetOptions, PanicStrategy};
pub fn target() -> Result<Target, String> {
let opts = TargetOptions {
// we allow dynamic linking, but only cdylibs. Basically we allow a
// final library artifact that exports some symbols (a wasm module) but
// we don't allow intermediate `dylib` crate types
dynamic_linking: true,
only_cdylib: true,
// This means we'll just embed a `start` function in the wasm module
executables: true,
// relatively self-explanatory!
exe_suffix: ".wasm".to_string(),
dll_prefix: "".to_string(),
dll_suffix: ".wasm".to_string(),
linker_is_gnu: false,
// A bit of a lie, but "eh"
max_atomic_width: Some(32),
// Unwinding doesn't work right now, so the whole target unconditionally
// defaults to panic=abort. Note that this is guaranteed to change in
// the future once unwinding is implemented. Don't rely on this.
panic_strategy: PanicStrategy::Abort,
// Wasm doesn't have atomics yet, so tell LLVM that we're in a single
// threaded model which will legalize atomics to normal operations.
singlethread: true,
// no dynamic linking, no need for default visibility!
default_hidden_visibility: true,
// we use the LLD shipped with the Rust toolchain by default
linker: Some("rust-lld".to_owned()),
lld_flavor: LldFlavor::Wasm,
.. Default::default()
};
Ok(Target {
llvm_target: "wasm32-unknown-unknown".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
// This is basically guaranteed to change in the future, don't rely on
// this. Use `not(target_os = "emscripten")` for now.
target_os: "unknown".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-n32:64-S128".to_string(),
arch: "wasm32".to_string(),
linker_flavor: LinkerFlavor::Lld(LldFlavor::Wasm),
options: opts,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/thumbv7m_none_eabi.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.
// Targets the Cortex-M3 processor (ARMv7-M)
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "thumbv7m-none-eabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "none".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
max_atomic_width: Some(32),
.. super::thumb_base::opts()
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/android_base.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.
use spec::{LinkerFlavor, TargetOptions};
pub fn opts() -> TargetOptions {
let mut base = super::linux_base::opts();
// Many of the symbols defined in compiler-rt are also defined in libgcc.
// Android's linker doesn't like that by default.
base.pre_link_args
.get_mut(&LinkerFlavor::Gcc).unwrap().push("-Wl,--allow-multiple-definition".to_string());
base.is_like_android = true;
base.position_independent_executables = true;
base.has_elf_tls = false;
base.requires_uwtable = true;
base
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_bitrig.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::bitrig_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-bitrig".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "bitrig".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_freebsd.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::freebsd_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "freebsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/msp430_none_elf.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.
use spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "msp430-none-elf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "16".to_string(),
target_c_int_width: "16".to_string(),
data_layout: "e-m:e-p:16:16-i32:16-i64:16-f32:16-f64:16-a:8-n8:16-S16".to_string(),
arch: "msp430".to_string(),
target_os: "none".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
executables: true,
// The LLVM backend currently can't generate object files. To
// workaround this LLVM generates assembly files which then we feed
// to gcc to get object files. For this reason we have a hard
// dependency on this specific gcc.
asm_args: vec!["-mcpu=msp430".to_string()],
linker: Some("msp430-elf-gcc".to_string()),
no_integrated_as: true,
// There are no atomic CAS instructions available in the MSP430
// instruction set
max_atomic_width: Some(16),
atomic_cas: false,
// Because these devices have very little resources having an
// unwinder is too onerous so we default to "abort" because the
// "unwind" strategy is very rare.
panic_strategy: PanicStrategy::Abort,
// Similarly, one almost always never wants to use relocatable
// code because of the extra costs it involves.
relocation_model: "static".to_string(),
// Right now we invoke an external assembler and this isn't
// compatible with multiple codegen units, and plus we probably
// don't want to invoke that many gcc instances.
default_codegen_units: Some(1),
// Since MSP430 doesn't meaningfully support faulting on illegal
// instructions, LLVM generates a call to abort() function instead
// of a trap instruction. Such calls are 4 bytes long, and that is
// too much overhead for such small target.
trap_unreachable: false,
// See the thumb_base.rs file for an explanation of this value
emit_debug_gdb_scripts: false,
.. Default::default( )
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i586_pc_windows_msvc.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::TargetResult;
pub fn target() -> TargetResult {
let mut base = super::i686_pc_windows_msvc::target()?;
base.options.cpu = "pentium".to_string();
base.llvm_target = "i586-pc-windows-msvc".to_string();
Ok(base)
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_fuchsia.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::fuchsia_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-fuchsia".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "fuchsia".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_unknown_netbsd.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "i686-unknown-netbsdelf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
arch: "x86".to_string(),
target_os: "netbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_linux_gnu.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/wasm32_experimental_emscripten.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::{LinkArgs, LinkerFlavor, Target, TargetOptions};
pub fn target() -> Result<Target, String> {
let mut post_link_args = LinkArgs::new();
post_link_args.insert(LinkerFlavor::Em,
vec!["-s".to_string(),
"WASM=1".to_string(),
"-s".to_string(),
"ASSERTIONS=1".to_string(),
"-s".to_string(),
"ERROR_ON_UNDEFINED_SYMBOLS=1".to_string(),
"-g3".to_string()]);
let opts = TargetOptions {
dynamic_linking: false,
executables: true,
// Today emcc emits two files - a .js file to bootstrap and
// possibly interpret the wasm, and a .wasm file
exe_suffix: ".js".to_string(),
linker_is_gnu: true,
link_env: vec![("EMCC_WASM_BACKEND".to_string(), "1".to_string())],
allow_asm: false,
obj_is_bitcode: true,
is_like_emscripten: true,
max_atomic_width: Some(32),
post_link_args,
target_family: Some("unix".to_string()),
.. Default::default()
};
Ok(Target {
llvm_target: "wasm32-unknown-unknown".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
target_os: "emscripten".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-n32:64-S128".to_string(),
arch: "wasm32".to_string(),
linker_flavor: LinkerFlavor::Em,
options: opts,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i686_pc_windows_msvc.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::windows_msvc_base::opts();
base.cpu = "pentium4".to_string();
base.max_atomic_width = Some(64);
// Mark all dynamic libraries and executables as compatible with the larger 4GiB address
// space available to x86 Windows binaries on x86_64.
base.pre_link_args
.get_mut(&LinkerFlavor::Msvc).unwrap().push("/LARGEADDRESSAWARE".to_string());
// Ensure the linker will only produce an image if it can also produce a table of
// the image's safe exception handlers.
// https://msdn.microsoft.com/en-us/library/9a89h429.aspx
base.pre_link_args.get_mut(&LinkerFlavor::Msvc).unwrap().push("/SAFESEH".to_string());
Ok(Target {
llvm_target: "i686-pc-windows-msvc".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32".to_string(),
arch: "x86".to_string(),
target_os: "windows".to_string(),
target_env: "msvc".to_string(),
target_vendor: "pc".to_string(),
linker_flavor: LinkerFlavor::Msvc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/i586_unknown_linux_musl.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.
use spec::TargetResult;
pub fn target() -> TargetResult {
let mut base = super::i686_unknown_linux_musl::target()?;
base.options.cpu = "pentium".to_string();
base.llvm_target = "i586-unknown-linux-musl".to_string();
Ok(base)
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armv6_unknown_netbsd_eabihf.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "armv6-unknown-netbsdelf-eabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "netbsd".to_string(),
target_env: "eabihf".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+v6,+vfp2".to_string(),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/netbsd_base.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc, vec![
// GNU-style linkers will use this to omit linking to libraries
// which don't actually fulfill any relocations, but only for
// libraries which follow this flag. Thus, use it before
// specifying libraries to link to.
"-Wl,--as-needed".to_string(),
// Always enable NX protection when it is available
"-Wl,-z,noexecstack".to_string(),
]);
TargetOptions {
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
pre_link_args: args,
position_independent_executables: true,
relro_level: RelroLevel::Full,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_linux_musl.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_musl_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-unknown-linux-musl".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/mod.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
//!
//! Rust targets a wide variety of usecases, and in the interest of flexibility,
//! allows new target triples to be defined in configuration files. Most users
//! will not need to care about these, but this is invaluable when porting Rust
//! to a new platform, and allows for an unprecedented level of control over how
//! the compiler works.
//!
//! # Using custom targets
//!
//! A target triple, as passed via `rustc --target=TRIPLE`, will first be
//! compared against the list of built-in targets. This is to ease distributing
//! rustc (no need for configuration files) and also to hold these built-in
//! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
//! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
//! will be loaded as the target configuration. If the file does not exist,
//! rustc will search each directory in the environment variable
//! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
//! be loaded. If no file is found in any of those directories, a fatal error
//! will be given.
//!
//! Projects defining their own targets should use
//! `--target=path/to/my-awesome-platform.json` instead of adding to
//! `RUST_TARGET_PATH`.
//!
//! # Defining a new target
//!
//! Targets are defined using [JSON](http://json.org/). The `Target` struct in
//! this module defines the format the JSON file should take, though each
//! underscore in the field names should be replaced with a hyphen (`-`) in the
//! JSON file. Some fields are required in every target specification, such as
//! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
//! `arch`, and `os`. In general, options passed to rustc with `-C` override
//! the target's settings, though `target-feature` and `link-args` will *add*
//! to the list specified by the target, rather than replace.
use serialize::json::{Json, ToJson};
use std::collections::BTreeMap;
use std::default::Default;
use std::{fmt, io};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use spec::abi::{Abi, lookup as lookup_abi};
pub mod abi;
mod android_base;
mod apple_base;
mod apple_ios_base;
mod arm_base;
mod bitrig_base;
mod cloudabi_base;
mod dragonfly_base;
mod freebsd_base;
mod haiku_base;
mod hermit_base;
mod linux_base;
mod linux_musl_base;
mod openbsd_base;
mod netbsd_base;
mod solaris_base;
mod windows_base;
mod windows_msvc_base;
mod thumb_base;
mod l4re_base;
mod fuchsia_base;
mod redox_base;
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
RustcEncodable, RustcDecodable)]
pub enum LinkerFlavor {
Em,
Gcc,
Ld,
Msvc,
Lld(LldFlavor),
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
RustcEncodable, RustcDecodable)]
pub enum LldFlavor {
Wasm,
Ld64,
Ld,
Link,
}
impl LldFlavor {
fn from_str(s: &str) -> Option<Self> {
Some(match s {
"darwin" => LldFlavor::Ld64,
"gnu" => LldFlavor::Ld,
"link" => LldFlavor::Link,
"wasm" => LldFlavor::Wasm,
_ => return None,
})
}
}
impl ToJson for LldFlavor {
fn to_json(&self) -> Json {
match *self {
LldFlavor::Ld64 => "darwin",
LldFlavor::Ld => "gnu",
LldFlavor::Link => "link",
LldFlavor::Wasm => "wasm",
}.to_json()
}
}
impl ToJson for LinkerFlavor {
fn to_json(&self) -> Json {
self.desc().to_json()
}
}
macro_rules! flavor_mappings {
($((($($flavor:tt)*), $string:expr),)*) => (
impl LinkerFlavor {
pub const fn one_of() -> &'static str {
concat!("one of: ", $($string, " ",)+)
}
pub fn from_str(s: &str) -> Option<Self> {
Some(match s {
$($string => $($flavor)*,)+
_ => return None,
})
}
pub fn desc(&self) -> &str {
match *self {
$($($flavor)* => $string,)+
}
}
}
)
}
flavor_mappings! {
((LinkerFlavor::Em), "em"),
((LinkerFlavor::Gcc), "gcc"),
((LinkerFlavor::Ld), "ld"),
((LinkerFlavor::Msvc), "msvc"),
((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
}
#[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
pub enum PanicStrategy {
Unwind,
Abort,
}
impl PanicStrategy {
pub fn desc(&self) -> &str {
match *self {
PanicStrategy::Unwind => "unwind",
PanicStrategy::Abort => "abort",
}
}
}
impl ToJson for PanicStrategy {
fn to_json(&self) -> Json {
match *self {
PanicStrategy::Abort => "abort".to_json(),
PanicStrategy::Unwind => "unwind".to_json(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
pub enum RelroLevel {
Full,
Partial,
Off,
None,
}
impl RelroLevel {
pub fn desc(&self) -> &str {
match *self {
RelroLevel::Full => "full",
RelroLevel::Partial => "partial",
RelroLevel::Off => "off",
RelroLevel::None => "none",
}
}
}
impl FromStr for RelroLevel {
type Err = ();
fn from_str(s: &str) -> Result<RelroLevel, ()> {
match s {
"full" => Ok(RelroLevel::Full),
"partial" => Ok(RelroLevel::Partial),
"off" => Ok(RelroLevel::Off),
"none" => Ok(RelroLevel::None),
_ => Err(()),
}
}
}
impl ToJson for RelroLevel {
fn to_json(&self) -> Json {
match *self {
RelroLevel::Full => "full".to_json(),
RelroLevel::Partial => "partial".to_json(),
RelroLevel::Off => "off".to_json(),
RelroLevel::None => "None".to_json(),
}
}
}
pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
pub type TargetResult = Result<Target, String>;
macro_rules! supported_targets {
( $(($triple:expr, $module:ident),)+ ) => (
$(mod $module;)*
/// List of supported targets
const TARGETS: &'static [&'static str] = &[$($triple),*];
fn load_specific(target: &str) -> TargetResult {
match target {
$(
$triple => {
let mut t = $module::target()?;
t.options.is_builtin = true;
// round-trip through the JSON parser to ensure at
// run-time that the parser works correctly
t = Target::from_json(t.to_json())?;
debug!("Got builtin target: {:?}", t);
Ok(t)
},
)+
_ => Err(format!("Unable to find target: {}", target))
}
}
pub fn get_targets() -> Box<dyn Iterator<Item=String>> {
Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
load_specific(t)
.and(Ok(t.to_string()))
.ok()
}))
}
#[cfg(test)]
mod test_json_encode_decode {
use serialize::json::ToJson;
use super::Target;
$(use super::$module;)*
$(
#[test]
fn $module() {
// Grab the TargetResult struct. If we successfully retrieved
// a Target, then the test JSON encoding/decoding can run for this
// Target on this testing platform (i.e., checking the iOS targets
// only on a Mac test platform).
let _ = $module::target().map(|original| {
let as_json = original.to_json();
let parsed = Target::from_json(as_json).unwrap();
assert_eq!(original, parsed);
});
}
)*
}
)
}
supported_targets! {
("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
("i686-unknown-linux-musl", i686_unknown_linux_musl),
("i586-unknown-linux-musl", i586_unknown_linux_musl),
("mips-unknown-linux-musl", mips_unknown_linux_musl),
("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
("i686-linux-android", i686_linux_android),
("x86_64-linux-android", x86_64_linux_android),
("arm-linux-androideabi", arm_linux_androideabi),
("armv7-linux-androideabi", armv7_linux_androideabi),
("aarch64-linux-android", aarch64_linux_android),
("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
("i686-unknown-freebsd", i686_unknown_freebsd),
("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
("i686-unknown-dragonfly", i686_unknown_dragonfly),
("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
("i686-unknown-openbsd", i686_unknown_openbsd),
("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
("i686-unknown-netbsd", i686_unknown_netbsd),
("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
("i686-unknown-haiku", i686_unknown_haiku),
("x86_64-unknown-haiku", x86_64_unknown_haiku),
("x86_64-apple-darwin", x86_64_apple_darwin),
("i686-apple-darwin", i686_apple_darwin),
("aarch64-fuchsia", aarch64_fuchsia),
("x86_64-fuchsia", x86_64_fuchsia),
("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
("x86_64-unknown-redox", x86_64_unknown_redox),
("i386-apple-ios", i386_apple_ios),
("x86_64-apple-ios", x86_64_apple_ios),
("aarch64-apple-ios", aarch64_apple_ios),
("armv7-apple-ios", armv7_apple_ios),
("armv7s-apple-ios", armv7s_apple_ios),
("armebv7r-none-eabihf", armebv7r_none_eabihf),
("x86_64-sun-solaris", x86_64_sun_solaris),
("sparcv9-sun-solaris", sparcv9_sun_solaris),
("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
("i686-pc-windows-gnu", i686_pc_windows_gnu),
("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
("i686-pc-windows-msvc", i686_pc_windows_msvc),
("i586-pc-windows-msvc", i586_pc_windows_msvc),
("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
("wasm32-unknown-unknown", wasm32_unknown_unknown),
("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
("thumbv6m-none-eabi", thumbv6m_none_eabi),
("thumbv7m-none-eabi", thumbv7m_none_eabi),
("thumbv7em-none-eabi", thumbv7em_none_eabi),
("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
("msp430-none-elf", msp430_none_elf),
("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
("i686-unknown-cloudabi", i686_unknown_cloudabi),
("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
("aarch64-unknown-hermit", aarch64_unknown_hermit),
("x86_64-unknown-hermit", x86_64_unknown_hermit),
("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
("aarch64-unknown-none", aarch64_unknown_none),
}
/// Everything `rustc` knows about how to compile for a specific target.
///
/// Every field here must be specified, and has no default value.
#[derive(PartialEq, Clone, Debug)]
pub struct Target {
/// Target triple to pass to LLVM.
pub llvm_target: String,
/// String to use as the `target_endian` `cfg` variable.
pub target_endian: String,
/// String to use as the `target_pointer_width` `cfg` variable.
pub target_pointer_width: String,
/// Width of c_int type
pub target_c_int_width: String,
/// OS name to use for conditional compilation.
pub target_os: String,
/// Environment name to use for conditional compilation.
pub target_env: String,
/// Vendor name to use for conditional compilation.
pub target_vendor: String,
/// Architecture to use for ABI considerations. Valid options: "x86",
/// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
pub arch: String,
/// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
pub data_layout: String,
/// Linker flavor
pub linker_flavor: LinkerFlavor,
/// Optional settings with defaults.
pub options: TargetOptions,
}
pub trait HasTargetSpec: Copy {
fn target_spec(&self) -> &Target;
}
impl<'a> HasTargetSpec for &'a Target {
fn target_spec(&self) -> &Target {
self
}
}
/// Optional aspects of a target specification.
///
/// This has an implementation of `Default`, see each field for what the default is. In general,
/// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
#[derive(PartialEq, Clone, Debug)]
pub struct TargetOptions {
/// Whether the target is built-in or loaded from a custom target specification.
pub is_builtin: bool,
/// Linker to invoke
pub linker: Option<String>,
/// LLD flavor
pub lld_flavor: LldFlavor,
/// Linker arguments that are passed *before* any user-defined libraries.
pub pre_link_args: LinkArgs, // ... unconditionally
pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
/// Objects to link before all others, always found within the
/// sysroot folder.
pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
/// Linker arguments that are unconditionally passed after any
/// user-defined but before post_link_objects. Standard platform
/// libraries that should be always be linked to, usually go here.
pub late_link_args: LinkArgs,
/// Objects to link after all others, always found within the
/// sysroot folder.
pub post_link_objects: Vec<String>, // ... unconditionally
pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
/// Linker arguments that are unconditionally passed *after* any
/// user-defined libraries.
pub post_link_args: LinkArgs,
/// Environment variables to be set before invoking the linker.
pub link_env: Vec<(String, String)>,
/// Extra arguments to pass to the external assembler (when used)
pub asm_args: Vec<String>,
/// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
/// to "generic".
pub cpu: String,
/// Default target features to pass to LLVM. These features will *always* be
/// passed, and cannot be disabled even via `-C`. Corresponds to `llc
/// -mattr=$features`.
pub features: String,
/// Whether dynamic linking is available on this target. Defaults to false.
pub dynamic_linking: bool,
/// If dynamic linking is available, whether only cdylibs are supported.
pub only_cdylib: bool,
/// Whether executables are available on this target. iOS, for example, only allows static
/// libraries. Defaults to false.
pub executables: bool,
/// Relocation model to use in object file. Corresponds to `llc
/// -relocation-model=$relocation_model`. Defaults to "pic".
pub relocation_model: String,
/// Code model to use. Corresponds to `llc -code-model=$code_model`.
pub code_model: Option<String>,
/// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
/// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
pub tls_model: String,
/// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
pub disable_redzone: bool,
/// Eliminate frame pointers from stack frames if possible. Defaults to true.
pub eliminate_frame_pointer: bool,
/// Emit each function in its own section. Defaults to true.
pub function_sections: bool,
/// String to prepend to the name of every dynamic library. Defaults to "lib".
pub dll_prefix: String,
/// String to append to the name of every dynamic library. Defaults to ".so".
pub dll_suffix: String,
/// String to append to the name of every executable.
pub exe_suffix: String,
/// String to prepend to the name of every static library. Defaults to "lib".
pub staticlib_prefix: String,
/// String to append to the name of every static library. Defaults to ".a".
pub staticlib_suffix: String,
/// OS family to use for conditional compilation. Valid options: "unix", "windows".
pub target_family: Option<String>,
/// Whether the target toolchain's ABI supports returning small structs as an integer.
pub abi_return_struct_as_int: bool,
/// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
/// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
pub is_like_osx: bool,
/// Whether the target toolchain is like Solaris's.
/// Only useful for compiling against Illumos/Solaris,
/// as they have a different set of linker flags. Defaults to false.
pub is_like_solaris: bool,
/// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
/// only really used for figuring out how to find libraries, since Windows uses its own
/// library naming convention. Defaults to false.
pub is_like_windows: bool,
pub is_like_msvc: bool,
/// Whether the target toolchain is like Android's. Only useful for compiling against Android.
/// Defaults to false.
pub is_like_android: bool,
/// Whether the target toolchain is like Emscripten's. Only useful for compiling with
/// Emscripten toolchain.
/// Defaults to false.
pub is_like_emscripten: bool,
/// Whether the linker support GNU-like arguments such as -O. Defaults to false.
pub linker_is_gnu: bool,
/// The MinGW toolchain has a known issue that prevents it from correctly
/// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
/// symbol needs its own COMDAT section, weak linkage implies a large
/// number sections that easily exceeds the given limit for larger
/// codebases. Consequently we want a way to disallow weak linkage on some
/// platforms.
pub allows_weak_linkage: bool,
/// Whether the linker support rpaths or not. Defaults to false.
pub has_rpath: bool,
/// Whether to disable linking to the default libraries, typically corresponds
/// to `-nodefaultlibs`. Defaults to true.
pub no_default_libraries: bool,
/// Dynamically linked executables can be compiled as position independent
/// if the default relocation model of position independent code is not
/// changed. This is a requirement to take advantage of ASLR, as otherwise
/// the functions in the executable are not randomized and can be used
/// during an exploit of a vulnerability in any code.
pub position_independent_executables: bool,
/// Either partial, full, or off. Full RELRO makes the dynamic linker
/// resolve all symbols at startup and marks the GOT read-only before
/// starting the program, preventing overwriting the GOT.
pub relro_level: RelroLevel,
/// Format that archives should be emitted in. This affects whether we use
/// LLVM to assemble an archive or fall back to the system linker, and
/// currently only "gnu" is used to fall into LLVM. Unknown strings cause
/// the system linker to be used.
pub archive_format: String,
/// Is asm!() allowed? Defaults to true.
pub allow_asm: bool,
/// Whether the target uses a custom unwind resumption routine.
/// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
/// defined in libgcc. If this option is enabled, the target must provide
/// `eh_unwind_resume` lang item.
pub custom_unwind_resume: bool,
/// If necessary, a different crate to link exe allocators by default
pub exe_allocation_crate: Option<String>,
/// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
/// this target.
pub has_elf_tls: bool,
// This is mainly for easy compatibility with emscripten.
// If we give emcc .o files that are actually .bc files it
// will 'just work'.
pub obj_is_bitcode: bool,
// LLVM can't produce object files for this target. Instead, we'll make LLVM
// emit assembly and then use `gcc` to turn that assembly into an object
// file
pub no_integrated_as: bool,
/// Don't use this field; instead use the `.min_atomic_width()` method.
pub min_atomic_width: Option<u64>,
/// Don't use this field; instead use the `.max_atomic_width()` method.
pub max_atomic_width: Option<u64>,
/// Whether the target supports atomic CAS operations natively
pub atomic_cas: bool,
/// Panic strategy: "unwind" or "abort"
pub panic_strategy: PanicStrategy,
/// A blacklist of ABIs unsupported by the current target. Note that generic
/// ABIs are considered to be supported on all platforms and cannot be blacklisted.
pub abi_blacklist: Vec<Abi>,
/// Whether or not linking dylibs to a static CRT is allowed.
pub crt_static_allows_dylibs: bool,
/// Whether or not the CRT is statically linked by default.
pub crt_static_default: bool,
/// Whether or not crt-static is respected by the compiler (or is a no-op).
pub crt_static_respected: bool,
/// Whether or not stack probes (__rust_probestack) are enabled
pub stack_probes: bool,
/// The minimum alignment for global symbols.
pub min_global_align: Option<u64>,
/// Default number of codegen units to use in debug mode
pub default_codegen_units: Option<u64>,
/// Whether to generate trap instructions in places where optimization would
/// otherwise produce control flow that falls through into unrelated memory.
pub trap_unreachable: bool,
/// This target requires everything to be compiled with LTO to emit a final
/// executable, aka there is no native linker for this target.
pub requires_lto: bool,
/// This target has no support for threads.
pub singlethread: bool,
/// Whether library functions call lowering/optimization is disabled in LLVM
/// for this target unconditionally.
pub no_builtins: bool,
/// Whether to lower 128-bit operations to compiler_builtins calls. Use if
/// your backend only supports 64-bit and smaller math.
pub i128_lowering: bool,
/// The codegen backend to use for this target, typically "llvm"
pub codegen_backend: String,
/// The default visibility for symbols in this target should be "hidden"
/// rather than "default"
pub default_hidden_visibility: bool,
/// Whether or not bitcode is embedded in object files
pub embed_bitcode: bool,
/// Whether a .debug_gdb_scripts section will be added to the output object file
pub emit_debug_gdb_scripts: bool,
/// Whether or not to unconditionally `uwtable` attributes on functions,
/// typically because the platform needs to unwind for things like stack
/// unwinders.
pub requires_uwtable: bool,
}
impl Default for TargetOptions {
/// Create a set of "sane defaults" for any target. This is still
/// incomplete, and if used for compilation, will certainly not work.
fn default() -> TargetOptions {
TargetOptions {
is_builtin: false,
linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
lld_flavor: LldFlavor::Ld,
pre_link_args: LinkArgs::new(),
pre_link_args_crt: LinkArgs::new(),
post_link_args: LinkArgs::new(),
asm_args: Vec::new(),
cpu: "generic".to_string(),
features: "".to_string(),
dynamic_linking: false,
only_cdylib: false,
executables: false,
relocation_model: "pic".to_string(),
code_model: None,
tls_model: "global-dynamic".to_string(),
disable_redzone: false,
eliminate_frame_pointer: true,
function_sections: true,
dll_prefix: "lib".to_string(),
dll_suffix: ".so".to_string(),
exe_suffix: "".to_string(),
staticlib_prefix: "lib".to_string(),
staticlib_suffix: ".a".to_string(),
target_family: None,
abi_return_struct_as_int: false,
is_like_osx: false,
is_like_solaris: false,
is_like_windows: false,
is_like_android: false,
is_like_emscripten: false,
is_like_msvc: false,
linker_is_gnu: false,
allows_weak_linkage: true,
has_rpath: false,
no_default_libraries: true,
position_independent_executables: false,
relro_level: RelroLevel::None,
pre_link_objects_exe: Vec::new(),
pre_link_objects_exe_crt: Vec::new(),
pre_link_objects_dll: Vec::new(),
post_link_objects: Vec::new(),
post_link_objects_crt: Vec::new(),
late_link_args: LinkArgs::new(),
link_env: Vec::new(),
archive_format: "gnu".to_string(),
custom_unwind_resume: false,
exe_allocation_crate: None,
allow_asm: true,
has_elf_tls: false,
obj_is_bitcode: false,
no_integrated_as: false,
min_atomic_width: None,
max_atomic_width: None,
atomic_cas: true,
panic_strategy: PanicStrategy::Unwind,
abi_blacklist: vec![],
crt_static_allows_dylibs: false,
crt_static_default: false,
crt_static_respected: false,
stack_probes: false,
min_global_align: None,
default_codegen_units: None,
trap_unreachable: true,
requires_lto: false,
singlethread: false,
no_builtins: false,
i128_lowering: false,
codegen_backend: "llvm".to_string(),
default_hidden_visibility: false,
embed_bitcode: false,
emit_debug_gdb_scripts: true,
requires_uwtable: false,
}
}
}
impl Target {
/// Given a function ABI, turn "System" into the correct ABI for this target.
pub fn adjust_abi(&self, abi: Abi) -> Abi {
match abi {
Abi::System => {
if self.options.is_like_windows && self.arch == "x86" {
Abi::Stdcall
} else {
Abi::C
}
},
abi => abi
}
}
/// Minimum integer size in bits that this target can perform atomic
/// operations on.
pub fn min_atomic_width(&self) -> u64 {
self.options.min_atomic_width.unwrap_or(8)
}
/// Maximum integer size in bits that this target can perform atomic
/// operations on.
pub fn max_atomic_width(&self) -> u64 {
self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
}
pub fn is_abi_supported(&self, abi: Abi) -> bool {
abi.generic() || !self.options.abi_blacklist.contains(&abi)
}
/// Load a target descriptor from a JSON object.
pub fn from_json(obj: Json) -> TargetResult {
// While ugly, this code must remain this way to retain
// compatibility with existing JSON fields and the internal
// expected naming of the Target and TargetOptions structs.
// To ensure compatibility is retained, the built-in targets
// are round-tripped through this code to catch cases where
// the JSON parser is not updated to match the structs.
let get_req_field = |name: &str| {
obj.find(name)
.map(|s| s.as_string())
.and_then(|os| os.map(|s| s.to_string()))
.ok_or_else(|| format!("Field {} in target specification is required", name))
};
let get_opt_field = |name: &str, default: &str| {
obj.find(name).and_then(|s| s.as_string())
.map(|s| s.to_string())
.unwrap_or_else(|| default.to_string())
};
let mut base = Target {
llvm_target: get_req_field("llvm-target")?,
target_endian: get_req_field("target-endian")?,
target_pointer_width: get_req_field("target-pointer-width")?,
target_c_int_width: get_req_field("target-c-int-width")?,
data_layout: get_req_field("data-layout")?,
arch: get_req_field("arch")?,
target_os: get_req_field("os")?,
target_env: get_opt_field("env", ""),
target_vendor: get_opt_field("vendor", "unknown"),
linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
.ok_or_else(|| {
format!("linker flavor must be {}", LinkerFlavor::one_of())
})?,
options: Default::default(),
};
macro_rules! key {
($key_name:ident) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).map(|o| o.as_string()
.map(|s| base.options.$key_name = s.to_string()));
} );
($key_name:ident, bool) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..])
.map(|o| o.as_boolean()
.map(|s| base.options.$key_name = s));
} );
($key_name:ident, Option<u64>) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..])
.map(|o| o.as_u64()
.map(|s| base.options.$key_name = Some(s)));
} );
($key_name:ident, PanicStrategy) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
match s {
"unwind" => base.options.$key_name = PanicStrategy::Unwind,
"abort" => base.options.$key_name = PanicStrategy::Abort,
_ => return Some(Err(format!("'{}' is not a valid value for \
panic-strategy. Use 'unwind' or 'abort'.",
s))),
}
Some(Ok(()))
})).unwrap_or(Ok(()))
} );
($key_name:ident, RelroLevel) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
match s.parse::<RelroLevel>() {
Ok(level) => base.options.$key_name = level,
_ => return Some(Err(format!("'{}' is not a valid value for \
relro-level. Use 'full', 'partial, or 'off'.",
s))),
}
Some(Ok(()))
})).unwrap_or(Ok(()))
} );
($key_name:ident, list) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).map(|o| o.as_array()
.map(|v| base.options.$key_name = v.iter()
.map(|a| a.as_string().unwrap().to_string()).collect()
)
);
} );
($key_name:ident, optional) => ( {
let name = (stringify!($key_name)).replace("_", "-");
if let Some(o) = obj.find(&name[..]) {
base.options.$key_name = o
.as_string()
.map(|s| s.to_string() );
}
} );
($key_name:ident, LldFlavor) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
if let Some(flavor) = LldFlavor::from_str(&s) {
base.options.$key_name = flavor;
} else {
return Some(Err(format!(
"'{}' is not a valid value for lld-flavor. \
Use 'darwin', 'gnu', 'link' or 'wasm.",
s)))
}
Some(Ok(()))
})).unwrap_or(Ok(()))
} );
($key_name:ident, LinkerFlavor) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
LinkerFlavor::from_str(&s).ok_or_else(|| {
Err(format!("'{}' is not a valid value for linker-flavor. \
Use 'em', 'gcc', 'ld' or 'msvc.", s))
})
})).unwrap_or(Ok(()))
} );
($key_name:ident, link_args) => ( {
let name = (stringify!($key_name)).replace("_", "-");
if let Some(val) = obj.find(&name[..]) {
let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
JSON object with fields per linker-flavor.", name))?;
let mut args = LinkArgs::new();
for (k, v) in obj {
let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
format!("{}: '{}' is not a valid value for linker-flavor. \
Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
})?;
let v = v.as_array().ok_or_else(||
format!("{}.{}: expected a JSON array", name, k)
)?.iter().enumerate()
.map(|(i,s)| {
let s = s.as_string().ok_or_else(||
format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
Ok(s.to_owned())
})
.collect::<Result<Vec<_>, String>>()?;
args.insert(flavor, v);
}
base.options.$key_name = args;
}
} );
($key_name:ident, env) => ( {
let name = (stringify!($key_name)).replace("_", "-");
if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
for o in a {
if let Some(s) = o.as_string() {
let p = s.split('=').collect::<Vec<_>>();
if p.len() == 2 {
let k = p[0].to_string();
let v = p[1].to_string();
base.options.$key_name.push((k, v));
}
}
}
}
} );
}
key!(is_builtin, bool);
key!(linker, optional);
try!(key!(lld_flavor, LldFlavor));
key!(pre_link_args, link_args);
key!(pre_link_args_crt, link_args);
key!(pre_link_objects_exe, list);
key!(pre_link_objects_exe_crt, list);
key!(pre_link_objects_dll, list);
key!(late_link_args, link_args);
key!(post_link_objects, list);
key!(post_link_objects_crt, list);
key!(post_link_args, link_args);
key!(link_env, env);
key!(asm_args, list);
key!(cpu);
key!(features);
key!(dynamic_linking, bool);
key!(only_cdylib, bool);
key!(executables, bool);
key!(relocation_model);
key!(code_model, optional);
key!(tls_model);
key!(disable_redzone, bool);
key!(eliminate_frame_pointer, bool);
key!(function_sections, bool);
key!(dll_prefix);
key!(dll_suffix);
key!(exe_suffix);
key!(staticlib_prefix);
key!(staticlib_suffix);
key!(target_family, optional);
key!(abi_return_struct_as_int, bool);
key!(is_like_osx, bool);
key!(is_like_solaris, bool);
key!(is_like_windows, bool);
key!(is_like_msvc, bool);
key!(is_like_emscripten, bool);
key!(is_like_android, bool);
key!(linker_is_gnu, bool);
key!(allows_weak_linkage, bool);
key!(has_rpath, bool);
key!(no_default_libraries, bool);
key!(position_independent_executables, bool);
try!(key!(relro_level, RelroLevel));
key!(archive_format);
key!(allow_asm, bool);
key!(custom_unwind_resume, bool);
key!(exe_allocation_crate, optional);
key!(has_elf_tls, bool);
key!(obj_is_bitcode, bool);
key!(no_integrated_as, bool);
key!(max_atomic_width, Option<u64>);
key!(min_atomic_width, Option<u64>);
key!(atomic_cas, bool);
try!(key!(panic_strategy, PanicStrategy));
key!(crt_static_allows_dylibs, bool);
key!(crt_static_default, bool);
key!(crt_static_respected, bool);
key!(stack_probes, bool);
key!(min_global_align, Option<u64>);
key!(default_codegen_units, Option<u64>);
key!(trap_unreachable, bool);
key!(requires_lto, bool);
key!(singlethread, bool);
key!(no_builtins, bool);
key!(codegen_backend);
key!(default_hidden_visibility, bool);
key!(embed_bitcode, bool);
key!(emit_debug_gdb_scripts, bool);
key!(requires_uwtable, bool);
if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
for name in array.iter().filter_map(|abi| abi.as_string()) {
match lookup_abi(name) {
Some(abi) => {
if abi.generic() {
return Err(format!("The ABI \"{}\" is considered to be supported on \
all targets and cannot be blacklisted", abi))
}
base.options.abi_blacklist.push(abi)
}
None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
}
}
}
Ok(base)
}
/// Search RUST_TARGET_PATH for a JSON file specifying the given target
/// triple. Note that it could also just be a bare filename already, so also
/// check for that. If one of the hardcoded targets we know about, just
/// return it directly.
///
/// The error string could come from any of the APIs called, including
/// filesystem access and JSON decoding.
pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
use std::env;
use std::fs;
use serialize::json;
fn load_file(path: &Path) -> Result<Target, String> {
let contents = fs::read(path).map_err(|e| e.to_string())?;
let obj = json::from_reader(&mut &contents[..])
.map_err(|e| e.to_string())?;
Target::from_json(obj)
}
match *target_triple {
TargetTriple::TargetTriple(ref target_triple) => {
// check if triple is in list of supported targets
if let Ok(t) = load_specific(target_triple) {
return Ok(t)
}
// search for a file named `target_triple`.json in RUST_TARGET_PATH
let path = {
let mut target = target_triple.to_string();
target.push_str(".json");
PathBuf::from(target)
};
let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
// FIXME 16351: add a sane default search path?
for dir in env::split_paths(&target_path) {
let p = dir.join(&path);
if p.is_file() {
return load_file(&p);
}
}
Err(format!("Could not find specification for target {:?}", target_triple))
}
TargetTriple::TargetPath(ref target_path) => {
if target_path.is_file() {
return load_file(&target_path);
}
Err(format!("Target path {:?} is not a valid file", target_path))
}
}
}
}
impl ToJson for Target {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
let default: TargetOptions = Default::default();
macro_rules! target_val {
($attr:ident) => ( {
let name = (stringify!($attr)).replace("_", "-");
d.insert(name.to_string(), self.$attr.to_json());
} );
($attr:ident, $key_name:expr) => ( {
let name = $key_name;
d.insert(name.to_string(), self.$attr.to_json());
} );
}
macro_rules! target_option_val {
($attr:ident) => ( {
let name = (stringify!($attr)).replace("_", "-");
if default.$attr != self.options.$attr {
d.insert(name.to_string(), self.options.$attr.to_json());
}
} );
($attr:ident, $key_name:expr) => ( {
let name = $key_name;
if default.$attr != self.options.$attr {
d.insert(name.to_string(), self.options.$attr.to_json());
}
} );
(link_args - $attr:ident) => ( {
let name = (stringify!($attr)).replace("_", "-");
if default.$attr != self.options.$attr {
let obj = self.options.$attr
.iter()
.map(|(k, v)| (k.desc().to_owned(), v.clone()))
.collect::<BTreeMap<_, _>>();
d.insert(name.to_string(), obj.to_json());
}
} );
(env - $attr:ident) => ( {
let name = (stringify!($attr)).replace("_", "-");
if default.$attr != self.options.$attr {
let obj = self.options.$attr
.iter()
.map(|&(ref k, ref v)| k.clone() + "=" + &v)
.collect::<Vec<_>>();
d.insert(name.to_string(), obj.to_json());
}
} );
}
target_val!(llvm_target);
target_val!(target_endian);
target_val!(target_pointer_width);
target_val!(target_c_int_width);
target_val!(arch);
target_val!(target_os, "os");
target_val!(target_env, "env");
target_val!(target_vendor, "vendor");
target_val!(data_layout);
target_val!(linker_flavor);
target_option_val!(is_builtin);
target_option_val!(linker);
target_option_val!(lld_flavor);
target_option_val!(link_args - pre_link_args);
target_option_val!(link_args - pre_link_args_crt);
target_option_val!(pre_link_objects_exe);
target_option_val!(pre_link_objects_exe_crt);
target_option_val!(pre_link_objects_dll);
target_option_val!(link_args - late_link_args);
target_option_val!(post_link_objects);
target_option_val!(post_link_objects_crt);
target_option_val!(link_args - post_link_args);
target_option_val!(env - link_env);
target_option_val!(asm_args);
target_option_val!(cpu);
target_option_val!(features);
target_option_val!(dynamic_linking);
target_option_val!(only_cdylib);
target_option_val!(executables);
target_option_val!(relocation_model);
target_option_val!(code_model);
target_option_val!(tls_model);
target_option_val!(disable_redzone);
target_option_val!(eliminate_frame_pointer);
target_option_val!(function_sections);
target_option_val!(dll_prefix);
target_option_val!(dll_suffix);
target_option_val!(exe_suffix);
target_option_val!(staticlib_prefix);
target_option_val!(staticlib_suffix);
target_option_val!(target_family);
target_option_val!(abi_return_struct_as_int);
target_option_val!(is_like_osx);
target_option_val!(is_like_solaris);
target_option_val!(is_like_windows);
target_option_val!(is_like_msvc);
target_option_val!(is_like_emscripten);
target_option_val!(is_like_android);
target_option_val!(linker_is_gnu);
target_option_val!(allows_weak_linkage);
target_option_val!(has_rpath);
target_option_val!(no_default_libraries);
target_option_val!(position_independent_executables);
target_option_val!(relro_level);
target_option_val!(archive_format);
target_option_val!(allow_asm);
target_option_val!(custom_unwind_resume);
target_option_val!(exe_allocation_crate);
target_option_val!(has_elf_tls);
target_option_val!(obj_is_bitcode);
target_option_val!(no_integrated_as);
target_option_val!(min_atomic_width);
target_option_val!(max_atomic_width);
target_option_val!(atomic_cas);
target_option_val!(panic_strategy);
target_option_val!(crt_static_allows_dylibs);
target_option_val!(crt_static_default);
target_option_val!(crt_static_respected);
target_option_val!(stack_probes);
target_option_val!(min_global_align);
target_option_val!(default_codegen_units);
target_option_val!(trap_unreachable);
target_option_val!(requires_lto);
target_option_val!(singlethread);
target_option_val!(no_builtins);
target_option_val!(codegen_backend);
target_option_val!(default_hidden_visibility);
target_option_val!(embed_bitcode);
target_option_val!(emit_debug_gdb_scripts);
target_option_val!(requires_uwtable);
if default.abi_blacklist != self.options.abi_blacklist {
d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
.map(|&name| Abi::name(name).to_json())
.collect::<Vec<_>>().to_json());
}
Json::Object(d)
}
}
fn maybe_jemalloc() -> Option<String> {
if cfg!(feature = "jemalloc") {
Some("alloc_jemalloc".to_string())
} else {
None
}
}
/// Either a target triple string or a path to a JSON file.
#[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
pub enum TargetTriple {
TargetTriple(String),
TargetPath(PathBuf),
}
impl TargetTriple {
/// Creates a target triple from the passed target triple string.
pub fn from_triple(triple: &str) -> Self {
TargetTriple::TargetTriple(triple.to_string())
}
/// Creates a target triple from the passed target path.
pub fn from_path(path: &Path) -> Result<Self, io::Error> {
let canonicalized_path = path.canonicalize()?;
Ok(TargetTriple::TargetPath(canonicalized_path))
}
/// Returns a string triple for this target.
///
/// If this target is a path, the file name (without extension) is returned.
pub fn triple(&self) -> &str {
match *self {
TargetTriple::TargetTriple(ref triple) => triple,
TargetTriple::TargetPath(ref path) => {
path.file_stem().expect("target path must not be empty").to_str()
.expect("target path must be valid unicode")
}
}
}
/// Returns an extended string triple for this target.
///
/// If this target is a path, a hash of the path is appended to the triple returned
/// by `triple()`.
pub fn debug_triple(&self) -> String {
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
let triple = self.triple();
if let TargetTriple::TargetPath(ref path) = *self {
let mut hasher = DefaultHasher::new();
path.hash(&mut hasher);
let hash = hasher.finish();
format!("{}-{}", triple, hash)
} else {
triple.to_owned()
}
}
}
impl fmt::Display for TargetTriple {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.debug_triple())
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_unknown_l4re_uclibc.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::l4re_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "x86_64-unknown-l4re-uclibc".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "l4re".to_string(),
target_env: "uclibc".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Ld,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/armv7_unknown_linux_musleabihf.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.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
let base = super::linux_musl_base::opts();
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
// Most of these settings are copied from the armv7_unknown_linux_gnueabihf
// target.
options: TargetOptions {
features: "+v7,+vfp3,+d16,+thumb2,-neon".to_string(),
cpu: "generic".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/x86_64_rumprun_netbsd.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-rumprun-netbsd-gcc".to_string());
base.max_atomic_width = Some(64);
base.dynamic_linking = false;
base.has_rpath = false;
base.position_independent_executables = false;
base.disable_redzone = true;
base.no_default_libraries = false;
base.exe_allocation_crate = None;
base.stack_probes = true;
Ok(Target {
llvm_target: "x86_64-rumprun-netbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
arch: "x86_64".to_string(),
target_os: "netbsd".to_string(),
target_env: "".to_string(),
target_vendor: "rumprun".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/powerpc_unknown_netbsd.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
base.max_atomic_width = Some(32);
// see #36994
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "powerpc-unknown-netbsd".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-p:32:32-i64:64-n32".to_string(),
arch: "powerpc".to_string(),
target_os: "netbsd".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/s390x_unknown_linux_gnu.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
// z10 is the oldest CPU supported by LLVM
base.cpu = "z10".to_string();
// FIXME: The data_layout string below and the ABI implementation in
// cabi_s390x.rs are for now hard-coded to assume the no-vector ABI.
// Pass the -vector feature string to LLVM to respect this assumption.
base.features = "-vector".to_string();
base.max_atomic_width = Some(64);
// see #36994
base.exe_allocation_crate = None;
base.min_global_align = Some(16);
Ok(Target {
llvm_target: "s390x-unknown-linux-gnu".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64".to_string(),
arch: "s390x".to_string(),
target_os: "linux".to_string(),
target_env: "gnu".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/wasm32_unknown_emscripten.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::{LinkArgs, LinkerFlavor, Target, TargetOptions};
pub fn target() -> Result<Target, String> {
let mut post_link_args = LinkArgs::new();
post_link_args.insert(LinkerFlavor::Em,
vec!["-s".to_string(),
"BINARYEN=1".to_string(),
"-s".to_string(),
"ERROR_ON_UNDEFINED_SYMBOLS=1".to_string()]);
let opts = TargetOptions {
dynamic_linking: false,
executables: true,
// Today emcc emits two files - a .js file to bootstrap and
// possibly interpret the wasm, and a .wasm file
exe_suffix: ".js".to_string(),
linker_is_gnu: true,
allow_asm: false,
obj_is_bitcode: true,
is_like_emscripten: true,
max_atomic_width: Some(32),
post_link_args,
target_family: Some("unix".to_string()),
codegen_backend: "emscripten".to_string(),
.. Default::default()
};
Ok(Target {
llvm_target: "asmjs-unknown-emscripten".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
target_os: "emscripten".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
data_layout: "e-p:32:32-i64:64-v128:32:128-n32-S128".to_string(),
arch: "wasm32".to_string(),
linker_flavor: LinkerFlavor::Em,
options: opts,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/apple_base.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.
use std::env;
use spec::{LinkArgs, TargetOptions};
pub fn opts() -> TargetOptions {
// ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6
// either the linker will complain if it is used or the binary will end up
// segfaulting at runtime when run on 10.6. Rust by default supports macOS
// 10.7+, but there is a standard environment variable,
// MACOSX_DEPLOYMENT_TARGET, which is used to signal targeting older
// versions of macOS. For example compiling on 10.10 with
// MACOSX_DEPLOYMENT_TARGET set to 10.6 will cause the linker to generate
// warnings about the usage of ELF TLS.
//
// Here we detect what version is being requested, defaulting to 10.7. ELF
// TLS is flagged as enabled if it looks to be supported.
let deployment_target = env::var("MACOSX_DEPLOYMENT_TARGET").ok();
let version = deployment_target.as_ref().and_then(|s| {
let mut i = s.splitn(2, '.');
i.next().and_then(|a| i.next().map(|b| (a, b)))
}).and_then(|(a, b)| {
a.parse::<u32>().and_then(|a| b.parse::<u32>().map(|b| (a, b))).ok()
}).unwrap_or((10, 7));
TargetOptions {
// macOS has -dead_strip, which doesn't rely on function_sections
function_sections: false,
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
is_like_osx: true,
has_rpath: true,
dll_prefix: "lib".to_string(),
dll_suffix: ".dylib".to_string(),
archive_format: "bsd".to_string(),
pre_link_args: LinkArgs::new(),
exe_allocation_crate: super::maybe_jemalloc(),
has_elf_tls: version >= (10, 7),
abi_return_struct_as_int: true,
emit_debug_gdb_scripts: false,
.. Default::default()
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/sparcv9_sun_solaris.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.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::solaris_base::opts();
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
// llvm calls this "v9"
base.cpu = "v9".to_string();
base.max_atomic_width = Some(64);
base.exe_allocation_crate = None;
Ok(Target {
llvm_target: "sparcv9-sun-solaris".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-i64:64-n32:64-S128".to_string(),
// Use "sparc64" instead of "sparcv9" here, since the former is already
// used widely in the source base. If we ever needed ABI
// differentiation from the sparc64, we could, but that would probably
// just be confusing.
arch: "sparc64".to_string(),
target_os: "solaris".to_string(),
target_env: "".to_string(),
target_vendor: "sun".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/thumbv6m_none_eabi.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.
// Targets the Cortex-M0, Cortex-M0+ and Cortex-M1 processors (ARMv6-M architecture)
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
Ok(Target {
llvm_target: "thumbv6m-none-eabi".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "none".to_string(),
target_env: "".to_string(),
target_vendor: "".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
// The ARMv6-M architecture doesn't support unaligned loads/stores so we disable them
// with +strict-align.
features: "+strict-align".to_string(),
// There are no atomic CAS instructions available in the instruction set of the ARMv6-M
// architecture
atomic_cas: false,
.. super::thumb_base::opts()
}
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/aarch64_linux_android.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn target() -> TargetResult {
let mut base = super::android_base::opts();
base.max_atomic_width = Some(128);
// As documented in http://developer.android.com/ndk/guides/cpu-features.html
// the neon (ASIMD) and FP must exist on all android aarch64 targets.
base.features = "+neon,+fp-armv8".to_string();
Ok(Target {
llvm_target: "aarch64-linux-android".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "android".to_string(),
target_env: "".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
},
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/apple_ios_base.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.
use std::io;
use std::process::Command;
use spec::{LinkArgs, LinkerFlavor, TargetOptions};
use self::Arch::*;
#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub enum Arch {
Armv7,
Armv7s,
Arm64,
I386,
X86_64
}
impl Arch {
pub fn to_string(self) -> &'static str {
match self {
Armv7 => "armv7",
Armv7s => "armv7s",
Arm64 => "arm64",
I386 => "i386",
X86_64 => "x86_64"
}
}
}
pub fn get_sdk_root(sdk_name: &str) -> Result<String, String> {
let res = Command::new("xcrun")
.arg("--show-sdk-path")
.arg("-sdk")
.arg(sdk_name)
.output()
.and_then(|output| {
if output.status.success() {
Ok(String::from_utf8(output.stdout).unwrap())
} else {
let error = String::from_utf8(output.stderr);
let error = format!("process exit with error: {}",
error.unwrap());
Err(io::Error::new(io::ErrorKind::Other,
&error[..]))
}
});
match res {
Ok(output) => Ok(output.trim().to_string()),
Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e))
}
}
fn build_pre_link_args(arch: Arch) -> Result<LinkArgs, String> {
let sdk_name = match arch {
Armv7 | Armv7s | Arm64 => "iphoneos",
I386 | X86_64 => "iphonesimulator"
};
let arch_name = arch.to_string();
let sdk_root = get_sdk_root(sdk_name)?;
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc,
vec!["-arch".to_string(),
arch_name.to_string(),
"-Wl,-syslibroot".to_string(),
sdk_root]);
Ok(args)
}
fn target_cpu(arch: Arch) -> String {
match arch {
Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher
Armv7s => "cortex-a9",
Arm64 => "cyclone",
I386 => "yonah",
X86_64 => "core2",
}.to_string()
}
pub fn opts(arch: Arch) -> Result<TargetOptions, String> {
let pre_link_args = build_pre_link_args(arch)?;
Ok(TargetOptions {
cpu: target_cpu(arch),
dynamic_linking: false,
executables: true,
pre_link_args,
has_elf_tls: false,
eliminate_frame_pointer: false,
// The following line is a workaround for jemalloc 4.5 being broken on
// ios. jemalloc 5.0 is supposed to fix this.
// see https://github.com/rust-lang/rust/issues/45262
exe_allocation_crate: None,
.. super::apple_base::opts()
})
}
| 0
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target
|
solana_public_repos/solana-playground/solana-playground/wasm/rustfmt/deps/librustc_target/spec/bitrig_base.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.
use spec::{TargetOptions, RelroLevel};
use std::default::Default;
pub fn opts() -> TargetOptions {
TargetOptions {
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
position_independent_executables: true,
relro_level: RelroLevel::Full,
.. Default::default()
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.