file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
drop-trait-enum.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::thread;
use std::sync::mpsc::{channel, Sender};
#[derive(PartialEq, Debug)]
enum Message {
Dropped,
DestructorRan
}
struct SendOnDrop {
sender: Sender<Message>
}
impl Drop for SendOnDrop {
fn drop(&mut self) {
self.sender.send(Message::Dropped).unwrap();
}
}
enum Foo {
SimpleVariant(Sender<Message>),
NestedVariant(Box<usize>, SendOnDrop, Sender<Message>),
FailingVariant { on_drop: SendOnDrop }
}
impl Drop for Foo {
fn drop(&mut self) {
match self {
&mut Foo::SimpleVariant(ref mut sender) => {
sender.send(Message::DestructorRan).unwrap();
}
&mut Foo::NestedVariant(_, _, ref mut sender) => {
sender.send(Message::DestructorRan).unwrap();
}
&mut Foo::FailingVariant {.. } => {
panic!("Failed");
}
}
}
}
pub fn main() {
let (sender, receiver) = channel();
{
let v = Foo::SimpleVariant(sender);
}
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
{
let v = Foo::NestedVariant(box 42, SendOnDrop { sender: sender.clone() }, sender);
}
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
let t = thread::spawn(move|| {
let v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
});
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
drop(t.join());
let (sender, receiver) = channel();
let t = {
thread::spawn(move|| {
let mut v = Foo::NestedVariant(box 42, SendOnDrop {
sender: sender.clone()
}, sender.clone());
v = Foo::NestedVariant(box 42,
|
};
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
drop(t.join());
}
|
SendOnDrop { sender: sender.clone() },
sender.clone());
v = Foo::SimpleVariant(sender.clone());
v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
})
|
random_line_split
|
drop-trait-enum.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::thread;
use std::sync::mpsc::{channel, Sender};
#[derive(PartialEq, Debug)]
enum Message {
Dropped,
DestructorRan
}
struct SendOnDrop {
sender: Sender<Message>
}
impl Drop for SendOnDrop {
fn drop(&mut self) {
self.sender.send(Message::Dropped).unwrap();
}
}
enum Foo {
SimpleVariant(Sender<Message>),
NestedVariant(Box<usize>, SendOnDrop, Sender<Message>),
FailingVariant { on_drop: SendOnDrop }
}
impl Drop for Foo {
fn drop(&mut self)
|
}
pub fn main() {
let (sender, receiver) = channel();
{
let v = Foo::SimpleVariant(sender);
}
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
{
let v = Foo::NestedVariant(box 42, SendOnDrop { sender: sender.clone() }, sender);
}
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
let t = thread::spawn(move|| {
let v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
});
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
drop(t.join());
let (sender, receiver) = channel();
let t = {
thread::spawn(move|| {
let mut v = Foo::NestedVariant(box 42, SendOnDrop {
sender: sender.clone()
}, sender.clone());
v = Foo::NestedVariant(box 42,
SendOnDrop { sender: sender.clone() },
sender.clone());
v = Foo::SimpleVariant(sender.clone());
v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
})
};
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
drop(t.join());
}
|
{
match self {
&mut Foo::SimpleVariant(ref mut sender) => {
sender.send(Message::DestructorRan).unwrap();
}
&mut Foo::NestedVariant(_, _, ref mut sender) => {
sender.send(Message::DestructorRan).unwrap();
}
&mut Foo::FailingVariant { .. } => {
panic!("Failed");
}
}
}
|
identifier_body
|
drop-trait-enum.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::thread;
use std::sync::mpsc::{channel, Sender};
#[derive(PartialEq, Debug)]
enum Message {
Dropped,
DestructorRan
}
struct
|
{
sender: Sender<Message>
}
impl Drop for SendOnDrop {
fn drop(&mut self) {
self.sender.send(Message::Dropped).unwrap();
}
}
enum Foo {
SimpleVariant(Sender<Message>),
NestedVariant(Box<usize>, SendOnDrop, Sender<Message>),
FailingVariant { on_drop: SendOnDrop }
}
impl Drop for Foo {
fn drop(&mut self) {
match self {
&mut Foo::SimpleVariant(ref mut sender) => {
sender.send(Message::DestructorRan).unwrap();
}
&mut Foo::NestedVariant(_, _, ref mut sender) => {
sender.send(Message::DestructorRan).unwrap();
}
&mut Foo::FailingVariant {.. } => {
panic!("Failed");
}
}
}
}
pub fn main() {
let (sender, receiver) = channel();
{
let v = Foo::SimpleVariant(sender);
}
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
{
let v = Foo::NestedVariant(box 42, SendOnDrop { sender: sender.clone() }, sender);
}
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
let t = thread::spawn(move|| {
let v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
});
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
drop(t.join());
let (sender, receiver) = channel();
let t = {
thread::spawn(move|| {
let mut v = Foo::NestedVariant(box 42, SendOnDrop {
sender: sender.clone()
}, sender.clone());
v = Foo::NestedVariant(box 42,
SendOnDrop { sender: sender.clone() },
sender.clone());
v = Foo::SimpleVariant(sender.clone());
v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
})
};
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
drop(t.join());
}
|
SendOnDrop
|
identifier_name
|
assert-eq-macro-success.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
#[deriving(PartialEq, Show)]
struct
|
{ x : int }
pub fn main() {
assert_eq!(14,14);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(@Point{x:34},@Point{x:34});
}
|
Point
|
identifier_name
|
assert-eq-macro-success.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
|
pub fn main() {
assert_eq!(14,14);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(@Point{x:34},@Point{x:34});
}
|
#[deriving(PartialEq, Show)]
struct Point { x : int }
|
random_line_split
|
common.rs
|
build::Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
build::Unreachable(out);
}
return out;
}
}
// Heap selectors. Indicate which heap something should go on.
#[deriving(Eq)]
pub enum heap {
heap_managed,
heap_exchange,
heap_exchange_closure
}
// Basic block context. We create a block context for each basic block
// (single-entry, single-exit sequence of instructions) we generate from Rust
// code. Each basic block we generate is attached to a function, typically
// with many basic blocks per function. All the basic blocks attached to a
// function are organized as a directed graph.
pub struct Block<'a> {
// The BasicBlockRef returned from a call to
// llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
// block to the function pointed to by llfn. We insert
// instructions into that block by way of this block context.
// The block pointing to this one in the function's digraph.
llbb: BasicBlockRef,
terminated: Cell<bool>,
unreachable: Cell<bool>,
// Is this block part of a landing pad?
is_lpad: bool,
// AST node-id associated with this block, if any. Used for
// debugging purposes only.
opt_node_id: Option<ast::NodeId>,
// The function context for the function to which this block is
// attached.
fcx: &'a FunctionContext<'a>,
}
impl<'a> Block<'a> {
pub fn new<'a>(
llbb: BasicBlockRef,
is_lpad: bool,
opt_node_id: Option<ast::NodeId>,
fcx: &'a FunctionContext<'a>)
-> &'a Block<'a> {
fcx.block_arena.alloc(Block {
llbb: llbb,
terminated: Cell::new(false),
unreachable: Cell::new(false),
is_lpad: is_lpad,
opt_node_id: opt_node_id,
fcx: fcx
})
}
pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
pub fn tcx(&self) -> &'a ty::ctxt {
&self.fcx.ccx.tcx
}
pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
pub fn ident(&self, ident: Ident) -> ~str {
token::get_ident(ident).get().to_str()
}
pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
self.tcx().map.node_to_str(id)
}
pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
e.repr(self.tcx())
}
pub fn expr_is_lval(&self, e: &ast::Expr) -> bool {
ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
}
pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
}
pub fn def(&self, nid: ast::NodeId) -> ast::Def {
match self.tcx().def_map.borrow().find(&nid) {
Some(&v) => v,
None => {
self.tcx().sess.bug(format!(
"no def associated with node id {:?}", nid));
}
}
}
pub fn val_to_str(&self, val: ValueRef) -> ~str {
self.ccx().tn.val_to_str(val)
}
pub fn llty_str(&self, ty: Type) -> ~str {
self.ccx().tn.type_to_str(ty)
}
pub fn ty_to_str(&self, t: ty::t) -> ~str {
t.repr(self.tcx())
}
pub fn to_str(&self) -> ~str {
let blk: *Block = self;
format!("[block {}]", blk)
}
}
pub struct Result<'a> {
bcx: &'a Block<'a>,
val: ValueRef
}
pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
Result {
bcx: bcx,
val: val,
}
}
impl<'a> Result<'a> {
pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
*bcx = self.bcx;
return self.val;
}
}
pub fn val_ty(v: ValueRef) -> Type {
unsafe {
Type::from_ref(llvm::LLVMTypeOf(v))
}
}
// LLVM constant constructors.
pub fn C_null(t: Type) -> ValueRef {
unsafe {
llvm::LLVMConstNull(t.to_ref())
}
}
pub fn C_undef(t: Type) -> ValueRef {
unsafe {
llvm::LLVMGetUndef(t.to_ref())
}
}
pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
unsafe {
llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
}
}
pub fn C_floating(s: &str, t: Type) -> ValueRef {
unsafe {
s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
}
}
pub fn C_nil(ccx: &CrateContext) -> ValueRef {
C_struct(ccx, [], false)
}
pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
C_integral(Type::bool(ccx), val as u64, false)
}
pub fn C_i1(ccx: &CrateContext, val: bool) -> ValueRef {
C_integral(Type::i1(ccx), val as u64, false)
}
pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
C_integral(Type::i32(ccx), i as u64, true)
}
pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
C_integral(Type::i64(ccx), i as u64, true)
}
pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
C_integral(Type::i64(ccx), i, false)
}
pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
C_integral(ccx.int_type, i as u64, true)
}
pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
C_integral(ccx.int_type, i as u64, false)
}
pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
C_integral(Type::i8(ccx), i as u64, false)
}
// This is a 'c-like' raw string, which differs from
// our boxed-and-length-annotated strings.
pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef {
unsafe {
match cx.const_cstr_cache.borrow().find(&s) {
Some(&llval) => return llval,
None => ()
}
let sc = llvm::LLVMConstStringInContext(cx.llcx,
s.get().as_ptr() as *c_char,
s.get().len() as c_uint,
False);
let gsym = token::gensym("str");
let g = format!("str{}", gsym).with_c_str(|buf| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
});
llvm::LLVMSetInitializer(g, sc);
llvm::LLVMSetGlobalConstant(g, True);
lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
cx.const_cstr_cache.borrow_mut().insert(s, g);
g
}
}
// NB: Do not use `do_spill_noroot` to make this into a constant string, or
// you will be kicked off fast isel. See issue #4352 for an example of this.
pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
unsafe {
let len = s.get().len();
let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p(cx).to_ref());
C_struct(cx, [cs, C_uint(cx, len)], false)
}
}
pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
unsafe {
let len = data.len();
let lldata = C_bytes(cx, data);
let gsym = token::gensym("binary");
let g = format!("binary{}", gsym).with_c_str(|buf| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
});
llvm::LLVMSetInitializer(g, lldata);
llvm::LLVMSetGlobalConstant(g, True);
lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
C_struct(cx, [cs, C_uint(cx, len)], false)
}
}
pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
unsafe {
llvm::LLVMConstStructInContext(ccx.llcx,
elts.as_ptr(), elts.len() as c_uint,
packed as Bool)
}
}
pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
unsafe {
llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
}
}
pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
unsafe {
return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
}
}
pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
unsafe {
let ptr = bytes.as_ptr() as *c_char;
return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
}
}
pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
unsafe {
llvm::LLVMGetParam(fndecl, param as c_uint)
}
}
pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
-> ValueRef {
unsafe {
let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
debug!("const_get_elt(v={}, us={:?}, r={})",
cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
return r;
}
}
pub fn is_const(v: ValueRef) -> bool {
unsafe {
llvm::LLVMIsConstant(v) == True
}
}
pub fn const_to_int(v: ValueRef) -> c_longlong {
unsafe {
llvm::LLVMConstIntGetSExtValue(v)
}
}
pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
unsafe {
llvm::LLVMConstIntGetZExtValue(v)
}
}
pub fn is_undef(val: ValueRef) -> bool {
unsafe {
llvm::LLVMIsUndef(val)!= False
}
}
pub fn is_null(val: ValueRef) -> bool {
unsafe {
llvm::LLVMIsNull(val)!= False
}
}
// Used to identify cached monomorphized functions and vtables
#[deriving(Eq, TotalEq, Hash)]
pub enum mono_param_id {
mono_precise(ty::t, Option<@Vec<mono_id> >),
mono_any,
mono_repr(uint /* size */,
uint /* align */,
MonoDataClass,
datum::RvalueMode),
}
#[deriving(Eq, TotalEq, Hash)]
pub enum MonoDataClass {
MonoBits, // Anything not treated differently from arbitrary integer data
MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
// FIXME(#3547)---scalars and floats are
// treated differently in most ABIs. But we
// should be doing something more detailed
// here.
MonoFloat
}
pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
match ty::get(t).sty {
ty::ty_float(_) => MonoFloat,
ty::ty_rptr(..) | ty::ty_uniq(..) | ty::ty_box(..) |
ty::ty_str(ty::vstore_uniq) | ty::ty_vec(_, ty::vstore_uniq) |
ty::ty_bare_fn(..) => MonoNonNull,
// Is that everything? Would closures or slices qualify?
_ => MonoBits
}
}
#[deriving(Eq, TotalEq, Hash)]
pub struct mono_id_ {
def: ast::DefId,
params: Vec<mono_param_id> }
pub type mono_id = @mono_id_;
pub fn umax(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
return build::Select(cx, cond, b, a);
}
pub fn umin(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
return build::Select(cx, cond, a, b);
}
pub fn align_to(cx: &Block, off: ValueRef, align: ValueRef) -> ValueRef {
let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
let bumped = build::Add(cx, off, mask);
return build::And(cx, bumped, build::Not(cx, mask));
}
pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
match bcx.fcx.param_substs {
Some(substs) => {
ty::subst_tps(bcx.tcx(), substs.tys.as_slice(), substs.self_ty, t)
}
_ => {
assert!(!ty::type_has_params(t));
assert!(!ty::type_has_self(t));
t
}
}
}
pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
let tcx = bcx.tcx();
let t = ty::node_id_to_type(tcx, id);
monomorphize_type(bcx, t)
}
pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
node_id_type(bcx, ex.id)
}
pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
let tcx = bcx.tcx();
let t = ty::expr_ty_adjusted(tcx, ex, &*bcx.ccx().maps.method_map.borrow());
monomorphize_type(bcx, t)
}
// Key used to lookup values supplied for type parameters in an expr.
#[deriving(Eq)]
pub enum ExprOrMethodCall {
// Type parameters for a path like `None::<int>`
ExprId(ast::NodeId),
// Type parameters for a method call like `a.foo::<int>()`
MethodCall(typeck::MethodCall)
}
pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec<ty::t> {
let tcx = bcx.tcx();
let params = match node {
ExprId(id) => ty::node_id_to_type_params(tcx, id),
MethodCall(method_call) => {
bcx.ccx().maps.method_map.borrow().get(&method_call).substs.tps.clone()
}
};
if!params.iter().all(|t|!ty::type_needs_infer(*t)) {
bcx.sess().bug(
format!("type parameters for node {:?} include inference types: {}",
node, params.iter()
.map(|t| bcx.ty_to_str(*t))
.collect::<Vec<~str>>()
.connect(",")));
}
match bcx.fcx.param_substs {
Some(substs) => {
params.iter().map(|t| {
ty::subst_tps(tcx, substs.tys.as_slice(), substs.self_ty, *t)
}).collect()
}
_ => params
}
}
pub fn node_vtables(bcx: &Block, id: typeck::MethodCall)
-> Option<typeck::vtable_res> {
let vtable_map = bcx.ccx().maps.vtable_map.borrow();
let raw_vtables = vtable_map.find(&id);
raw_vtables.map(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
}
// Apply the typaram substitutions in the FunctionContext to some
// vtables. This should eliminate any vtable_params.
pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
-> typeck::vtable_res {
resolve_vtables_under_param_substs(fcx.ccx.tcx(),
fcx.param_substs,
vts)
}
pub fn resolve_vtables_under_param_substs(tcx: &ty::ctxt,
param_substs: Option<@param_substs>,
vts: typeck::vtable_res)
-> typeck::vtable_res {
@vts.iter().map(|ds|
resolve_param_vtables_under_param_substs(tcx,
param_substs,
*ds))
.collect()
}
pub fn resolve_param_vtables_under_param_substs(
tcx: &ty::ctxt,
param_substs: Option<@param_substs>,
ds: typeck::vtable_param_res)
-> typeck::vtable_param_res {
@ds.iter().map(
|d| resolve_vtable_under_param_substs(tcx,
param_substs,
d))
.collect()
}
pub fn resolve_vtable_under_param_substs(tcx: &ty::ctxt,
param_substs: Option<@param_substs>,
vt: &typeck::vtable_origin)
-> typeck::vtable_origin {
match *vt {
typeck::vtable_static(trait_id, ref tys, sub) => {
let tys = match param_substs {
Some(substs) => {
tys.iter().map(|t| {
ty::subst_tps(tcx,
substs.tys.as_slice(),
substs.self_ty,
*t)
}).collect()
}
_ => Vec::from_slice(tys.as_slice())
};
typeck::vtable_static(
trait_id, tys,
resolve_vtables_under_param_substs(tcx, param_substs, sub))
}
typeck::vtable_param(n_param, n_bound) => {
match param_substs {
Some(substs) => {
find_vtable(tcx, substs, n_param, n_bound)
}
_ => {
tcx.sess.bug(format!(
"resolve_vtable_under_param_substs: asked to lookup \
but no vtables in the fn_ctxt!"))
}
}
}
}
}
pub fn find_vtable(tcx: &ty::ctxt,
ps: ¶m_substs,
n_param: typeck::param_index,
n_bound: uint)
-> typeck::vtable_origin {
debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
n_param, n_bound, ps.repr(tcx));
let param_bounds = match n_param {
typeck::param_self => ps.self_vtables.expect("self vtables missing"),
typeck::param_numbered(n) => {
let tables = ps.vtables
.expect("vtables missing where they are needed");
*tables.get(n)
}
};
param_bounds.get(n_bound).clone()
}
pub fn dummy_substs(tps: Vec<ty::t> ) -> ty::substs {
substs {
regions: ty::ErasedRegions,
self_ty: None,
tps: tps
}
}
|
random_line_split
|
||
common.rs
|
llvm::LLVMDisposeBuilder(self.b);
}
}
}
pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
BuilderRef_res {
b: b
}
}
pub type ExternMap = HashMap<~str, ValueRef>;
// Here `self_ty` is the real type of the self parameter to this method. It
// will only be set in the case of default methods.
pub struct param_substs {
tys: Vec<ty::t>,
self_ty: Option<ty::t>,
vtables: Option<typeck::vtable_res>,
self_vtables: Option<typeck::vtable_param_res>
}
impl param_substs {
pub fn validate(&self) {
for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
}
}
fn param_substs_to_str(this: ¶m_substs, tcx: &ty::ctxt) -> ~str {
format!("param_substs \\{tys:{}, vtables:{}\\}",
this.tys.repr(tcx),
this.vtables.repr(tcx))
}
impl Repr for param_substs {
fn repr(&self, tcx: &ty::ctxt) -> ~str {
param_substs_to_str(self, tcx)
}
}
// work around bizarre resolve errors
pub type RvalueDatum = datum::Datum<datum::Rvalue>;
pub type LvalueDatum = datum::Datum<datum::Lvalue>;
// Function context. Every LLVM function we create will have one of
// these.
pub struct FunctionContext<'a> {
// The ValueRef returned from a call to llvm::LLVMAddFunction; the
// address of the first instruction in the sequence of
// instructions for this function that will go in the.text
// section of the executable we're generating.
llfn: ValueRef,
// The environment argument in a closure.
llenv: Option<ValueRef>,
// The place to store the return value. If the return type is immediate,
// this is an alloca in the function. Otherwise, it's the hidden first
// parameter to the function. After function construction, this should
// always be Some.
llretptr: Cell<Option<ValueRef>>,
entry_bcx: RefCell<Option<&'a Block<'a>>>,
// These elements: "hoisted basic blocks" containing
// administrative activities that have to happen in only one place in
// the function, due to LLVM's quirks.
// A marker for the place where we want to insert the function's static
// allocas, so that LLVM will coalesce them into a single alloca call.
alloca_insert_pt: Cell<Option<ValueRef>>,
llreturn: Cell<Option<BasicBlockRef>>,
// The a value alloca'd for calls to upcalls.rust_personality. Used when
// outputting the resume instruction.
personality: Cell<Option<ValueRef>>,
// True if the caller expects this fn to use the out pointer to
// return. Either way, your code should write into llretptr, but if
// this value is false, llretptr will be a local alloca.
caller_expects_out_pointer: bool,
// Maps arguments to allocas created for them in llallocas.
llargs: RefCell<NodeMap<LvalueDatum>>,
// Maps the def_ids for local variables to the allocas created for
// them in llallocas.
lllocals: RefCell<NodeMap<LvalueDatum>>,
// Same as above, but for closure upvars
llupvars: RefCell<NodeMap<ValueRef>>,
// The NodeId of the function, or -1 if it doesn't correspond to
// a user-defined function.
id: ast::NodeId,
// If this function is being monomorphized, this contains the type
// substitutions used.
param_substs: Option<@param_substs>,
// The source span and nesting context where this function comes from, for
// error reporting and symbol generation.
span: Option<Span>,
// The arena that blocks are allocated from.
block_arena: &'a TypedArena<Block<'a>>,
// This function's enclosing crate context.
ccx: &'a CrateContext,
// Used and maintained by the debuginfo module.
debug_context: debuginfo::FunctionDebugContext,
// Cleanup scopes.
scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
}
impl<'a> FunctionContext<'a> {
pub fn arg_pos(&self, arg: uint) -> uint {
let arg = self.env_arg_pos() + arg;
if self.llenv.is_some() {
arg + 1
} else {
arg
}
}
pub fn out_arg_pos(&self) -> uint {
assert!(self.caller_expects_out_pointer);
0u
}
pub fn env_arg_pos(&self) -> uint {
if self.caller_expects_out_pointer {
1u
} else {
0u
}
}
pub fn cleanup(&self) {
unsafe {
llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
.get()
.unwrap());
}
// Remove the cycle between fcx and bcx, so memory can be freed
self.entry_bcx.set(None);
}
pub fn get_llreturn(&self) -> BasicBlockRef {
if self.llreturn.get().is_none() {
self.llreturn.set(Some(unsafe {
"return".with_c_str(|buf| {
llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx, self.llfn, buf)
})
}))
}
self.llreturn.get().unwrap()
}
pub fn new_block(&'a self,
is_lpad: bool,
name: &str,
opt_node_id: Option<ast::NodeId>)
-> &'a Block<'a> {
unsafe {
let llbb = name.with_c_str(|buf| {
llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
self.llfn,
buf)
});
Block::new(llbb, is_lpad, opt_node_id, self)
}
}
pub fn new_id_block(&'a self,
name: &str,
node_id: ast::NodeId)
-> &'a Block<'a> {
self.new_block(false, name, Some(node_id))
}
pub fn new_temp_block(&'a self,
name: &str)
-> &'a Block<'a> {
self.new_block(false, name, None)
}
pub fn join_blocks(&'a self,
id: ast::NodeId,
in_cxs: &[&'a Block<'a>])
-> &'a Block<'a> {
let out = self.new_id_block("join", id);
let mut reachable = false;
for bcx in in_cxs.iter() {
if!bcx.unreachable.get() {
build::Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
build::Unreachable(out);
}
return out;
}
}
// Heap selectors. Indicate which heap something should go on.
#[deriving(Eq)]
pub enum heap {
heap_managed,
heap_exchange,
heap_exchange_closure
}
// Basic block context. We create a block context for each basic block
// (single-entry, single-exit sequence of instructions) we generate from Rust
// code. Each basic block we generate is attached to a function, typically
// with many basic blocks per function. All the basic blocks attached to a
// function are organized as a directed graph.
pub struct Block<'a> {
// The BasicBlockRef returned from a call to
// llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
// block to the function pointed to by llfn. We insert
// instructions into that block by way of this block context.
// The block pointing to this one in the function's digraph.
llbb: BasicBlockRef,
terminated: Cell<bool>,
unreachable: Cell<bool>,
// Is this block part of a landing pad?
is_lpad: bool,
// AST node-id associated with this block, if any. Used for
// debugging purposes only.
opt_node_id: Option<ast::NodeId>,
// The function context for the function to which this block is
// attached.
fcx: &'a FunctionContext<'a>,
}
impl<'a> Block<'a> {
pub fn new<'a>(
llbb: BasicBlockRef,
is_lpad: bool,
opt_node_id: Option<ast::NodeId>,
fcx: &'a FunctionContext<'a>)
-> &'a Block<'a> {
fcx.block_arena.alloc(Block {
llbb: llbb,
terminated: Cell::new(false),
unreachable: Cell::new(false),
is_lpad: is_lpad,
opt_node_id: opt_node_id,
fcx: fcx
})
}
pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
pub fn tcx(&self) -> &'a ty::ctxt {
&self.fcx.ccx.tcx
}
pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
pub fn ident(&self, ident: Ident) -> ~str {
token::get_ident(ident).get().to_str()
}
pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
self.tcx().map.node_to_str(id)
}
pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
e.repr(self.tcx())
}
pub fn expr_is_lval(&self, e: &ast::Expr) -> bool {
ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
}
pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
}
pub fn def(&self, nid: ast::NodeId) -> ast::Def {
match self.tcx().def_map.borrow().find(&nid) {
Some(&v) => v,
None => {
self.tcx().sess.bug(format!(
"no def associated with node id {:?}", nid));
}
}
}
pub fn val_to_str(&self, val: ValueRef) -> ~str {
self.ccx().tn.val_to_str(val)
}
pub fn llty_str(&self, ty: Type) -> ~str {
self.ccx().tn.type_to_str(ty)
}
pub fn ty_to_str(&self, t: ty::t) -> ~str {
t.repr(self.tcx())
}
pub fn to_str(&self) -> ~str {
let blk: *Block = self;
format!("[block {}]", blk)
}
}
pub struct Result<'a> {
bcx: &'a Block<'a>,
val: ValueRef
}
pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
Result {
bcx: bcx,
val: val,
}
}
impl<'a> Result<'a> {
pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
*bcx = self.bcx;
return self.val;
}
}
pub fn val_ty(v: ValueRef) -> Type {
unsafe {
Type::from_ref(llvm::LLVMTypeOf(v))
}
}
// LLVM constant constructors.
pub fn C_null(t: Type) -> ValueRef {
unsafe {
llvm::LLVMConstNull(t.to_ref())
}
}
pub fn C_undef(t: Type) -> ValueRef {
unsafe {
llvm::LLVMGetUndef(t.to_ref())
}
}
pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
unsafe {
llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
}
}
pub fn C_floating(s: &str, t: Type) -> ValueRef {
unsafe {
s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
}
}
pub fn C_nil(ccx: &CrateContext) -> ValueRef {
C_struct(ccx, [], false)
}
pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
C_integral(Type::bool(ccx), val as u64, false)
}
pub fn C_i1(ccx: &CrateContext, val: bool) -> ValueRef {
C_integral(Type::i1(ccx), val as u64, false)
}
pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
C_integral(Type::i32(ccx), i as u64, true)
}
pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
C_integral(Type::i64(ccx), i as u64, true)
}
pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
C_integral(Type::i64(ccx), i, false)
}
pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
C_integral(ccx.int_type, i as u64, true)
}
pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
C_integral(ccx.int_type, i as u64, false)
}
pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
C_integral(Type::i8(ccx), i as u64, false)
}
// This is a 'c-like' raw string, which differs from
// our boxed-and-length-annotated strings.
pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef {
unsafe {
match cx.const_cstr_cache.borrow().find(&s) {
Some(&llval) => return llval,
None => ()
}
let sc = llvm::LLVMConstStringInContext(cx.llcx,
s.get().as_ptr() as *c_char,
s.get().len() as c_uint,
False);
let gsym = token::gensym("str");
let g = format!("str{}", gsym).with_c_str(|buf| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
});
llvm::LLVMSetInitializer(g, sc);
llvm::LLVMSetGlobalConstant(g, True);
lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
cx.const_cstr_cache.borrow_mut().insert(s, g);
g
}
}
// NB: Do not use `do_spill_noroot` to make this into a constant string, or
// you will be kicked off fast isel. See issue #4352 for an example of this.
pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
unsafe {
let len = s.get().len();
let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p(cx).to_ref());
C_struct(cx, [cs, C_uint(cx, len)], false)
}
}
pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
unsafe {
let len = data.len();
let lldata = C_bytes(cx, data);
let gsym = token::gensym("binary");
let g = format!("binary{}", gsym).with_c_str(|buf| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
});
llvm::LLVMSetInitializer(g, lldata);
llvm::LLVMSetGlobalConstant(g, True);
lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
C_struct(cx, [cs, C_uint(cx, len)], false)
}
}
pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
unsafe {
llvm::LLVMConstStructInContext(ccx.llcx,
elts.as_ptr(), elts.len() as c_uint,
packed as Bool)
}
}
pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
unsafe {
llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
}
}
pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
unsafe {
return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
}
}
pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
unsafe {
let ptr = bytes.as_ptr() as *c_char;
return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
}
}
pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
unsafe {
llvm::LLVMGetParam(fndecl, param as c_uint)
}
}
pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
-> ValueRef {
unsafe {
let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
debug!("const_get_elt(v={}, us={:?}, r={})",
cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
return r;
}
}
pub fn is_const(v: ValueRef) -> bool {
unsafe {
llvm::LLVMIsConstant(v) == True
}
}
pub fn const_to_int(v: ValueRef) -> c_longlong {
unsafe {
llvm::LLVMConstIntGetSExtValue(v)
}
}
pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
unsafe {
llvm::LLVMConstIntGetZExtValue(v)
}
}
pub fn is_undef(val: ValueRef) -> bool {
unsafe {
llvm::LLVMIsUndef(val)!= False
}
}
pub fn is_null(val: ValueRef) -> bool {
unsafe {
llvm::LLVMIsNull(val)!= False
}
}
// Used to identify cached monomorphized functions and vtables
#[deriving(Eq, TotalEq, Hash)]
pub enum mono_param_id {
mono_precise(ty::t, Option<@Vec<mono_id> >),
mono_any,
mono_repr(uint /* size */,
uint /* align */,
MonoDataClass,
datum::RvalueMode),
}
#[deriving(Eq, TotalEq, Hash)]
pub enum MonoDataClass {
MonoBits, // Anything not treated differently from arbitrary integer data
MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
// FIXME(#3547)---scalars and floats are
// treated differently in most ABIs. But we
// should be doing something more detailed
// here.
MonoFloat
}
pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
match ty::get(t).sty {
ty::ty_float(_) => MonoFloat,
ty::ty_rptr(..) | ty::ty_uniq(..) | ty::ty_box(..) |
ty::ty_str(ty::vstore_uniq) | ty::ty_vec(_, ty::vstore_uniq) |
ty::ty_bare_fn(..) => MonoNonNull,
// Is that everything? Would closures or slices qualify?
_ => MonoBits
}
}
#[deriving(Eq, TotalEq, Hash)]
pub struct mono_id_ {
def: ast::DefId,
params: Vec<mono_param_id> }
pub type mono_id = @mono_id_;
pub fn umax(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
return build::Select(cx, cond, b, a);
}
pub fn umin(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
return build::Select(cx, cond, a, b);
}
pub fn align_to(cx: &Block, off: ValueRef, align: ValueRef) -> ValueRef {
let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
let bumped = build::Add(cx, off, mask);
return build::And(cx, bumped, build::Not(cx, mask));
}
pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
match bcx.fcx.param_substs {
Some(substs) => {
ty::subst_tps(bcx.tcx(), substs.tys.as_slice(), substs.self_ty, t)
}
_ => {
assert!(!ty::type_has_params(t));
assert!(!ty::type_has_self(t));
t
}
}
}
pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
let tcx = bcx.tcx();
let t = ty::node_id_to_type(tcx, id);
monomorphize_type(bcx, t)
}
pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t
|
{
node_id_type(bcx, ex.id)
}
|
identifier_body
|
|
common.rs
|
dependency; this causes the rust driver
* to locate an extern crate, scan its compilation metadata, and emit extern
* declarations for any symbols used by the declaring crate.
*
* A "foreign" is an extern that references C (or other non-rust ABI) code.
* There is no metadata to scan for extern references so in these cases either
* a header-digester like bindgen, or manual function prototypes, have to
* serve as declarators. So these are usually given explicitly as prototype
* declarations, in rust code, with ABI attributes on them noting which ABI to
* link via.
*
* An "upcall" is a foreign call generated by the compiler (not corresponding
* to any user-written call in the code) into the runtime library, to perform
* some helper task such as bringing a task to life, allocating memory, etc.
*
*/
pub struct NodeInfo {
id: ast::NodeId,
span: Span,
}
pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
NodeInfo { id: expr.id, span: expr.span }
}
pub struct Stats {
n_static_tydescs: Cell<uint>,
n_glues_created: Cell<uint>,
n_null_glues: Cell<uint>,
n_real_glues: Cell<uint>,
n_fns: Cell<uint>,
n_monos: Cell<uint>,
n_inlines: Cell<uint>,
n_closures: Cell<uint>,
n_llvm_insns: Cell<uint>,
llvm_insns: RefCell<HashMap<~str, uint>>,
// (ident, time-in-ms, llvm-instructions)
fn_stats: RefCell<Vec<(~str, uint, uint)> >,
}
pub struct BuilderRef_res {
b: BuilderRef,
}
impl Drop for BuilderRef_res {
fn drop(&mut self) {
unsafe {
llvm::LLVMDisposeBuilder(self.b);
}
}
}
pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
BuilderRef_res {
b: b
}
}
pub type ExternMap = HashMap<~str, ValueRef>;
// Here `self_ty` is the real type of the self parameter to this method. It
// will only be set in the case of default methods.
pub struct param_substs {
tys: Vec<ty::t>,
self_ty: Option<ty::t>,
vtables: Option<typeck::vtable_res>,
self_vtables: Option<typeck::vtable_param_res>
}
impl param_substs {
pub fn validate(&self) {
for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
}
}
fn param_substs_to_str(this: ¶m_substs, tcx: &ty::ctxt) -> ~str {
format!("param_substs \\{tys:{}, vtables:{}\\}",
this.tys.repr(tcx),
this.vtables.repr(tcx))
}
impl Repr for param_substs {
fn repr(&self, tcx: &ty::ctxt) -> ~str {
param_substs_to_str(self, tcx)
}
}
// work around bizarre resolve errors
pub type RvalueDatum = datum::Datum<datum::Rvalue>;
pub type LvalueDatum = datum::Datum<datum::Lvalue>;
// Function context. Every LLVM function we create will have one of
// these.
pub struct FunctionContext<'a> {
// The ValueRef returned from a call to llvm::LLVMAddFunction; the
// address of the first instruction in the sequence of
// instructions for this function that will go in the.text
// section of the executable we're generating.
llfn: ValueRef,
// The environment argument in a closure.
llenv: Option<ValueRef>,
// The place to store the return value. If the return type is immediate,
// this is an alloca in the function. Otherwise, it's the hidden first
// parameter to the function. After function construction, this should
// always be Some.
llretptr: Cell<Option<ValueRef>>,
entry_bcx: RefCell<Option<&'a Block<'a>>>,
// These elements: "hoisted basic blocks" containing
// administrative activities that have to happen in only one place in
// the function, due to LLVM's quirks.
// A marker for the place where we want to insert the function's static
// allocas, so that LLVM will coalesce them into a single alloca call.
alloca_insert_pt: Cell<Option<ValueRef>>,
llreturn: Cell<Option<BasicBlockRef>>,
// The a value alloca'd for calls to upcalls.rust_personality. Used when
// outputting the resume instruction.
personality: Cell<Option<ValueRef>>,
// True if the caller expects this fn to use the out pointer to
// return. Either way, your code should write into llretptr, but if
// this value is false, llretptr will be a local alloca.
caller_expects_out_pointer: bool,
// Maps arguments to allocas created for them in llallocas.
llargs: RefCell<NodeMap<LvalueDatum>>,
// Maps the def_ids for local variables to the allocas created for
// them in llallocas.
lllocals: RefCell<NodeMap<LvalueDatum>>,
// Same as above, but for closure upvars
llupvars: RefCell<NodeMap<ValueRef>>,
// The NodeId of the function, or -1 if it doesn't correspond to
// a user-defined function.
id: ast::NodeId,
// If this function is being monomorphized, this contains the type
// substitutions used.
param_substs: Option<@param_substs>,
// The source span and nesting context where this function comes from, for
// error reporting and symbol generation.
span: Option<Span>,
// The arena that blocks are allocated from.
block_arena: &'a TypedArena<Block<'a>>,
// This function's enclosing crate context.
ccx: &'a CrateContext,
// Used and maintained by the debuginfo module.
debug_context: debuginfo::FunctionDebugContext,
// Cleanup scopes.
scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
}
impl<'a> FunctionContext<'a> {
pub fn arg_pos(&self, arg: uint) -> uint {
let arg = self.env_arg_pos() + arg;
if self.llenv.is_some() {
arg + 1
} else {
arg
}
}
pub fn out_arg_pos(&self) -> uint {
assert!(self.caller_expects_out_pointer);
0u
}
pub fn env_arg_pos(&self) -> uint {
if self.caller_expects_out_pointer {
1u
} else {
0u
}
}
pub fn cleanup(&self) {
unsafe {
llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
.get()
.unwrap());
}
// Remove the cycle between fcx and bcx, so memory can be freed
self.entry_bcx.set(None);
}
pub fn get_llreturn(&self) -> BasicBlockRef {
if self.llreturn.get().is_none() {
self.llreturn.set(Some(unsafe {
"return".with_c_str(|buf| {
llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx, self.llfn, buf)
})
}))
}
self.llreturn.get().unwrap()
}
pub fn new_block(&'a self,
is_lpad: bool,
name: &str,
opt_node_id: Option<ast::NodeId>)
-> &'a Block<'a> {
unsafe {
let llbb = name.with_c_str(|buf| {
llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
self.llfn,
buf)
});
Block::new(llbb, is_lpad, opt_node_id, self)
}
}
pub fn new_id_block(&'a self,
name: &str,
node_id: ast::NodeId)
-> &'a Block<'a> {
self.new_block(false, name, Some(node_id))
}
pub fn new_temp_block(&'a self,
name: &str)
-> &'a Block<'a> {
self.new_block(false, name, None)
}
pub fn join_blocks(&'a self,
id: ast::NodeId,
in_cxs: &[&'a Block<'a>])
-> &'a Block<'a> {
let out = self.new_id_block("join", id);
let mut reachable = false;
for bcx in in_cxs.iter() {
if!bcx.unreachable.get() {
build::Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
build::Unreachable(out);
}
return out;
}
}
// Heap selectors. Indicate which heap something should go on.
#[deriving(Eq)]
pub enum heap {
heap_managed,
heap_exchange,
heap_exchange_closure
}
// Basic block context. We create a block context for each basic block
// (single-entry, single-exit sequence of instructions) we generate from Rust
// code. Each basic block we generate is attached to a function, typically
// with many basic blocks per function. All the basic blocks attached to a
// function are organized as a directed graph.
pub struct Block<'a> {
// The BasicBlockRef returned from a call to
// llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
// block to the function pointed to by llfn. We insert
// instructions into that block by way of this block context.
// The block pointing to this one in the function's digraph.
llbb: BasicBlockRef,
terminated: Cell<bool>,
unreachable: Cell<bool>,
// Is this block part of a landing pad?
is_lpad: bool,
// AST node-id associated with this block, if any. Used for
// debugging purposes only.
opt_node_id: Option<ast::NodeId>,
// The function context for the function to which this block is
// attached.
fcx: &'a FunctionContext<'a>,
}
impl<'a> Block<'a> {
pub fn new<'a>(
llbb: BasicBlockRef,
is_lpad: bool,
opt_node_id: Option<ast::NodeId>,
fcx: &'a FunctionContext<'a>)
-> &'a Block<'a> {
fcx.block_arena.alloc(Block {
llbb: llbb,
terminated: Cell::new(false),
unreachable: Cell::new(false),
is_lpad: is_lpad,
opt_node_id: opt_node_id,
fcx: fcx
})
}
pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
pub fn tcx(&self) -> &'a ty::ctxt {
&self.fcx.ccx.tcx
}
pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
pub fn ident(&self, ident: Ident) -> ~str {
token::get_ident(ident).get().to_str()
}
pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
self.tcx().map.node_to_str(id)
}
pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
e.repr(self.tcx())
}
pub fn
|
(&self, e: &ast::Expr) -> bool {
ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
}
pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
}
pub fn def(&self, nid: ast::NodeId) -> ast::Def {
match self.tcx().def_map.borrow().find(&nid) {
Some(&v) => v,
None => {
self.tcx().sess.bug(format!(
"no def associated with node id {:?}", nid));
}
}
}
pub fn val_to_str(&self, val: ValueRef) -> ~str {
self.ccx().tn.val_to_str(val)
}
pub fn llty_str(&self, ty: Type) -> ~str {
self.ccx().tn.type_to_str(ty)
}
pub fn ty_to_str(&self, t: ty::t) -> ~str {
t.repr(self.tcx())
}
pub fn to_str(&self) -> ~str {
let blk: *Block = self;
format!("[block {}]", blk)
}
}
pub struct Result<'a> {
bcx: &'a Block<'a>,
val: ValueRef
}
pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
Result {
bcx: bcx,
val: val,
}
}
impl<'a> Result<'a> {
pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
*bcx = self.bcx;
return self.val;
}
}
pub fn val_ty(v: ValueRef) -> Type {
unsafe {
Type::from_ref(llvm::LLVMTypeOf(v))
}
}
// LLVM constant constructors.
pub fn C_null(t: Type) -> ValueRef {
unsafe {
llvm::LLVMConstNull(t.to_ref())
}
}
pub fn C_undef(t: Type) -> ValueRef {
unsafe {
llvm::LLVMGetUndef(t.to_ref())
}
}
pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
unsafe {
llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
}
}
pub fn C_floating(s: &str, t: Type) -> ValueRef {
unsafe {
s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
}
}
pub fn C_nil(ccx: &CrateContext) -> ValueRef {
C_struct(ccx, [], false)
}
pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
C_integral(Type::bool(ccx), val as u64, false)
}
pub fn C_i1(ccx: &CrateContext, val: bool) -> ValueRef {
C_integral(Type::i1(ccx), val as u64, false)
}
pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
C_integral(Type::i32(ccx), i as u64, true)
}
pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
C_integral(Type::i64(ccx), i as u64, true)
}
pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
C_integral(Type::i64(ccx), i, false)
}
pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
C_integral(ccx.int_type, i as u64, true)
}
pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
C_integral(ccx.int_type, i as u64, false)
}
pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
C_integral(Type::i8(ccx), i as u64, false)
}
// This is a 'c-like' raw string, which differs from
// our boxed-and-length-annotated strings.
pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef {
unsafe {
match cx.const_cstr_cache.borrow().find(&s) {
Some(&llval) => return llval,
None => ()
}
let sc = llvm::LLVMConstStringInContext(cx.llcx,
s.get().as_ptr() as *c_char,
s.get().len() as c_uint,
False);
let gsym = token::gensym("str");
let g = format!("str{}", gsym).with_c_str(|buf| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
});
llvm::LLVMSetInitializer(g, sc);
llvm::LLVMSetGlobalConstant(g, True);
lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
cx.const_cstr_cache.borrow_mut().insert(s, g);
g
}
}
// NB: Do not use `do_spill_noroot` to make this into a constant string, or
// you will be kicked off fast isel. See issue #4352 for an example of this.
pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
unsafe {
let len = s.get().len();
let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p(cx).to_ref());
C_struct(cx, [cs, C_uint(cx, len)], false)
}
}
pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
unsafe {
let len = data.len();
let lldata = C_bytes(cx, data);
let gsym = token::gensym("binary");
let g = format!("binary{}", gsym).with_c_str(|buf| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
});
llvm::LLVMSetInitializer(g, lldata);
llvm::LLVMSetGlobalConstant(g, True);
lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
C_struct(cx, [cs, C_uint(cx, len)], false)
}
}
pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
unsafe {
llvm::LLVMConstStructInContext(ccx.llcx,
elts.as_ptr(), elts.len() as c_uint,
packed as Bool)
}
}
pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
unsafe {
llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
}
}
pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
unsafe {
return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
}
}
pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
unsafe {
let ptr = bytes.as_ptr() as *c_char;
return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
}
}
pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
unsafe {
llvm::LLVMGetParam(fndecl, param as c_uint)
}
}
pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
-> ValueRef {
unsafe {
let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
debug!("const_get_elt(v={}, us={:?}, r={})",
cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
return r;
}
}
pub fn is_const(v: ValueRef) -> bool {
unsafe {
llvm::LLVMIsConstant(v) == True
}
}
pub fn const_to_int(v: ValueRef) -> c_longlong {
unsafe {
llvm::LLVMConstIntGetSExtValue(v)
}
}
pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
unsafe {
llvm::LLVMConstIntGetZExtValue(v)
}
}
pub fn is_undef(val: ValueRef) -> bool {
unsafe {
llvm::LLVMIsUndef(val)!= False
}
}
pub fn is_null(val: ValueRef) -> bool {
unsafe {
llvm::LLVMIsNull(val)!= False
}
}
// Used to identify cached monomorphized functions and vtables
#[deriving(Eq, TotalEq, Hash)]
pub enum mono_param_id {
mono_precise(ty::t, Option<@Vec<mono_id> >),
mono_any,
mono_repr(uint /* size */,
uint /* align */,
MonoDataClass,
datum::RvalueMode),
}
#[deriving(Eq, TotalEq, Hash)]
pub enum MonoDataClass {
MonoBits, // Anything not treated differently from arbitrary integer data
MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
// FIXME(#3547)---scalars and floats are
// treated differently in most ABIs. But we
// should be doing something more detailed
// here.
MonoFloat
}
pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
match ty::get(t).sty {
ty::ty_float(_) => MonoFloat,
ty::ty_rptr(..) | ty::ty_uniq(..) | ty::ty_box(..) |
ty::ty_str(ty::vstore_uniq) | ty::ty_vec(_, ty::vstore_uniq) |
ty::ty_bare_fn(..) => MonoNonNull,
// Is that everything? Would closures or slices qualify?
_ => MonoBits
}
}
#[deriving(Eq, TotalEq, Hash)]
pub struct mono_id_ {
def: ast::DefId,
params: Vec<mono_param_id> }
pub type mono_id = @mono_id_;
pub fn umax(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
|
expr_is_lval
|
identifier_name
|
remutex.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.
#![unstable(feature = "reentrant_mutex", reason = "new API",
issue = "27738")]
use prelude::v1::*;
use fmt;
use marker;
use ops::Deref;
use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
use sys::mutex as sys;
/// A re-entrant mutual exclusion
///
/// This mutex will block *other* threads waiting for the lock to become
/// available. The thread which has already locked the mutex can lock it
/// multiple times without blocking, preventing a common source of deadlocks.
pub struct ReentrantMutex<T> {
inner: Box<sys::ReentrantMutex>,
poison: poison::Flag,
data: T,
}
unsafe impl<T: Send> Send for ReentrantMutex<T> {}
unsafe impl<T: Send> Sync for ReentrantMutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// Deref implementation.
///
/// # Mutability
///
/// Unlike `MutexGuard`, `ReentrantMutexGuard` does not implement `DerefMut`,
/// because implementation of the trait would violate Rust’s reference aliasing
/// rules. Use interior mutability (usually `RefCell`) in order to mutate the
/// guarded data.
#[must_use]
pub struct ReentrantMutexGuard<'a, T: 'a> {
// funny underscores due to how Deref currently works (it disregards field
// privacy).
__lock: &'a ReentrantMutex<T>,
__poison: poison::Guard,
}
impl<'a, T>!marker::Send for ReentrantMutexGuard<'a, T> {}
impl<T> ReentrantMutex<T> {
/// Creates a new reentrant mutex in an unlocked state.
pub fn new(t: T) -> ReentrantMutex<T> {
unsafe {
let mut mutex = ReentrantMutex {
inner: box sys::ReentrantMutex::uninitialized(),
poison: poison::Flag::new(),
data: t,
};
mutex.inner.init();
mutex
}
}
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the caller until it is available to acquire the mutex.
/// Upon returning, the thread is the only thread with the mutex held. When the thread
/// calling this method already holds the lock, the call shall succeed without
/// blocking.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn lock(&self) -> LockResult<ReentrantMutexGuard<T>> {
unsafe { self.inner.lock() }
ReentrantMutexGuard::new(&self)
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then `Err` is returned.
/// Otherwise, an RAII guard is returned.
///
/// This function does not block.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn tr
|
self) -> TryLockResult<ReentrantMutexGuard<T>> {
if unsafe { self.inner.try_lock() } {
Ok(try!(ReentrantMutexGuard::new(&self)))
} else {
Err(TryLockError::WouldBlock)
}
}
}
impl<T> Drop for ReentrantMutex<T> {
fn drop(&mut self) {
// This is actually safe b/c we know that there is no further usage of
// this mutex (it's up to the user to arrange for a mutex to get
// dropped, that's not our job)
unsafe { self.inner.destroy() }
}
}
impl<T: fmt::Debug +'static> fmt::Debug for ReentrantMutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
Ok(guard) => write!(f, "ReentrantMutex {{ data: {:?} }}", &*guard),
Err(TryLockError::Poisoned(err)) => {
write!(f, "ReentrantMutex {{ data: Poisoned({:?}) }}", &**err.get_ref())
},
Err(TryLockError::WouldBlock) => write!(f, "ReentrantMutex {{ <locked> }}")
}
}
}
impl<'mutex, T> ReentrantMutexGuard<'mutex, T> {
fn new(lock: &'mutex ReentrantMutex<T>)
-> LockResult<ReentrantMutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| {
ReentrantMutexGuard {
__lock: lock,
__poison: guard,
}
})
}
}
impl<'mutex, T> Deref for ReentrantMutexGuard<'mutex, T> {
type Target = T;
fn deref(&self) -> &T {
&self.__lock.data
}
}
impl<'a, T> Drop for ReentrantMutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.__lock.poison.done(&self.__poison);
self.__lock.inner.unlock();
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
use cell::RefCell;
use sync::Arc;
use boxed;
use thread;
#[test]
fn smoke() {
let m = ReentrantMutex::new(());
{
let a = m.lock().unwrap();
{
let b = m.lock().unwrap();
{
let c = m.lock().unwrap();
assert_eq!(*c, ());
}
assert_eq!(*b, ());
}
assert_eq!(*a, ());
}
}
#[test]
fn is_mutex() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let m2 = m.clone();
let lock = m.lock().unwrap();
let child = thread::spawn(move || {
let lock = m2.lock().unwrap();
assert_eq!(*lock.borrow(), 4950);
});
for i in 0..100 {
let lock = m.lock().unwrap();
*lock.borrow_mut() += i;
}
drop(lock);
child.join().unwrap();
}
#[test]
fn trylock_works() {
let m = Arc::new(ReentrantMutex::new(()));
let m2 = m.clone();
let lock = m.try_lock().unwrap();
let lock2 = m.try_lock().unwrap();
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join().unwrap();
let lock3 = m.try_lock().unwrap();
}
pub struct Answer<'a>(pub ReentrantMutexGuard<'a, RefCell<u32>>);
impl<'a> Drop for Answer<'a> {
fn drop(&mut self) {
*self.0.borrow_mut() = 42;
}
}
#[test]
fn poison_works() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let mc = m.clone();
let result = thread::spawn(move ||{
let lock = mc.lock().unwrap();
*lock.borrow_mut() = 1;
let lock2 = mc.lock().unwrap();
*lock.borrow_mut() = 2;
let answer = Answer(lock2);
panic!("What the answer to my lifetimes dilemma is?");
drop(answer);
}).join();
assert!(result.is_err());
let r = m.lock().err().unwrap().into_inner();
assert_eq!(*r.borrow(), 42);
}
}
|
y_lock(&
|
identifier_name
|
remutex.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.
#![unstable(feature = "reentrant_mutex", reason = "new API",
issue = "27738")]
use prelude::v1::*;
use fmt;
use marker;
use ops::Deref;
use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
use sys::mutex as sys;
/// A re-entrant mutual exclusion
///
/// This mutex will block *other* threads waiting for the lock to become
/// available. The thread which has already locked the mutex can lock it
/// multiple times without blocking, preventing a common source of deadlocks.
pub struct ReentrantMutex<T> {
inner: Box<sys::ReentrantMutex>,
poison: poison::Flag,
data: T,
}
unsafe impl<T: Send> Send for ReentrantMutex<T> {}
unsafe impl<T: Send> Sync for ReentrantMutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// Deref implementation.
///
/// # Mutability
///
/// Unlike `MutexGuard`, `ReentrantMutexGuard` does not implement `DerefMut`,
/// because implementation of the trait would violate Rust’s reference aliasing
/// rules. Use interior mutability (usually `RefCell`) in order to mutate the
/// guarded data.
#[must_use]
pub struct ReentrantMutexGuard<'a, T: 'a> {
// funny underscores due to how Deref currently works (it disregards field
// privacy).
__lock: &'a ReentrantMutex<T>,
__poison: poison::Guard,
}
impl<'a, T>!marker::Send for ReentrantMutexGuard<'a, T> {}
impl<T> ReentrantMutex<T> {
/// Creates a new reentrant mutex in an unlocked state.
pub fn new(t: T) -> ReentrantMutex<T> {
unsafe {
let mut mutex = ReentrantMutex {
inner: box sys::ReentrantMutex::uninitialized(),
poison: poison::Flag::new(),
data: t,
};
mutex.inner.init();
mutex
}
}
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the caller until it is available to acquire the mutex.
/// Upon returning, the thread is the only thread with the mutex held. When the thread
/// calling this method already holds the lock, the call shall succeed without
/// blocking.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn lock(&self) -> LockResult<ReentrantMutexGuard<T>> {
unsafe { self.inner.lock() }
ReentrantMutexGuard::new(&self)
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then `Err` is returned.
/// Otherwise, an RAII guard is returned.
///
/// This function does not block.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
if unsafe { self.inner.try_lock() } {
|
lse {
Err(TryLockError::WouldBlock)
}
}
}
impl<T> Drop for ReentrantMutex<T> {
fn drop(&mut self) {
// This is actually safe b/c we know that there is no further usage of
// this mutex (it's up to the user to arrange for a mutex to get
// dropped, that's not our job)
unsafe { self.inner.destroy() }
}
}
impl<T: fmt::Debug +'static> fmt::Debug for ReentrantMutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
Ok(guard) => write!(f, "ReentrantMutex {{ data: {:?} }}", &*guard),
Err(TryLockError::Poisoned(err)) => {
write!(f, "ReentrantMutex {{ data: Poisoned({:?}) }}", &**err.get_ref())
},
Err(TryLockError::WouldBlock) => write!(f, "ReentrantMutex {{ <locked> }}")
}
}
}
impl<'mutex, T> ReentrantMutexGuard<'mutex, T> {
fn new(lock: &'mutex ReentrantMutex<T>)
-> LockResult<ReentrantMutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| {
ReentrantMutexGuard {
__lock: lock,
__poison: guard,
}
})
}
}
impl<'mutex, T> Deref for ReentrantMutexGuard<'mutex, T> {
type Target = T;
fn deref(&self) -> &T {
&self.__lock.data
}
}
impl<'a, T> Drop for ReentrantMutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.__lock.poison.done(&self.__poison);
self.__lock.inner.unlock();
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
use cell::RefCell;
use sync::Arc;
use boxed;
use thread;
#[test]
fn smoke() {
let m = ReentrantMutex::new(());
{
let a = m.lock().unwrap();
{
let b = m.lock().unwrap();
{
let c = m.lock().unwrap();
assert_eq!(*c, ());
}
assert_eq!(*b, ());
}
assert_eq!(*a, ());
}
}
#[test]
fn is_mutex() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let m2 = m.clone();
let lock = m.lock().unwrap();
let child = thread::spawn(move || {
let lock = m2.lock().unwrap();
assert_eq!(*lock.borrow(), 4950);
});
for i in 0..100 {
let lock = m.lock().unwrap();
*lock.borrow_mut() += i;
}
drop(lock);
child.join().unwrap();
}
#[test]
fn trylock_works() {
let m = Arc::new(ReentrantMutex::new(()));
let m2 = m.clone();
let lock = m.try_lock().unwrap();
let lock2 = m.try_lock().unwrap();
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join().unwrap();
let lock3 = m.try_lock().unwrap();
}
pub struct Answer<'a>(pub ReentrantMutexGuard<'a, RefCell<u32>>);
impl<'a> Drop for Answer<'a> {
fn drop(&mut self) {
*self.0.borrow_mut() = 42;
}
}
#[test]
fn poison_works() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let mc = m.clone();
let result = thread::spawn(move ||{
let lock = mc.lock().unwrap();
*lock.borrow_mut() = 1;
let lock2 = mc.lock().unwrap();
*lock.borrow_mut() = 2;
let answer = Answer(lock2);
panic!("What the answer to my lifetimes dilemma is?");
drop(answer);
}).join();
assert!(result.is_err());
let r = m.lock().err().unwrap().into_inner();
assert_eq!(*r.borrow(), 42);
}
}
|
Ok(try!(ReentrantMutexGuard::new(&self)))
} e
|
conditional_block
|
remutex.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.
#![unstable(feature = "reentrant_mutex", reason = "new API",
issue = "27738")]
use prelude::v1::*;
use fmt;
use marker;
use ops::Deref;
use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
use sys::mutex as sys;
/// A re-entrant mutual exclusion
///
/// This mutex will block *other* threads waiting for the lock to become
/// available. The thread which has already locked the mutex can lock it
/// multiple times without blocking, preventing a common source of deadlocks.
pub struct ReentrantMutex<T> {
inner: Box<sys::ReentrantMutex>,
poison: poison::Flag,
data: T,
}
unsafe impl<T: Send> Send for ReentrantMutex<T> {}
unsafe impl<T: Send> Sync for ReentrantMutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// Deref implementation.
///
/// # Mutability
///
/// Unlike `MutexGuard`, `ReentrantMutexGuard` does not implement `DerefMut`,
/// because implementation of the trait would violate Rust’s reference aliasing
/// rules. Use interior mutability (usually `RefCell`) in order to mutate the
/// guarded data.
#[must_use]
pub struct ReentrantMutexGuard<'a, T: 'a> {
// funny underscores due to how Deref currently works (it disregards field
// privacy).
__lock: &'a ReentrantMutex<T>,
__poison: poison::Guard,
}
impl<'a, T>!marker::Send for ReentrantMutexGuard<'a, T> {}
impl<T> ReentrantMutex<T> {
/// Creates a new reentrant mutex in an unlocked state.
pub fn new(t: T) -> ReentrantMutex<T> {
unsafe {
let mut mutex = ReentrantMutex {
inner: box sys::ReentrantMutex::uninitialized(),
poison: poison::Flag::new(),
data: t,
};
mutex.inner.init();
mutex
}
}
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the caller until it is available to acquire the mutex.
/// Upon returning, the thread is the only thread with the mutex held. When the thread
/// calling this method already holds the lock, the call shall succeed without
/// blocking.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn lock(&self) -> LockResult<ReentrantMutexGuard<T>> {
unsafe { self.inner.lock() }
ReentrantMutexGuard::new(&self)
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then `Err` is returned.
/// Otherwise, an RAII guard is returned.
///
/// This function does not block.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
if unsafe { self.inner.try_lock() } {
Ok(try!(ReentrantMutexGuard::new(&self)))
} else {
Err(TryLockError::WouldBlock)
}
}
}
impl<T> Drop for ReentrantMutex<T> {
fn drop(&mut self) {
// This is actually safe b/c we know that there is no further usage of
// this mutex (it's up to the user to arrange for a mutex to get
// dropped, that's not our job)
unsafe { self.inner.destroy() }
}
}
impl<T: fmt::Debug +'static> fmt::Debug for ReentrantMutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
Ok(guard) => write!(f, "ReentrantMutex {{ data: {:?} }}", &*guard),
Err(TryLockError::Poisoned(err)) => {
write!(f, "ReentrantMutex {{ data: Poisoned({:?}) }}", &**err.get_ref())
},
Err(TryLockError::WouldBlock) => write!(f, "ReentrantMutex {{ <locked> }}")
}
}
}
impl<'mutex, T> ReentrantMutexGuard<'mutex, T> {
fn new(lock: &'mutex ReentrantMutex<T>)
-> LockResult<ReentrantMutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| {
ReentrantMutexGuard {
__lock: lock,
__poison: guard,
}
})
}
}
impl<'mutex, T> Deref for ReentrantMutexGuard<'mutex, T> {
type Target = T;
fn deref(&self) -> &T {
&self.__lock.data
}
}
impl<'a, T> Drop for ReentrantMutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.__lock.poison.done(&self.__poison);
self.__lock.inner.unlock();
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
use cell::RefCell;
use sync::Arc;
use boxed;
use thread;
#[test]
fn smoke() {
let m = ReentrantMutex::new(());
{
let a = m.lock().unwrap();
|
{
let c = m.lock().unwrap();
assert_eq!(*c, ());
}
assert_eq!(*b, ());
}
assert_eq!(*a, ());
}
}
#[test]
fn is_mutex() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let m2 = m.clone();
let lock = m.lock().unwrap();
let child = thread::spawn(move || {
let lock = m2.lock().unwrap();
assert_eq!(*lock.borrow(), 4950);
});
for i in 0..100 {
let lock = m.lock().unwrap();
*lock.borrow_mut() += i;
}
drop(lock);
child.join().unwrap();
}
#[test]
fn trylock_works() {
let m = Arc::new(ReentrantMutex::new(()));
let m2 = m.clone();
let lock = m.try_lock().unwrap();
let lock2 = m.try_lock().unwrap();
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join().unwrap();
let lock3 = m.try_lock().unwrap();
}
pub struct Answer<'a>(pub ReentrantMutexGuard<'a, RefCell<u32>>);
impl<'a> Drop for Answer<'a> {
fn drop(&mut self) {
*self.0.borrow_mut() = 42;
}
}
#[test]
fn poison_works() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let mc = m.clone();
let result = thread::spawn(move ||{
let lock = mc.lock().unwrap();
*lock.borrow_mut() = 1;
let lock2 = mc.lock().unwrap();
*lock.borrow_mut() = 2;
let answer = Answer(lock2);
panic!("What the answer to my lifetimes dilemma is?");
drop(answer);
}).join();
assert!(result.is_err());
let r = m.lock().err().unwrap().into_inner();
assert_eq!(*r.borrow(), 42);
}
}
|
{
let b = m.lock().unwrap();
|
random_line_split
|
remutex.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.
#![unstable(feature = "reentrant_mutex", reason = "new API",
issue = "27738")]
use prelude::v1::*;
use fmt;
use marker;
use ops::Deref;
use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
use sys::mutex as sys;
/// A re-entrant mutual exclusion
///
/// This mutex will block *other* threads waiting for the lock to become
/// available. The thread which has already locked the mutex can lock it
/// multiple times without blocking, preventing a common source of deadlocks.
pub struct ReentrantMutex<T> {
inner: Box<sys::ReentrantMutex>,
poison: poison::Flag,
data: T,
}
unsafe impl<T: Send> Send for ReentrantMutex<T> {}
unsafe impl<T: Send> Sync for ReentrantMutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// Deref implementation.
///
/// # Mutability
///
/// Unlike `MutexGuard`, `ReentrantMutexGuard` does not implement `DerefMut`,
/// because implementation of the trait would violate Rust’s reference aliasing
/// rules. Use interior mutability (usually `RefCell`) in order to mutate the
/// guarded data.
#[must_use]
pub struct ReentrantMutexGuard<'a, T: 'a> {
// funny underscores due to how Deref currently works (it disregards field
// privacy).
__lock: &'a ReentrantMutex<T>,
__poison: poison::Guard,
}
impl<'a, T>!marker::Send for ReentrantMutexGuard<'a, T> {}
impl<T> ReentrantMutex<T> {
/// Creates a new reentrant mutex in an unlocked state.
pub fn new(t: T) -> ReentrantMutex<T> {
unsafe {
let mut mutex = ReentrantMutex {
inner: box sys::ReentrantMutex::uninitialized(),
poison: poison::Flag::new(),
data: t,
};
mutex.inner.init();
mutex
}
}
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the caller until it is available to acquire the mutex.
/// Upon returning, the thread is the only thread with the mutex held. When the thread
/// calling this method already holds the lock, the call shall succeed without
/// blocking.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn lock(&self) -> LockResult<ReentrantMutexGuard<T>> {
unsafe { self.inner.lock() }
ReentrantMutexGuard::new(&self)
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then `Err` is returned.
/// Otherwise, an RAII guard is returned.
///
/// This function does not block.
///
/// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return failure if the mutex would otherwise be
/// acquired.
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
if unsafe { self.inner.try_lock() } {
Ok(try!(ReentrantMutexGuard::new(&self)))
} else {
Err(TryLockError::WouldBlock)
}
}
}
impl<T> Drop for ReentrantMutex<T> {
fn drop(&mut self) {
// This is actually safe b/c we know that there is no further usage of
// this mutex (it's up to the user to arrange for a mutex to get
// dropped, that's not our job)
unsafe { self.inner.destroy() }
}
}
impl<T: fmt::Debug +'static> fmt::Debug for ReentrantMutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
impl<'mutex, T> ReentrantMutexGuard<'mutex, T> {
fn new(lock: &'mutex ReentrantMutex<T>)
-> LockResult<ReentrantMutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| {
ReentrantMutexGuard {
__lock: lock,
__poison: guard,
}
})
}
}
impl<'mutex, T> Deref for ReentrantMutexGuard<'mutex, T> {
type Target = T;
fn deref(&self) -> &T {
&self.__lock.data
}
}
impl<'a, T> Drop for ReentrantMutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.__lock.poison.done(&self.__poison);
self.__lock.inner.unlock();
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
use cell::RefCell;
use sync::Arc;
use boxed;
use thread;
#[test]
fn smoke() {
let m = ReentrantMutex::new(());
{
let a = m.lock().unwrap();
{
let b = m.lock().unwrap();
{
let c = m.lock().unwrap();
assert_eq!(*c, ());
}
assert_eq!(*b, ());
}
assert_eq!(*a, ());
}
}
#[test]
fn is_mutex() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let m2 = m.clone();
let lock = m.lock().unwrap();
let child = thread::spawn(move || {
let lock = m2.lock().unwrap();
assert_eq!(*lock.borrow(), 4950);
});
for i in 0..100 {
let lock = m.lock().unwrap();
*lock.borrow_mut() += i;
}
drop(lock);
child.join().unwrap();
}
#[test]
fn trylock_works() {
let m = Arc::new(ReentrantMutex::new(()));
let m2 = m.clone();
let lock = m.try_lock().unwrap();
let lock2 = m.try_lock().unwrap();
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join().unwrap();
let lock3 = m.try_lock().unwrap();
}
pub struct Answer<'a>(pub ReentrantMutexGuard<'a, RefCell<u32>>);
impl<'a> Drop for Answer<'a> {
fn drop(&mut self) {
*self.0.borrow_mut() = 42;
}
}
#[test]
fn poison_works() {
let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
let mc = m.clone();
let result = thread::spawn(move ||{
let lock = mc.lock().unwrap();
*lock.borrow_mut() = 1;
let lock2 = mc.lock().unwrap();
*lock.borrow_mut() = 2;
let answer = Answer(lock2);
panic!("What the answer to my lifetimes dilemma is?");
drop(answer);
}).join();
assert!(result.is_err());
let r = m.lock().err().unwrap().into_inner();
assert_eq!(*r.borrow(), 42);
}
}
|
match self.try_lock() {
Ok(guard) => write!(f, "ReentrantMutex {{ data: {:?} }}", &*guard),
Err(TryLockError::Poisoned(err)) => {
write!(f, "ReentrantMutex {{ data: Poisoned({:?}) }}", &**err.get_ref())
},
Err(TryLockError::WouldBlock) => write!(f, "ReentrantMutex {{ <locked> }}")
}
}
}
|
identifier_body
|
buffer.rs
|
use std::ffi::c_void;
use std::cell::Cell;
use std::fmt;
use std::ops::Deref;
pub unsafe trait BufferType: ::lv2::core::PortType {
type BufferImpl: PortBuffer +'static;
}
pub unsafe trait PortBuffer {
fn get_ptr(&self) -> *mut c_void;
fn get_size(&self) -> usize;
}
#[derive(Clone, Default)]
pub struct CellBuffer<T: Copy = f32> {
inner: Cell<T>
}
impl<T: Copy> CellBuffer<T> {
#[inline]
pub fn new(value: T) -> Self {
Self { inner: Cell::new(value) }
}
#[inline]
pub fn get(&self) -> T { self.inner.get() }
#[inline]
pub fn set(&self, value: T) {
self.inner.replace(value);
}
}
unsafe impl<T: Copy> PortBuffer for CellBuffer<T> {
#[inline]
fn get_ptr(&self) -> *mut c_void {
self.inner.as_ptr() as _
}
#[inline]
fn get_size(&self) -> usize {
1
}
}
unsafe impl BufferType for ::lv2::core::ports::Control {
type BufferImpl = CellBuffer<f32>;
}
impl<T: Copy + fmt::Debug> fmt::Debug for CellBuffer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self.get(), f)
}
}
#[derive(Clone)]
pub struct VecBuffer<T: Copy = f32> {
inner: Vec<Cell<T>>
}
impl<T: Copy> VecBuffer<T> {
#[inline]
pub fn new(initial_value: T, capacity: usize) -> Self {
Self { inner: vec![Cell::new(initial_value); capacity] }
}
#[inline]
pub fn get(&self) -> &[Cell<T>] {
&*(self.inner)
}
#[inline]
|
dst.set(src)
}
}
}
unsafe impl<T: Copy> PortBuffer for VecBuffer<T> {
#[inline]
fn get_ptr(&self) -> *mut c_void {
self.inner.as_ptr() as _
}
#[inline]
fn get_size(&self) -> usize {
self.inner.len()
}
// type BufferType = SampleDependentBufferType<T>;
}
impl<T: Copy + fmt::Debug> fmt::Debug for VecBuffer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self.get(), f)
}
}
unsafe impl BufferType for ::lv2::core::ports::Audio {
type BufferImpl = VecBuffer<f32>;
}
unsafe impl BufferType for ::lv2::core::ports::CV {
type BufferImpl = VecBuffer<f32>;
}
impl<T: Copy> Deref for VecBuffer<T> {
type Target = [Cell<T>];
fn deref(&self) -> &[Cell<T>] {
&*self.inner
}
}
|
pub fn set_all<I: IntoIterator<Item=T>>(&self, iter: I) {
for (src, dst) in iter.into_iter().zip(&self.inner) {
|
random_line_split
|
buffer.rs
|
use std::ffi::c_void;
use std::cell::Cell;
use std::fmt;
use std::ops::Deref;
pub unsafe trait BufferType: ::lv2::core::PortType {
type BufferImpl: PortBuffer +'static;
}
pub unsafe trait PortBuffer {
fn get_ptr(&self) -> *mut c_void;
fn get_size(&self) -> usize;
}
#[derive(Clone, Default)]
pub struct CellBuffer<T: Copy = f32> {
inner: Cell<T>
}
impl<T: Copy> CellBuffer<T> {
#[inline]
pub fn new(value: T) -> Self {
Self { inner: Cell::new(value) }
}
#[inline]
pub fn get(&self) -> T { self.inner.get() }
#[inline]
pub fn set(&self, value: T) {
self.inner.replace(value);
}
}
unsafe impl<T: Copy> PortBuffer for CellBuffer<T> {
#[inline]
fn get_ptr(&self) -> *mut c_void {
self.inner.as_ptr() as _
}
#[inline]
fn get_size(&self) -> usize {
1
}
}
unsafe impl BufferType for ::lv2::core::ports::Control {
type BufferImpl = CellBuffer<f32>;
}
impl<T: Copy + fmt::Debug> fmt::Debug for CellBuffer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self.get(), f)
}
}
#[derive(Clone)]
pub struct VecBuffer<T: Copy = f32> {
inner: Vec<Cell<T>>
}
impl<T: Copy> VecBuffer<T> {
#[inline]
pub fn new(initial_value: T, capacity: usize) -> Self {
Self { inner: vec![Cell::new(initial_value); capacity] }
}
#[inline]
pub fn get(&self) -> &[Cell<T>] {
&*(self.inner)
}
#[inline]
pub fn set_all<I: IntoIterator<Item=T>>(&self, iter: I) {
for (src, dst) in iter.into_iter().zip(&self.inner) {
dst.set(src)
}
}
}
unsafe impl<T: Copy> PortBuffer for VecBuffer<T> {
#[inline]
fn get_ptr(&self) -> *mut c_void {
self.inner.as_ptr() as _
}
#[inline]
fn get_size(&self) -> usize
|
// type BufferType = SampleDependentBufferType<T>;
}
impl<T: Copy + fmt::Debug> fmt::Debug for VecBuffer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self.get(), f)
}
}
unsafe impl BufferType for ::lv2::core::ports::Audio {
type BufferImpl = VecBuffer<f32>;
}
unsafe impl BufferType for ::lv2::core::ports::CV {
type BufferImpl = VecBuffer<f32>;
}
impl<T: Copy> Deref for VecBuffer<T> {
type Target = [Cell<T>];
fn deref(&self) -> &[Cell<T>] {
&*self.inner
}
}
|
{
self.inner.len()
}
|
identifier_body
|
buffer.rs
|
use std::ffi::c_void;
use std::cell::Cell;
use std::fmt;
use std::ops::Deref;
pub unsafe trait BufferType: ::lv2::core::PortType {
type BufferImpl: PortBuffer +'static;
}
pub unsafe trait PortBuffer {
fn get_ptr(&self) -> *mut c_void;
fn get_size(&self) -> usize;
}
#[derive(Clone, Default)]
pub struct CellBuffer<T: Copy = f32> {
inner: Cell<T>
}
impl<T: Copy> CellBuffer<T> {
#[inline]
pub fn new(value: T) -> Self {
Self { inner: Cell::new(value) }
}
#[inline]
pub fn get(&self) -> T { self.inner.get() }
#[inline]
pub fn
|
(&self, value: T) {
self.inner.replace(value);
}
}
unsafe impl<T: Copy> PortBuffer for CellBuffer<T> {
#[inline]
fn get_ptr(&self) -> *mut c_void {
self.inner.as_ptr() as _
}
#[inline]
fn get_size(&self) -> usize {
1
}
}
unsafe impl BufferType for ::lv2::core::ports::Control {
type BufferImpl = CellBuffer<f32>;
}
impl<T: Copy + fmt::Debug> fmt::Debug for CellBuffer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self.get(), f)
}
}
#[derive(Clone)]
pub struct VecBuffer<T: Copy = f32> {
inner: Vec<Cell<T>>
}
impl<T: Copy> VecBuffer<T> {
#[inline]
pub fn new(initial_value: T, capacity: usize) -> Self {
Self { inner: vec![Cell::new(initial_value); capacity] }
}
#[inline]
pub fn get(&self) -> &[Cell<T>] {
&*(self.inner)
}
#[inline]
pub fn set_all<I: IntoIterator<Item=T>>(&self, iter: I) {
for (src, dst) in iter.into_iter().zip(&self.inner) {
dst.set(src)
}
}
}
unsafe impl<T: Copy> PortBuffer for VecBuffer<T> {
#[inline]
fn get_ptr(&self) -> *mut c_void {
self.inner.as_ptr() as _
}
#[inline]
fn get_size(&self) -> usize {
self.inner.len()
}
// type BufferType = SampleDependentBufferType<T>;
}
impl<T: Copy + fmt::Debug> fmt::Debug for VecBuffer<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self.get(), f)
}
}
unsafe impl BufferType for ::lv2::core::ports::Audio {
type BufferImpl = VecBuffer<f32>;
}
unsafe impl BufferType for ::lv2::core::ports::CV {
type BufferImpl = VecBuffer<f32>;
}
impl<T: Copy> Deref for VecBuffer<T> {
type Target = [Cell<T>];
fn deref(&self) -> &[Cell<T>] {
&*self.inner
}
}
|
set
|
identifier_name
|
part1.rs
|
// adventofcode - day 9
// part 1
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashSet;
struct Graph {
nodes: Option<Vec<String>>,
matrix: Option<Vec<Vec<i32>>>,
}
impl Graph {
fn new(names: HashSet<&str>) -> Graph {
let mut graph = Graph{nodes: None, matrix: None};
let size = names.len();
graph.nodes = Some(Vec::with_capacity(size));
match graph.nodes {
Some(ref mut nodes) => {
for name in names {
nodes.push(name.to_string());
}
nodes.sort();
},
None => {
panic!("Failed to create graph!");
}
}
graph.matrix = Some(Vec::<Vec<i32>>::with_capacity(size));
match graph.matrix {
Some(ref mut matrix) => {
for ii in 0..size {
matrix.push(Vec::<i32>::with_capacity(size));
for _ in 0..size {
matrix[ii].push(0);
}
}
},
None => {
panic!("Failed to create graph!");
}
}
graph
}
fn size(&self) -> usize {
match self.nodes {
Some(ref nodes) => nodes.len(),
None => 0,
}
}
#[allow(dead_code)]
fn get_node_names(&self) -> Vec<String> {
match self.nodes {
Some(ref nodes) => nodes.clone(),
None => Vec::<String>::new(),
}
}
fn insert_edge(&mut self, src: &String, dest: &String, length: i32) {
let src_idx = match self.nodes {
Some(ref nodes) => match nodes.binary_search(src){
Ok(x) => x,
Err(e) => {
println!("Error: {}", e);
return;
},
},
None => return,
};
let dst_idx = match self.nodes {
Some(ref nodes) => match nodes.binary_search(dest){
Ok(x) => x,
Err(e) => {
println!("Error: {}", e);
return;
},
},
None => return,
};
match self.matrix {
Some(ref mut matrix) => {
matrix[src_idx][dst_idx] = length;
matrix[dst_idx][src_idx] = length;
},
None => return,
}
}
// bruteforce solution
fn calculate_path(&self, visited: Vec<usize>) -> (i32, Vec<usize>){
if visited.len() == self.size() {
return (self.calculate_cost_of_path(&visited), visited);
}
let mut min_cost = std::i32::MAX;
let mut min_path = Vec::new();
for ii in 0..self.size(){
if! visited.contains(&ii){
let mut path = visited.clone();
path.push(ii);
let (cost, path) = self.calculate_path(path);
if cost < min_cost {
min_cost = cost;
min_path = path;
}
}
}
(min_cost, min_path)
}
fn calculate_cost_of_path(&self, path: &Vec<usize>) -> i32 {
let mut locations = path.iter();
let mut from = locations.next().unwrap();
let mut cost = 0i32;
loop {
match locations.next() {
Some(to) => {
cost += self.get_edge_cost(*from, *to);
from = to;
},
None => return cost,
}
}
}
fn get_edge_cost(&self, from: usize, to: usize) -> i32 {
match self.matrix {
Some(ref matrix) => matrix[from][to],
None => 0,
}
}
}
fn main(){
println!("Advent of Code - day 9 | part 1");
// import data
let data = import_data();
let graph = match parse_data(data){
Some(x) => x,
None => panic!("Couldn\'t parse data!"),
};
//println!("Graph has the following nodes ({}):", graph.size());
//for name in graph.get_node_names() {
// println!("{}", name);
//}
let path = Vec::new();
let (cost, path) = graph.calculate_path(path);
println!("Shortest path costs: {}", cost);
for location in path {
println!("{}", location);
}
}
fn parse_data(data: String) -> Option<Graph> {
let mut all_names = HashSet::new();
// first: scan data for names
for line in data.lines(){
let names = line.split(" to ").flat_map(|s| s.split(" = ")).take(2);
for name in names {
all_names.insert(name);
}
}
let mut graph = Graph::new(all_names);
for line in data.lines(){
let info = line.split(" to ")
.flat_map(|s| s.split(" = "))
.map(|s| s.parse::<String>().unwrap())
.collect::<Vec<String>>();
let length = info[2].parse::<i32>().unwrap();
graph.insert_edge(&info[0], &info[1], length);
}
Some(graph)
}
// This function simply imports the data set from a file called input.txt
fn import_data() -> String
|
{
let mut file = match File::open("../../inputs/09.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
// remove trailing \n
data.pop();
data
}
|
identifier_body
|
|
part1.rs
|
// adventofcode - day 9
// part 1
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashSet;
struct Graph {
nodes: Option<Vec<String>>,
matrix: Option<Vec<Vec<i32>>>,
}
impl Graph {
fn new(names: HashSet<&str>) -> Graph {
let mut graph = Graph{nodes: None, matrix: None};
let size = names.len();
graph.nodes = Some(Vec::with_capacity(size));
match graph.nodes {
Some(ref mut nodes) => {
for name in names {
nodes.push(name.to_string());
}
nodes.sort();
},
None => {
panic!("Failed to create graph!");
}
}
graph.matrix = Some(Vec::<Vec<i32>>::with_capacity(size));
match graph.matrix {
Some(ref mut matrix) => {
for ii in 0..size {
matrix.push(Vec::<i32>::with_capacity(size));
for _ in 0..size {
matrix[ii].push(0);
}
}
},
None => {
panic!("Failed to create graph!");
}
}
graph
}
fn size(&self) -> usize {
match self.nodes {
Some(ref nodes) => nodes.len(),
None => 0,
}
}
#[allow(dead_code)]
fn get_node_names(&self) -> Vec<String> {
match self.nodes {
Some(ref nodes) => nodes.clone(),
None => Vec::<String>::new(),
}
}
fn insert_edge(&mut self, src: &String, dest: &String, length: i32) {
let src_idx = match self.nodes {
Some(ref nodes) => match nodes.binary_search(src){
Ok(x) => x,
Err(e) => {
println!("Error: {}", e);
return;
},
},
None => return,
};
let dst_idx = match self.nodes {
Some(ref nodes) => match nodes.binary_search(dest){
Ok(x) => x,
Err(e) => {
println!("Error: {}", e);
return;
},
},
None => return,
};
match self.matrix {
Some(ref mut matrix) => {
matrix[src_idx][dst_idx] = length;
matrix[dst_idx][src_idx] = length;
},
None => return,
}
}
// bruteforce solution
fn calculate_path(&self, visited: Vec<usize>) -> (i32, Vec<usize>){
if visited.len() == self.size() {
return (self.calculate_cost_of_path(&visited), visited);
}
let mut min_cost = std::i32::MAX;
let mut min_path = Vec::new();
for ii in 0..self.size(){
if! visited.contains(&ii){
let mut path = visited.clone();
path.push(ii);
let (cost, path) = self.calculate_path(path);
if cost < min_cost {
min_cost = cost;
min_path = path;
}
}
}
(min_cost, min_path)
}
fn calculate_cost_of_path(&self, path: &Vec<usize>) -> i32 {
let mut locations = path.iter();
let mut from = locations.next().unwrap();
let mut cost = 0i32;
loop {
match locations.next() {
Some(to) => {
cost += self.get_edge_cost(*from, *to);
from = to;
},
None => return cost,
}
}
}
fn get_edge_cost(&self, from: usize, to: usize) -> i32 {
match self.matrix {
Some(ref matrix) => matrix[from][to],
None => 0,
}
}
}
fn main(){
println!("Advent of Code - day 9 | part 1");
// import data
let data = import_data();
let graph = match parse_data(data){
Some(x) => x,
None => panic!("Couldn\'t parse data!"),
};
//println!("Graph has the following nodes ({}):", graph.size());
//for name in graph.get_node_names() {
// println!("{}", name);
//}
let path = Vec::new();
let (cost, path) = graph.calculate_path(path);
println!("Shortest path costs: {}", cost);
for location in path {
println!("{}", location);
}
}
fn parse_data(data: String) -> Option<Graph> {
let mut all_names = HashSet::new();
// first: scan data for names
for line in data.lines(){
let names = line.split(" to ").flat_map(|s| s.split(" = ")).take(2);
for name in names {
all_names.insert(name);
}
}
let mut graph = Graph::new(all_names);
|
.collect::<Vec<String>>();
let length = info[2].parse::<i32>().unwrap();
graph.insert_edge(&info[0], &info[1], length);
}
Some(graph)
}
// This function simply imports the data set from a file called input.txt
fn import_data() -> String {
let mut file = match File::open("../../inputs/09.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
// remove trailing \n
data.pop();
data
}
|
for line in data.lines(){
let info = line.split(" to ")
.flat_map(|s| s.split(" = "))
.map(|s| s.parse::<String>().unwrap())
|
random_line_split
|
part1.rs
|
// adventofcode - day 9
// part 1
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashSet;
struct Graph {
nodes: Option<Vec<String>>,
matrix: Option<Vec<Vec<i32>>>,
}
impl Graph {
fn new(names: HashSet<&str>) -> Graph {
let mut graph = Graph{nodes: None, matrix: None};
let size = names.len();
graph.nodes = Some(Vec::with_capacity(size));
match graph.nodes {
Some(ref mut nodes) => {
for name in names {
nodes.push(name.to_string());
}
nodes.sort();
},
None => {
panic!("Failed to create graph!");
}
}
graph.matrix = Some(Vec::<Vec<i32>>::with_capacity(size));
match graph.matrix {
Some(ref mut matrix) => {
for ii in 0..size {
matrix.push(Vec::<i32>::with_capacity(size));
for _ in 0..size {
matrix[ii].push(0);
}
}
},
None => {
panic!("Failed to create graph!");
}
}
graph
}
fn size(&self) -> usize {
match self.nodes {
Some(ref nodes) => nodes.len(),
None => 0,
}
}
#[allow(dead_code)]
fn get_node_names(&self) -> Vec<String> {
match self.nodes {
Some(ref nodes) => nodes.clone(),
None => Vec::<String>::new(),
}
}
fn insert_edge(&mut self, src: &String, dest: &String, length: i32) {
let src_idx = match self.nodes {
Some(ref nodes) => match nodes.binary_search(src){
Ok(x) => x,
Err(e) => {
println!("Error: {}", e);
return;
},
},
None => return,
};
let dst_idx = match self.nodes {
Some(ref nodes) => match nodes.binary_search(dest){
Ok(x) => x,
Err(e) => {
println!("Error: {}", e);
return;
},
},
None => return,
};
match self.matrix {
Some(ref mut matrix) => {
matrix[src_idx][dst_idx] = length;
matrix[dst_idx][src_idx] = length;
},
None => return,
}
}
// bruteforce solution
fn calculate_path(&self, visited: Vec<usize>) -> (i32, Vec<usize>){
if visited.len() == self.size() {
return (self.calculate_cost_of_path(&visited), visited);
}
let mut min_cost = std::i32::MAX;
let mut min_path = Vec::new();
for ii in 0..self.size(){
if! visited.contains(&ii){
let mut path = visited.clone();
path.push(ii);
let (cost, path) = self.calculate_path(path);
if cost < min_cost {
min_cost = cost;
min_path = path;
}
}
}
(min_cost, min_path)
}
fn calculate_cost_of_path(&self, path: &Vec<usize>) -> i32 {
let mut locations = path.iter();
let mut from = locations.next().unwrap();
let mut cost = 0i32;
loop {
match locations.next() {
Some(to) => {
cost += self.get_edge_cost(*from, *to);
from = to;
},
None => return cost,
}
}
}
fn get_edge_cost(&self, from: usize, to: usize) -> i32 {
match self.matrix {
Some(ref matrix) => matrix[from][to],
None => 0,
}
}
}
fn main(){
println!("Advent of Code - day 9 | part 1");
// import data
let data = import_data();
let graph = match parse_data(data){
Some(x) => x,
None => panic!("Couldn\'t parse data!"),
};
//println!("Graph has the following nodes ({}):", graph.size());
//for name in graph.get_node_names() {
// println!("{}", name);
//}
let path = Vec::new();
let (cost, path) = graph.calculate_path(path);
println!("Shortest path costs: {}", cost);
for location in path {
println!("{}", location);
}
}
fn parse_data(data: String) -> Option<Graph> {
let mut all_names = HashSet::new();
// first: scan data for names
for line in data.lines(){
let names = line.split(" to ").flat_map(|s| s.split(" = ")).take(2);
for name in names {
all_names.insert(name);
}
}
let mut graph = Graph::new(all_names);
for line in data.lines(){
let info = line.split(" to ")
.flat_map(|s| s.split(" = "))
.map(|s| s.parse::<String>().unwrap())
.collect::<Vec<String>>();
let length = info[2].parse::<i32>().unwrap();
graph.insert_edge(&info[0], &info[1], length);
}
Some(graph)
}
// This function simply imports the data set from a file called input.txt
fn
|
() -> String {
let mut file = match File::open("../../inputs/09.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
// remove trailing \n
data.pop();
data
}
|
import_data
|
identifier_name
|
step7_quote.rs
|
#![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc};
use mal::{readline, reader, core};
use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env};
// read
fn read(str: String) -> MalRet {
reader::read_str(str)
}
// eval
fn is_pair(x: MalVal) -> bool {
match *x {
List(ref lst,_) | Vector(ref lst,_) => lst.len() > 0,
_ => false,
}
}
fn quasiquote(ast: MalVal) -> MalVal {
if!is_pair(ast.clone()) {
return list(vec![symbol("quote"), ast])
}
match *ast.clone() {
List(ref args,_) | Vector(ref args,_) => {
let ref a0 = args[0];
match **a0 {
Sym(ref s) if *s == "unquote" => return args[1].clone(),
_ => (),
}
if is_pair(a0.clone()) {
match **a0 {
List(ref a0args,_) | Vector(ref a0args,_) => {
match *a0args[0] {
Sym(ref s) if *s == "splice-unquote" => {
return list(vec![symbol("concat"),
a0args[1].clone(),
quasiquote(list(args[1..].to_vec()))])
},
_ => (),
}
},
_ => (),
}
}
let rest = list(args[1..].to_vec());
return list(vec![symbol("cons"),
quasiquote(a0.clone()),
quasiquote(rest)])
},
_ => _nil(), // should never reach
}
}
fn eval_ast(ast: MalVal, env: Env) -> MalRet {
match *ast {
Sym(_) => env_get(&env, &ast),
List(ref a,_) | Vector(ref a,_) => {
let mut ast_vec : Vec<MalVal> = vec![];
for mv in a.iter() {
let mv2 = mv.clone();
ast_vec.push(try!(eval(mv2, env.clone())));
}
Ok(match *ast { List(_,_) => list(ast_vec),
_ => vector(ast_vec) })
}
Hash_Map(ref hm,_) => {
let mut new_hm: HashMap<String,MalVal> = HashMap::new();
for (key, value) in hm.iter() {
new_hm.insert(key.to_string(),
try!(eval(value.clone(), env.clone())));
}
Ok(hash_map(new_hm))
}
_ => Ok(ast.clone()),
}
}
fn eval(mut ast: MalVal, mut env: Env) -> MalRet
|
return Ok(tmp.clone());
}
let ref a0 = *args[0];
match *a0 {
Sym(ref a0sym) => (args, &a0sym[..]),
_ => (args, "__<fn*>__"),
}
},
_ => return err_str("Expected list"),
};
match a0sym {
"def!" => {
let a1 = (*args)[1].clone();
let a2 = (*args)[2].clone();
let r = try!(eval(a2, env.clone()));
match *a1 {
Sym(_) => {
env_set(&env.clone(), a1, r.clone());
return Ok(r);
},
_ => return err_str("def! of non-symbol"),
}
},
"let*" => {
let let_env = env_new(Some(env.clone()));
let a1 = (*args)[1].clone();
let a2 = (*args)[2].clone();
match *a1 {
List(ref binds,_) | Vector(ref binds,_) => {
let mut it = binds.iter();
while it.len() >= 2 {
let b = it.next().unwrap();
let exp = it.next().unwrap();
match **b {
Sym(_) => {
let r = try!(eval(exp.clone(), let_env.clone()));
env_set(&let_env, b.clone(), r);
},
_ => return err_str("let* with non-symbol binding"),
}
}
},
_ => return err_str("let* with non-list bindings"),
}
ast = a2;
env = let_env.clone();
continue 'tco;
},
"quote" => return Ok((*args)[1].clone()),
"quasiquote" => {
let a1 = (*args)[1].clone();
ast = quasiquote(a1);
continue 'tco;
},
"do" => {
let el = list(args[1..args.len()-1].to_vec());
try!(eval_ast(el, env.clone()));
ast = args[args.len() - 1].clone();
continue 'tco;
},
"if" => {
let a1 = (*args)[1].clone();
let c = try!(eval(a1, env.clone()));
match *c {
False | Nil => {
if args.len() >= 4 {
ast = args[3].clone();
continue 'tco;
} else {
return Ok(_nil());
}
},
_ => {
ast = args[2].clone();
continue 'tco;
},
}
},
"fn*" => {
let a1 = args[1].clone();
let a2 = args[2].clone();
return Ok(malfunc(eval, a2, env, a1, _nil()));
},
"eval" => {
let a1 = (*args)[1].clone();
ast = try!(eval(a1, env.clone()));
env = env_root(&env);
continue 'tco;
},
_ => { // function call
let el = try!(eval_ast(tmp.clone(), env.clone()));
let args = match *el {
List(ref args,_) => args,
_ => return err_str("Invalid apply"),
};
return match *args.clone()[0] {
Func(f,_) => f(args[1..].to_vec()),
MalFunc(ref mf,_) => {
let mfc = mf.clone();
let alst = list(args[1..].to_vec());
let new_env = env_new(Some(mfc.env.clone()));
match env_bind(&new_env, mfc.params, alst) {
Ok(_) => {
ast = mfc.exp;
env = new_env;
continue 'tco;
},
Err(e) => err_str(&e),
}
},
_ => err_str("attempt to call non-function"),
}
},
}
}
}
// print
fn print(exp: MalVal) -> String {
exp.pr_str(true)
}
fn rep(str: &str, env: Env) -> Result<String,MalError> {
let ast = try!(read(str.to_string()));
//println!("read: {}", ast);
let exp = try!(eval(ast, env));
Ok(print(exp))
}
fn main() {
// core.rs: defined using rust
let repl_env = env_new(None);
for (k, v) in core::ns().into_iter() {
env_set(&repl_env, symbol(&k), v);
}
// see eval() for definition of "eval"
env_set(&repl_env, symbol("*ARGV*"), list(vec![]));
// core.mal: defined using the language itself
let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone());
let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone());
// Invoked with command line arguments
let args = stdenv::args();
if args.len() > 1 {
let mv_args = args.skip(2)
.map(|a| string(a))
.collect::<Vec<MalVal>>();
env_set(&repl_env, symbol("*ARGV*"), list(mv_args));
let lf = format!("(load-file \"{}\")",
stdenv::args().skip(1).next().unwrap());
return match rep(&lf, repl_env.clone()) {
Ok(_) => stdenv::set_exit_status(0),
Err(str) => {
println!("Error: {:?}", str);
stdenv::set_exit_status(1);
}
};
}
// repl loop
loop {
let line = readline::mal_readline("user> ");
match line { None => break, _ => () }
match rep(&line.unwrap(), repl_env.clone()) {
Ok(str) => println!("{}", str),
Err(ErrMalVal(_)) => (), // Blank line
Err(ErrString(s)) => println!("Error: {}", s),
}
}
}
|
{
'tco: loop {
//println!("eval: {}, {}", ast, env.borrow());
//println!("eval: {}", ast);
match *ast {
List(_,_) => (), // continue
_ => return eval_ast(ast, env),
}
// apply list
match *ast {
List(_,_) => (), // continue
_ => return Ok(ast),
}
let tmp = ast;
let (args, a0sym) = match *tmp {
List(ref args,_) => {
if args.len() == 0 {
|
identifier_body
|
step7_quote.rs
|
#![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc};
use mal::{readline, reader, core};
use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env};
// read
fn read(str: String) -> MalRet {
reader::read_str(str)
}
// eval
fn
|
(x: MalVal) -> bool {
match *x {
List(ref lst,_) | Vector(ref lst,_) => lst.len() > 0,
_ => false,
}
}
fn quasiquote(ast: MalVal) -> MalVal {
if!is_pair(ast.clone()) {
return list(vec![symbol("quote"), ast])
}
match *ast.clone() {
List(ref args,_) | Vector(ref args,_) => {
let ref a0 = args[0];
match **a0 {
Sym(ref s) if *s == "unquote" => return args[1].clone(),
_ => (),
}
if is_pair(a0.clone()) {
match **a0 {
List(ref a0args,_) | Vector(ref a0args,_) => {
match *a0args[0] {
Sym(ref s) if *s == "splice-unquote" => {
return list(vec![symbol("concat"),
a0args[1].clone(),
quasiquote(list(args[1..].to_vec()))])
},
_ => (),
}
},
_ => (),
}
}
let rest = list(args[1..].to_vec());
return list(vec![symbol("cons"),
quasiquote(a0.clone()),
quasiquote(rest)])
},
_ => _nil(), // should never reach
}
}
fn eval_ast(ast: MalVal, env: Env) -> MalRet {
match *ast {
Sym(_) => env_get(&env, &ast),
List(ref a,_) | Vector(ref a,_) => {
let mut ast_vec : Vec<MalVal> = vec![];
for mv in a.iter() {
let mv2 = mv.clone();
ast_vec.push(try!(eval(mv2, env.clone())));
}
Ok(match *ast { List(_,_) => list(ast_vec),
_ => vector(ast_vec) })
}
Hash_Map(ref hm,_) => {
let mut new_hm: HashMap<String,MalVal> = HashMap::new();
for (key, value) in hm.iter() {
new_hm.insert(key.to_string(),
try!(eval(value.clone(), env.clone())));
}
Ok(hash_map(new_hm))
}
_ => Ok(ast.clone()),
}
}
fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
'tco: loop {
//println!("eval: {}, {}", ast, env.borrow());
//println!("eval: {}", ast);
match *ast {
List(_,_) => (), // continue
_ => return eval_ast(ast, env),
}
// apply list
match *ast {
List(_,_) => (), // continue
_ => return Ok(ast),
}
let tmp = ast;
let (args, a0sym) = match *tmp {
List(ref args,_) => {
if args.len() == 0 {
return Ok(tmp.clone());
}
let ref a0 = *args[0];
match *a0 {
Sym(ref a0sym) => (args, &a0sym[..]),
_ => (args, "__<fn*>__"),
}
},
_ => return err_str("Expected list"),
};
match a0sym {
"def!" => {
let a1 = (*args)[1].clone();
let a2 = (*args)[2].clone();
let r = try!(eval(a2, env.clone()));
match *a1 {
Sym(_) => {
env_set(&env.clone(), a1, r.clone());
return Ok(r);
},
_ => return err_str("def! of non-symbol"),
}
},
"let*" => {
let let_env = env_new(Some(env.clone()));
let a1 = (*args)[1].clone();
let a2 = (*args)[2].clone();
match *a1 {
List(ref binds,_) | Vector(ref binds,_) => {
let mut it = binds.iter();
while it.len() >= 2 {
let b = it.next().unwrap();
let exp = it.next().unwrap();
match **b {
Sym(_) => {
let r = try!(eval(exp.clone(), let_env.clone()));
env_set(&let_env, b.clone(), r);
},
_ => return err_str("let* with non-symbol binding"),
}
}
},
_ => return err_str("let* with non-list bindings"),
}
ast = a2;
env = let_env.clone();
continue 'tco;
},
"quote" => return Ok((*args)[1].clone()),
"quasiquote" => {
let a1 = (*args)[1].clone();
ast = quasiquote(a1);
continue 'tco;
},
"do" => {
let el = list(args[1..args.len()-1].to_vec());
try!(eval_ast(el, env.clone()));
ast = args[args.len() - 1].clone();
continue 'tco;
},
"if" => {
let a1 = (*args)[1].clone();
let c = try!(eval(a1, env.clone()));
match *c {
False | Nil => {
if args.len() >= 4 {
ast = args[3].clone();
continue 'tco;
} else {
return Ok(_nil());
}
},
_ => {
ast = args[2].clone();
continue 'tco;
},
}
},
"fn*" => {
let a1 = args[1].clone();
let a2 = args[2].clone();
return Ok(malfunc(eval, a2, env, a1, _nil()));
},
"eval" => {
let a1 = (*args)[1].clone();
ast = try!(eval(a1, env.clone()));
env = env_root(&env);
continue 'tco;
},
_ => { // function call
let el = try!(eval_ast(tmp.clone(), env.clone()));
let args = match *el {
List(ref args,_) => args,
_ => return err_str("Invalid apply"),
};
return match *args.clone()[0] {
Func(f,_) => f(args[1..].to_vec()),
MalFunc(ref mf,_) => {
let mfc = mf.clone();
let alst = list(args[1..].to_vec());
let new_env = env_new(Some(mfc.env.clone()));
match env_bind(&new_env, mfc.params, alst) {
Ok(_) => {
ast = mfc.exp;
env = new_env;
continue 'tco;
},
Err(e) => err_str(&e),
}
},
_ => err_str("attempt to call non-function"),
}
},
}
}
}
// print
fn print(exp: MalVal) -> String {
exp.pr_str(true)
}
fn rep(str: &str, env: Env) -> Result<String,MalError> {
let ast = try!(read(str.to_string()));
//println!("read: {}", ast);
let exp = try!(eval(ast, env));
Ok(print(exp))
}
fn main() {
// core.rs: defined using rust
let repl_env = env_new(None);
for (k, v) in core::ns().into_iter() {
env_set(&repl_env, symbol(&k), v);
}
// see eval() for definition of "eval"
env_set(&repl_env, symbol("*ARGV*"), list(vec![]));
// core.mal: defined using the language itself
let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone());
let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone());
// Invoked with command line arguments
let args = stdenv::args();
if args.len() > 1 {
let mv_args = args.skip(2)
.map(|a| string(a))
.collect::<Vec<MalVal>>();
env_set(&repl_env, symbol("*ARGV*"), list(mv_args));
let lf = format!("(load-file \"{}\")",
stdenv::args().skip(1).next().unwrap());
return match rep(&lf, repl_env.clone()) {
Ok(_) => stdenv::set_exit_status(0),
Err(str) => {
println!("Error: {:?}", str);
stdenv::set_exit_status(1);
}
};
}
// repl loop
loop {
let line = readline::mal_readline("user> ");
match line { None => break, _ => () }
match rep(&line.unwrap(), repl_env.clone()) {
Ok(str) => println!("{}", str),
Err(ErrMalVal(_)) => (), // Blank line
Err(ErrString(s)) => println!("Error: {}", s),
}
}
}
|
is_pair
|
identifier_name
|
step7_quote.rs
|
#![feature(exit_status)]
extern crate mal;
use std::collections::HashMap;
use std::env as stdenv;
use mal::types::{MalVal, MalRet, MalError, err_str};
use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc};
use mal::types::MalError::{ErrString, ErrMalVal};
use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc};
use mal::{readline, reader, core};
use mal::env::{env_set, env_get, env_new, env_bind, env_root, Env};
// read
fn read(str: String) -> MalRet {
reader::read_str(str)
}
// eval
fn is_pair(x: MalVal) -> bool {
match *x {
List(ref lst,_) | Vector(ref lst,_) => lst.len() > 0,
_ => false,
}
}
|
return list(vec![symbol("quote"), ast])
}
match *ast.clone() {
List(ref args,_) | Vector(ref args,_) => {
let ref a0 = args[0];
match **a0 {
Sym(ref s) if *s == "unquote" => return args[1].clone(),
_ => (),
}
if is_pair(a0.clone()) {
match **a0 {
List(ref a0args,_) | Vector(ref a0args,_) => {
match *a0args[0] {
Sym(ref s) if *s == "splice-unquote" => {
return list(vec![symbol("concat"),
a0args[1].clone(),
quasiquote(list(args[1..].to_vec()))])
},
_ => (),
}
},
_ => (),
}
}
let rest = list(args[1..].to_vec());
return list(vec![symbol("cons"),
quasiquote(a0.clone()),
quasiquote(rest)])
},
_ => _nil(), // should never reach
}
}
fn eval_ast(ast: MalVal, env: Env) -> MalRet {
match *ast {
Sym(_) => env_get(&env, &ast),
List(ref a,_) | Vector(ref a,_) => {
let mut ast_vec : Vec<MalVal> = vec![];
for mv in a.iter() {
let mv2 = mv.clone();
ast_vec.push(try!(eval(mv2, env.clone())));
}
Ok(match *ast { List(_,_) => list(ast_vec),
_ => vector(ast_vec) })
}
Hash_Map(ref hm,_) => {
let mut new_hm: HashMap<String,MalVal> = HashMap::new();
for (key, value) in hm.iter() {
new_hm.insert(key.to_string(),
try!(eval(value.clone(), env.clone())));
}
Ok(hash_map(new_hm))
}
_ => Ok(ast.clone()),
}
}
fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
'tco: loop {
//println!("eval: {}, {}", ast, env.borrow());
//println!("eval: {}", ast);
match *ast {
List(_,_) => (), // continue
_ => return eval_ast(ast, env),
}
// apply list
match *ast {
List(_,_) => (), // continue
_ => return Ok(ast),
}
let tmp = ast;
let (args, a0sym) = match *tmp {
List(ref args,_) => {
if args.len() == 0 {
return Ok(tmp.clone());
}
let ref a0 = *args[0];
match *a0 {
Sym(ref a0sym) => (args, &a0sym[..]),
_ => (args, "__<fn*>__"),
}
},
_ => return err_str("Expected list"),
};
match a0sym {
"def!" => {
let a1 = (*args)[1].clone();
let a2 = (*args)[2].clone();
let r = try!(eval(a2, env.clone()));
match *a1 {
Sym(_) => {
env_set(&env.clone(), a1, r.clone());
return Ok(r);
},
_ => return err_str("def! of non-symbol"),
}
},
"let*" => {
let let_env = env_new(Some(env.clone()));
let a1 = (*args)[1].clone();
let a2 = (*args)[2].clone();
match *a1 {
List(ref binds,_) | Vector(ref binds,_) => {
let mut it = binds.iter();
while it.len() >= 2 {
let b = it.next().unwrap();
let exp = it.next().unwrap();
match **b {
Sym(_) => {
let r = try!(eval(exp.clone(), let_env.clone()));
env_set(&let_env, b.clone(), r);
},
_ => return err_str("let* with non-symbol binding"),
}
}
},
_ => return err_str("let* with non-list bindings"),
}
ast = a2;
env = let_env.clone();
continue 'tco;
},
"quote" => return Ok((*args)[1].clone()),
"quasiquote" => {
let a1 = (*args)[1].clone();
ast = quasiquote(a1);
continue 'tco;
},
"do" => {
let el = list(args[1..args.len()-1].to_vec());
try!(eval_ast(el, env.clone()));
ast = args[args.len() - 1].clone();
continue 'tco;
},
"if" => {
let a1 = (*args)[1].clone();
let c = try!(eval(a1, env.clone()));
match *c {
False | Nil => {
if args.len() >= 4 {
ast = args[3].clone();
continue 'tco;
} else {
return Ok(_nil());
}
},
_ => {
ast = args[2].clone();
continue 'tco;
},
}
},
"fn*" => {
let a1 = args[1].clone();
let a2 = args[2].clone();
return Ok(malfunc(eval, a2, env, a1, _nil()));
},
"eval" => {
let a1 = (*args)[1].clone();
ast = try!(eval(a1, env.clone()));
env = env_root(&env);
continue 'tco;
},
_ => { // function call
let el = try!(eval_ast(tmp.clone(), env.clone()));
let args = match *el {
List(ref args,_) => args,
_ => return err_str("Invalid apply"),
};
return match *args.clone()[0] {
Func(f,_) => f(args[1..].to_vec()),
MalFunc(ref mf,_) => {
let mfc = mf.clone();
let alst = list(args[1..].to_vec());
let new_env = env_new(Some(mfc.env.clone()));
match env_bind(&new_env, mfc.params, alst) {
Ok(_) => {
ast = mfc.exp;
env = new_env;
continue 'tco;
},
Err(e) => err_str(&e),
}
},
_ => err_str("attempt to call non-function"),
}
},
}
}
}
// print
fn print(exp: MalVal) -> String {
exp.pr_str(true)
}
fn rep(str: &str, env: Env) -> Result<String,MalError> {
let ast = try!(read(str.to_string()));
//println!("read: {}", ast);
let exp = try!(eval(ast, env));
Ok(print(exp))
}
fn main() {
// core.rs: defined using rust
let repl_env = env_new(None);
for (k, v) in core::ns().into_iter() {
env_set(&repl_env, symbol(&k), v);
}
// see eval() for definition of "eval"
env_set(&repl_env, symbol("*ARGV*"), list(vec![]));
// core.mal: defined using the language itself
let _ = rep("(def! not (fn* (a) (if a false true)))", repl_env.clone());
let _ = rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env.clone());
// Invoked with command line arguments
let args = stdenv::args();
if args.len() > 1 {
let mv_args = args.skip(2)
.map(|a| string(a))
.collect::<Vec<MalVal>>();
env_set(&repl_env, symbol("*ARGV*"), list(mv_args));
let lf = format!("(load-file \"{}\")",
stdenv::args().skip(1).next().unwrap());
return match rep(&lf, repl_env.clone()) {
Ok(_) => stdenv::set_exit_status(0),
Err(str) => {
println!("Error: {:?}", str);
stdenv::set_exit_status(1);
}
};
}
// repl loop
loop {
let line = readline::mal_readline("user> ");
match line { None => break, _ => () }
match rep(&line.unwrap(), repl_env.clone()) {
Ok(str) => println!("{}", str),
Err(ErrMalVal(_)) => (), // Blank line
Err(ErrString(s)) => println!("Error: {}", s),
}
}
}
|
fn quasiquote(ast: MalVal) -> MalVal {
if !is_pair(ast.clone()) {
|
random_line_split
|
main.rs
|
extern crate graphics;
extern crate freetype as ft;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
#[cfg(feature = "include_glfw")]
extern crate glfw_window;
#[cfg(feature = "include_glutin")]
extern crate glutin_window;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
#[cfg(feature = "include_glfw")]
use glfw_window::GlfwWindow as AppWindow;
#[cfg(feature = "include_glutin")]
use glutin_window::GlutinWindow as AppWindow;
use opengl_graphics::{ GlGraphics, Texture, TextureSettings, OpenGL };
use piston::window::WindowSettings;
use piston::input::*;
use piston::event_loop::{Events, EventSettings, EventLoop};
use graphics::{Context, Graphics, ImageSize};
fn glyphs(face: &mut ft::Face, text: &str) -> Vec<(Texture, [f64; 2])> {
let mut x = 10;
let mut y = 0;
let mut res = vec![];
for ch in text.chars() {
face.load_char(ch as usize, ft::face::LoadFlag::RENDER).unwrap();
let g = face.glyph();
let bitmap = g.bitmap();
|
).unwrap();
res.push((texture, [(x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64]));
x += (g.advance().x >> 6) as i32;
y += (g.advance().y >> 6) as i32;
}
res
}
fn render_text<G, T>(glyphs: &[(T, [f64; 2])], c: &Context, gl: &mut G)
where G: Graphics<Texture = T>, T: ImageSize
{
for &(ref texture, [x, y]) in glyphs {
use graphics::*;
Image::new_color(color::BLACK).draw(
texture,
&c.draw_state,
c.transform.trans(x, y),
gl
);
}
}
fn main() {
let opengl = OpenGL::V3_2;
let mut window: AppWindow =
WindowSettings::new("piston-example-freetype", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let freetype = ft::Library::init().unwrap();
let font = assets.join("FiraSans-Regular.ttf");
let mut face = freetype.new_face(&font, 0).unwrap();
face.set_pixel_sizes(0, 48).unwrap();
let ref mut gl = GlGraphics::new(opengl);
let glyphs = glyphs(&mut face, "Hello Piston!");
let mut events = Events::new(EventSettings::new().lazy(true));
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
use graphics::*;
gl.draw(args.viewport(), |c, gl| {
clear(color::WHITE, gl);
render_text(&glyphs, &c.trans(0.0, 100.0), gl);
});
}
}
}
|
let texture = Texture::from_memory_alpha(
bitmap.buffer(),
bitmap.width() as u32,
bitmap.rows() as u32,
&TextureSettings::new()
|
random_line_split
|
main.rs
|
extern crate graphics;
extern crate freetype as ft;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
#[cfg(feature = "include_glfw")]
extern crate glfw_window;
#[cfg(feature = "include_glutin")]
extern crate glutin_window;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
#[cfg(feature = "include_glfw")]
use glfw_window::GlfwWindow as AppWindow;
#[cfg(feature = "include_glutin")]
use glutin_window::GlutinWindow as AppWindow;
use opengl_graphics::{ GlGraphics, Texture, TextureSettings, OpenGL };
use piston::window::WindowSettings;
use piston::input::*;
use piston::event_loop::{Events, EventSettings, EventLoop};
use graphics::{Context, Graphics, ImageSize};
fn glyphs(face: &mut ft::Face, text: &str) -> Vec<(Texture, [f64; 2])>
|
res
}
fn render_text<G, T>(glyphs: &[(T, [f64; 2])], c: &Context, gl: &mut G)
where G: Graphics<Texture = T>, T: ImageSize
{
for &(ref texture, [x, y]) in glyphs {
use graphics::*;
Image::new_color(color::BLACK).draw(
texture,
&c.draw_state,
c.transform.trans(x, y),
gl
);
}
}
fn main() {
let opengl = OpenGL::V3_2;
let mut window: AppWindow =
WindowSettings::new("piston-example-freetype", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let freetype = ft::Library::init().unwrap();
let font = assets.join("FiraSans-Regular.ttf");
let mut face = freetype.new_face(&font, 0).unwrap();
face.set_pixel_sizes(0, 48).unwrap();
let ref mut gl = GlGraphics::new(opengl);
let glyphs = glyphs(&mut face, "Hello Piston!");
let mut events = Events::new(EventSettings::new().lazy(true));
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
use graphics::*;
gl.draw(args.viewport(), |c, gl| {
clear(color::WHITE, gl);
render_text(&glyphs, &c.trans(0.0, 100.0), gl);
});
}
}
}
|
{
let mut x = 10;
let mut y = 0;
let mut res = vec![];
for ch in text.chars() {
face.load_char(ch as usize, ft::face::LoadFlag::RENDER).unwrap();
let g = face.glyph();
let bitmap = g.bitmap();
let texture = Texture::from_memory_alpha(
bitmap.buffer(),
bitmap.width() as u32,
bitmap.rows() as u32,
&TextureSettings::new()
).unwrap();
res.push((texture, [(x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64]));
x += (g.advance().x >> 6) as i32;
y += (g.advance().y >> 6) as i32;
}
|
identifier_body
|
main.rs
|
extern crate graphics;
extern crate freetype as ft;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
#[cfg(feature = "include_glfw")]
extern crate glfw_window;
#[cfg(feature = "include_glutin")]
extern crate glutin_window;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
#[cfg(feature = "include_glfw")]
use glfw_window::GlfwWindow as AppWindow;
#[cfg(feature = "include_glutin")]
use glutin_window::GlutinWindow as AppWindow;
use opengl_graphics::{ GlGraphics, Texture, TextureSettings, OpenGL };
use piston::window::WindowSettings;
use piston::input::*;
use piston::event_loop::{Events, EventSettings, EventLoop};
use graphics::{Context, Graphics, ImageSize};
fn glyphs(face: &mut ft::Face, text: &str) -> Vec<(Texture, [f64; 2])> {
let mut x = 10;
let mut y = 0;
let mut res = vec![];
for ch in text.chars() {
face.load_char(ch as usize, ft::face::LoadFlag::RENDER).unwrap();
let g = face.glyph();
let bitmap = g.bitmap();
let texture = Texture::from_memory_alpha(
bitmap.buffer(),
bitmap.width() as u32,
bitmap.rows() as u32,
&TextureSettings::new()
).unwrap();
res.push((texture, [(x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64]));
x += (g.advance().x >> 6) as i32;
y += (g.advance().y >> 6) as i32;
}
res
}
fn render_text<G, T>(glyphs: &[(T, [f64; 2])], c: &Context, gl: &mut G)
where G: Graphics<Texture = T>, T: ImageSize
{
for &(ref texture, [x, y]) in glyphs {
use graphics::*;
Image::new_color(color::BLACK).draw(
texture,
&c.draw_state,
c.transform.trans(x, y),
gl
);
}
}
fn main() {
let opengl = OpenGL::V3_2;
let mut window: AppWindow =
WindowSettings::new("piston-example-freetype", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let freetype = ft::Library::init().unwrap();
let font = assets.join("FiraSans-Regular.ttf");
let mut face = freetype.new_face(&font, 0).unwrap();
face.set_pixel_sizes(0, 48).unwrap();
let ref mut gl = GlGraphics::new(opengl);
let glyphs = glyphs(&mut face, "Hello Piston!");
let mut events = Events::new(EventSettings::new().lazy(true));
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args()
|
}
}
|
{
use graphics::*;
gl.draw(args.viewport(), |c, gl| {
clear(color::WHITE, gl);
render_text(&glyphs, &c.trans(0.0, 100.0), gl);
});
}
|
conditional_block
|
main.rs
|
extern crate graphics;
extern crate freetype as ft;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
#[cfg(feature = "include_glfw")]
extern crate glfw_window;
#[cfg(feature = "include_glutin")]
extern crate glutin_window;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
#[cfg(feature = "include_glfw")]
use glfw_window::GlfwWindow as AppWindow;
#[cfg(feature = "include_glutin")]
use glutin_window::GlutinWindow as AppWindow;
use opengl_graphics::{ GlGraphics, Texture, TextureSettings, OpenGL };
use piston::window::WindowSettings;
use piston::input::*;
use piston::event_loop::{Events, EventSettings, EventLoop};
use graphics::{Context, Graphics, ImageSize};
fn
|
(face: &mut ft::Face, text: &str) -> Vec<(Texture, [f64; 2])> {
let mut x = 10;
let mut y = 0;
let mut res = vec![];
for ch in text.chars() {
face.load_char(ch as usize, ft::face::LoadFlag::RENDER).unwrap();
let g = face.glyph();
let bitmap = g.bitmap();
let texture = Texture::from_memory_alpha(
bitmap.buffer(),
bitmap.width() as u32,
bitmap.rows() as u32,
&TextureSettings::new()
).unwrap();
res.push((texture, [(x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64]));
x += (g.advance().x >> 6) as i32;
y += (g.advance().y >> 6) as i32;
}
res
}
fn render_text<G, T>(glyphs: &[(T, [f64; 2])], c: &Context, gl: &mut G)
where G: Graphics<Texture = T>, T: ImageSize
{
for &(ref texture, [x, y]) in glyphs {
use graphics::*;
Image::new_color(color::BLACK).draw(
texture,
&c.draw_state,
c.transform.trans(x, y),
gl
);
}
}
fn main() {
let opengl = OpenGL::V3_2;
let mut window: AppWindow =
WindowSettings::new("piston-example-freetype", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let freetype = ft::Library::init().unwrap();
let font = assets.join("FiraSans-Regular.ttf");
let mut face = freetype.new_face(&font, 0).unwrap();
face.set_pixel_sizes(0, 48).unwrap();
let ref mut gl = GlGraphics::new(opengl);
let glyphs = glyphs(&mut face, "Hello Piston!");
let mut events = Events::new(EventSettings::new().lazy(true));
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
use graphics::*;
gl.draw(args.viewport(), |c, gl| {
clear(color::WHITE, gl);
render_text(&glyphs, &c.trans(0.0, 100.0), gl);
});
}
}
}
|
glyphs
|
identifier_name
|
navigator.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::reflector::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::bluetooth::Bluetooth;
use dom::mimetypearray::MimeTypeArray;
use dom::navigatorinfo;
use dom::pluginarray::PluginArray;
use dom::window::Window;
#[dom_struct]
pub struct Navigator {
reflector_: Reflector,
bluetooth: MutNullableHeap<JS<Bluetooth>>,
plugins: MutNullableHeap<JS<PluginArray>>,
mime_types: MutNullableHeap<JS<MimeTypeArray>>,
}
impl Navigator {
fn new_inherited() -> Navigator {
Navigator {
reflector_: Reflector::new(),
bluetooth: Default::default(),
plugins: Default::default(),
mime_types: Default::default(),
}
}
pub fn new(window: &Window) -> Root<Navigator> {
reflect_dom_object(box Navigator::new_inherited(),
GlobalRef::Window(window),
NavigatorBinding::Wrap)
}
}
impl NavigatorMethods for Navigator {
// https://html.spec.whatwg.org/multipage/#dom-navigator-product
fn Product(&self) -> DOMString {
navigatorinfo::Product()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMString {
navigatorinfo::AppVersion()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth
fn Bluetooth(&self) -> Root<Bluetooth> {
self.bluetooth.or_init(|| Bluetooth::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#navigatorlanguage
fn
|
(&self) -> DOMString {
navigatorinfo::Language()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-plugins
fn Plugins(&self) -> Root<PluginArray> {
self.plugins.or_init(|| PluginArray::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes
fn MimeTypes(&self) -> Root<MimeTypeArray> {
self.mime_types.or_init(|| MimeTypeArray::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled
fn JavaEnabled(&self) -> bool {
false
}
}
|
Language
|
identifier_name
|
navigator.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::reflector::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::bluetooth::Bluetooth;
use dom::mimetypearray::MimeTypeArray;
use dom::navigatorinfo;
use dom::pluginarray::PluginArray;
use dom::window::Window;
#[dom_struct]
pub struct Navigator {
reflector_: Reflector,
bluetooth: MutNullableHeap<JS<Bluetooth>>,
plugins: MutNullableHeap<JS<PluginArray>>,
mime_types: MutNullableHeap<JS<MimeTypeArray>>,
}
impl Navigator {
fn new_inherited() -> Navigator {
Navigator {
reflector_: Reflector::new(),
bluetooth: Default::default(),
plugins: Default::default(),
mime_types: Default::default(),
}
}
pub fn new(window: &Window) -> Root<Navigator> {
reflect_dom_object(box Navigator::new_inherited(),
GlobalRef::Window(window),
NavigatorBinding::Wrap)
}
}
impl NavigatorMethods for Navigator {
// https://html.spec.whatwg.org/multipage/#dom-navigator-product
fn Product(&self) -> DOMString {
navigatorinfo::Product()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString
|
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMString {
navigatorinfo::AppVersion()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth
fn Bluetooth(&self) -> Root<Bluetooth> {
self.bluetooth.or_init(|| Bluetooth::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#navigatorlanguage
fn Language(&self) -> DOMString {
navigatorinfo::Language()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-plugins
fn Plugins(&self) -> Root<PluginArray> {
self.plugins.or_init(|| PluginArray::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes
fn MimeTypes(&self) -> Root<MimeTypeArray> {
self.mime_types.or_init(|| MimeTypeArray::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled
fn JavaEnabled(&self) -> bool {
false
}
}
|
{
navigatorinfo::AppCodeName()
}
|
identifier_body
|
navigator.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::reflector::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::bluetooth::Bluetooth;
use dom::mimetypearray::MimeTypeArray;
use dom::navigatorinfo;
use dom::pluginarray::PluginArray;
use dom::window::Window;
#[dom_struct]
pub struct Navigator {
reflector_: Reflector,
bluetooth: MutNullableHeap<JS<Bluetooth>>,
plugins: MutNullableHeap<JS<PluginArray>>,
mime_types: MutNullableHeap<JS<MimeTypeArray>>,
}
impl Navigator {
fn new_inherited() -> Navigator {
Navigator {
reflector_: Reflector::new(),
bluetooth: Default::default(),
plugins: Default::default(),
mime_types: Default::default(),
}
}
pub fn new(window: &Window) -> Root<Navigator> {
reflect_dom_object(box Navigator::new_inherited(),
GlobalRef::Window(window),
NavigatorBinding::Wrap)
}
}
impl NavigatorMethods for Navigator {
// https://html.spec.whatwg.org/multipage/#dom-navigator-product
fn Product(&self) -> DOMString {
navigatorinfo::Product()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMString {
navigatorinfo::AppVersion()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth
fn Bluetooth(&self) -> Root<Bluetooth> {
self.bluetooth.or_init(|| Bluetooth::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#navigatorlanguage
fn Language(&self) -> DOMString {
navigatorinfo::Language()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-plugins
fn Plugins(&self) -> Root<PluginArray> {
self.plugins.or_init(|| PluginArray::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes
fn MimeTypes(&self) -> Root<MimeTypeArray> {
self.mime_types.or_init(|| MimeTypeArray::new(self.global().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled
fn JavaEnabled(&self) -> bool {
false
}
}
|
random_line_split
|
|
build.rs
|
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::process::Command;
// this build script is called on en every `devtool build`,
// embedding the FIRECRACKER_VERSION directly in the resulting binary
fn
|
() {
let firecracker_version = Command::new("git")
.args(&["describe", "--dirty"])
.output()
.ok()
.and_then(|output| {
if output.status.success() {
return Some(output.stdout);
}
None
})
.and_then(|version_bytes| String::from_utf8(version_bytes).ok())
.map(|version_string| version_string.trim_start_matches('v').to_string())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
println!(
"cargo:rustc-env=FIRECRACKER_VERSION={}",
firecracker_version
);
}
|
main
|
identifier_name
|
build.rs
|
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
|
// this build script is called on en every `devtool build`,
// embedding the FIRECRACKER_VERSION directly in the resulting binary
fn main() {
let firecracker_version = Command::new("git")
.args(&["describe", "--dirty"])
.output()
.ok()
.and_then(|output| {
if output.status.success() {
return Some(output.stdout);
}
None
})
.and_then(|version_bytes| String::from_utf8(version_bytes).ok())
.map(|version_string| version_string.trim_start_matches('v').to_string())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
println!(
"cargo:rustc-env=FIRECRACKER_VERSION={}",
firecracker_version
);
}
|
use std::process::Command;
|
random_line_split
|
build.rs
|
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::process::Command;
// this build script is called on en every `devtool build`,
// embedding the FIRECRACKER_VERSION directly in the resulting binary
fn main()
|
{
let firecracker_version = Command::new("git")
.args(&["describe", "--dirty"])
.output()
.ok()
.and_then(|output| {
if output.status.success() {
return Some(output.stdout);
}
None
})
.and_then(|version_bytes| String::from_utf8(version_bytes).ok())
.map(|version_string| version_string.trim_start_matches('v').to_string())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
println!(
"cargo:rustc-env=FIRECRACKER_VERSION={}",
firecracker_version
);
}
|
identifier_body
|
|
build.rs
|
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::process::Command;
// this build script is called on en every `devtool build`,
// embedding the FIRECRACKER_VERSION directly in the resulting binary
fn main() {
let firecracker_version = Command::new("git")
.args(&["describe", "--dirty"])
.output()
.ok()
.and_then(|output| {
if output.status.success()
|
None
})
.and_then(|version_bytes| String::from_utf8(version_bytes).ok())
.map(|version_string| version_string.trim_start_matches('v').to_string())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
println!(
"cargo:rustc-env=FIRECRACKER_VERSION={}",
firecracker_version
);
}
|
{
return Some(output.stdout);
}
|
conditional_block
|
dom.rs
|
Some(n) => {
// Filter out nodes that layout should ignore.
if n.is_text_node() || n.is_element() {
return Some(n)
}
}
None => return None,
}
}
}
}
/// An iterator over the DOM children of a node.
pub struct DomChildren<N>(Option<N>);
impl<N> Iterator for DomChildren<N>
where
N: TNode
{
type Item = N;
fn next(&mut self) -> Option<N> {
match self.0.take() {
Some(n) => {
self.0 = n.next_sibling();
Some(n)
}
None => None,
}
}
}
/// An iterator over the DOM descendants of a node in pre-order.
pub struct DomDescendants<N> {
previous: Option<N>,
scope: N,
}
impl<N> Iterator for DomDescendants<N>
where
N: TNode
{
type Item = N;
#[inline]
fn next(&mut self) -> Option<N> {
let prev = match self.previous.take() {
None => return None,
Some(n) => n,
};
self.previous = prev.next_in_preorder(Some(self.scope));
self.previous
}
}
/// The `TDocument` trait, to represent a document node.
pub trait TDocument : Sized + Copy + Clone {
/// The concrete `TNode` type.
type ConcreteNode: TNode<ConcreteDocument = Self>;
/// Get this document as a `TNode`.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns whether this document is an HTML document.
fn is_html_document(&self) -> bool;
/// Returns the quirks mode of this document.
fn quirks_mode(&self) -> QuirksMode;
/// Get a list of elements with a given ID in this document, sorted by
/// document position.
///
/// Can return an error to signal that this list is not available, or also
/// return an empty slice.
fn
|
(
&self,
_id: &Atom,
) -> Result<&[<Self::ConcreteNode as TNode>::ConcreteElement], ()> {
Err(())
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo + PartialEq {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// The concrete `TDocument` type.
type ConcreteDocument: TDocument<ConcreteNode = Self>;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's first child.
fn first_child(&self) -> Option<Self>;
/// Get this node's first child.
fn last_child(&self) -> Option<Self>;
/// Get this node's previous sibling.
fn prev_sibling(&self) -> Option<Self>;
/// Get this node's next sibling.
fn next_sibling(&self) -> Option<Self>;
/// Get the owner document of this node.
fn owner_doc(&self) -> Self::ConcreteDocument;
/// Iterate over the DOM children of a node.
fn dom_children(&self) -> DomChildren<Self> {
DomChildren(self.first_child())
}
/// Returns whether the node is attached to a document.
fn is_in_document(&self) -> bool;
/// Iterate over the DOM children of a node, in preorder.
fn dom_descendants(&self) -> DomDescendants<Self> {
DomDescendants {
previous: Some(*self),
scope: *self,
}
}
/// Returns the next children in pre-order, optionally scoped to a subtree
/// root.
#[inline]
fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> {
if let Some(c) = self.first_child() {
return Some(c);
}
if Some(*self) == scoped_to {
return None;
}
let mut current = *self;
loop {
if let Some(s) = current.next_sibling() {
return Some(s);
}
let parent = current.parent_node();
if parent == scoped_to {
return None;
}
current = parent.expect("Not a descendant of the scope?");
}
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Get this node as a document, if it's one.
fn as_document(&self) -> Option<Self::ConcreteDocument>;
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
#[cfg(feature = "servo")]
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
#[cfg(feature = "servo")]
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
#[cfg(feature = "servo")]
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// The style scope of this element is a node that represents which rules
/// apply to the element.
///
/// In Servo, where we don't know about Shadow DOM or XBL, the style scope
/// is always the document.
fn style_scope(&self) -> Self::ConcreteNode {
self.as_node().owner_doc().as_node()
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(TraversalFlags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do
|
elements_with_id
|
identifier_name
|
dom.rs
|
None => return None,
Some(n) => n,
};
self.previous = prev.next_in_preorder(Some(self.scope));
self.previous
}
}
/// The `TDocument` trait, to represent a document node.
pub trait TDocument : Sized + Copy + Clone {
/// The concrete `TNode` type.
type ConcreteNode: TNode<ConcreteDocument = Self>;
/// Get this document as a `TNode`.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns whether this document is an HTML document.
fn is_html_document(&self) -> bool;
/// Returns the quirks mode of this document.
fn quirks_mode(&self) -> QuirksMode;
/// Get a list of elements with a given ID in this document, sorted by
/// document position.
///
/// Can return an error to signal that this list is not available, or also
/// return an empty slice.
fn elements_with_id(
&self,
_id: &Atom,
) -> Result<&[<Self::ConcreteNode as TNode>::ConcreteElement], ()> {
Err(())
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo + PartialEq {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// The concrete `TDocument` type.
type ConcreteDocument: TDocument<ConcreteNode = Self>;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's first child.
fn first_child(&self) -> Option<Self>;
/// Get this node's first child.
fn last_child(&self) -> Option<Self>;
/// Get this node's previous sibling.
fn prev_sibling(&self) -> Option<Self>;
/// Get this node's next sibling.
fn next_sibling(&self) -> Option<Self>;
/// Get the owner document of this node.
fn owner_doc(&self) -> Self::ConcreteDocument;
/// Iterate over the DOM children of a node.
fn dom_children(&self) -> DomChildren<Self> {
DomChildren(self.first_child())
}
/// Returns whether the node is attached to a document.
fn is_in_document(&self) -> bool;
/// Iterate over the DOM children of a node, in preorder.
fn dom_descendants(&self) -> DomDescendants<Self> {
DomDescendants {
previous: Some(*self),
scope: *self,
}
}
/// Returns the next children in pre-order, optionally scoped to a subtree
/// root.
#[inline]
fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> {
if let Some(c) = self.first_child() {
return Some(c);
}
if Some(*self) == scoped_to {
return None;
}
let mut current = *self;
loop {
if let Some(s) = current.next_sibling() {
return Some(s);
}
let parent = current.parent_node();
if parent == scoped_to {
return None;
}
current = parent.expect("Not a descendant of the scope?");
}
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Get this node as a document, if it's one.
fn as_document(&self) -> Option<Self::ConcreteDocument>;
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
#[cfg(feature = "servo")]
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
#[cfg(feature = "servo")]
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
#[cfg(feature = "servo")]
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// The style scope of this element is a node that represents which rules
/// apply to the element.
///
/// In Servo, where we don't know about Shadow DOM or XBL, the style scope
/// is always the document.
fn style_scope(&self) -> Self::ConcreteNode {
self.as_node().owner_doc().as_node()
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(TraversalFlags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.hint.has_animation_hint()
}
/// Returns the anonymous content for the current element's XBL binding,
/// given if any.
///
/// This is used in Gecko for XBL and shadow DOM.
fn xbl_binding_anonymous_content(&self) -> Option<Self::ConcreteNode> {
None
}
/// Return the element which we can use to look up rules in the selector
/// maps.
///
/// This is always the element itself, except in the case where we are an
/// element-backed pseudo-element, in which case we return the originating
/// element.
fn rule_hash_target(&self) -> Self {
let is_implemented_pseudo =
self.implemented_pseudo_element().is_some();
if is_implemented_pseudo {
self.closest_non_native_anonymous_ancestor().unwrap()
} else
|
{
*self
}
|
conditional_block
|
|
dom.rs
|
Some(n) => {
// Filter out nodes that layout should ignore.
if n.is_text_node() || n.is_element() {
return Some(n)
}
}
None => return None,
}
}
}
}
/// An iterator over the DOM children of a node.
pub struct DomChildren<N>(Option<N>);
impl<N> Iterator for DomChildren<N>
where
N: TNode
{
type Item = N;
fn next(&mut self) -> Option<N> {
match self.0.take() {
Some(n) => {
self.0 = n.next_sibling();
Some(n)
}
None => None,
}
}
}
/// An iterator over the DOM descendants of a node in pre-order.
pub struct DomDescendants<N> {
previous: Option<N>,
scope: N,
|
impl<N> Iterator for DomDescendants<N>
where
N: TNode
{
type Item = N;
#[inline]
fn next(&mut self) -> Option<N> {
let prev = match self.previous.take() {
None => return None,
Some(n) => n,
};
self.previous = prev.next_in_preorder(Some(self.scope));
self.previous
}
}
/// The `TDocument` trait, to represent a document node.
pub trait TDocument : Sized + Copy + Clone {
/// The concrete `TNode` type.
type ConcreteNode: TNode<ConcreteDocument = Self>;
/// Get this document as a `TNode`.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns whether this document is an HTML document.
fn is_html_document(&self) -> bool;
/// Returns the quirks mode of this document.
fn quirks_mode(&self) -> QuirksMode;
/// Get a list of elements with a given ID in this document, sorted by
/// document position.
///
/// Can return an error to signal that this list is not available, or also
/// return an empty slice.
fn elements_with_id(
&self,
_id: &Atom,
) -> Result<&[<Self::ConcreteNode as TNode>::ConcreteElement], ()> {
Err(())
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo + PartialEq {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// The concrete `TDocument` type.
type ConcreteDocument: TDocument<ConcreteNode = Self>;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's first child.
fn first_child(&self) -> Option<Self>;
/// Get this node's first child.
fn last_child(&self) -> Option<Self>;
/// Get this node's previous sibling.
fn prev_sibling(&self) -> Option<Self>;
/// Get this node's next sibling.
fn next_sibling(&self) -> Option<Self>;
/// Get the owner document of this node.
fn owner_doc(&self) -> Self::ConcreteDocument;
/// Iterate over the DOM children of a node.
fn dom_children(&self) -> DomChildren<Self> {
DomChildren(self.first_child())
}
/// Returns whether the node is attached to a document.
fn is_in_document(&self) -> bool;
/// Iterate over the DOM children of a node, in preorder.
fn dom_descendants(&self) -> DomDescendants<Self> {
DomDescendants {
previous: Some(*self),
scope: *self,
}
}
/// Returns the next children in pre-order, optionally scoped to a subtree
/// root.
#[inline]
fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> {
if let Some(c) = self.first_child() {
return Some(c);
}
if Some(*self) == scoped_to {
return None;
}
let mut current = *self;
loop {
if let Some(s) = current.next_sibling() {
return Some(s);
}
let parent = current.parent_node();
if parent == scoped_to {
return None;
}
current = parent.expect("Not a descendant of the scope?");
}
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Get this node as a document, if it's one.
fn as_document(&self) -> Option<Self::ConcreteDocument>;
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
#[cfg(feature = "servo")]
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
#[cfg(feature = "servo")]
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
#[cfg(feature = "servo")]
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// The style scope of this element is a node that represents which rules
/// apply to the element.
///
/// In Servo, where we don't know about Shadow DOM or XBL, the style scope
/// is always the document.
fn style_scope(&self) -> Self::ConcreteNode {
self.as_node().owner_doc().as_node()
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(TraversalFlags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in
|
}
|
random_line_split
|
dom.rs
|
Some(n) => {
// Filter out nodes that layout should ignore.
if n.is_text_node() || n.is_element() {
return Some(n)
}
}
None => return None,
}
}
}
}
/// An iterator over the DOM children of a node.
pub struct DomChildren<N>(Option<N>);
impl<N> Iterator for DomChildren<N>
where
N: TNode
{
type Item = N;
fn next(&mut self) -> Option<N> {
match self.0.take() {
Some(n) => {
self.0 = n.next_sibling();
Some(n)
}
None => None,
}
}
}
/// An iterator over the DOM descendants of a node in pre-order.
pub struct DomDescendants<N> {
previous: Option<N>,
scope: N,
}
impl<N> Iterator for DomDescendants<N>
where
N: TNode
{
type Item = N;
#[inline]
fn next(&mut self) -> Option<N> {
let prev = match self.previous.take() {
None => return None,
Some(n) => n,
};
self.previous = prev.next_in_preorder(Some(self.scope));
self.previous
}
}
/// The `TDocument` trait, to represent a document node.
pub trait TDocument : Sized + Copy + Clone {
/// The concrete `TNode` type.
type ConcreteNode: TNode<ConcreteDocument = Self>;
/// Get this document as a `TNode`.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns whether this document is an HTML document.
fn is_html_document(&self) -> bool;
/// Returns the quirks mode of this document.
fn quirks_mode(&self) -> QuirksMode;
/// Get a list of elements with a given ID in this document, sorted by
/// document position.
///
/// Can return an error to signal that this list is not available, or also
/// return an empty slice.
fn elements_with_id(
&self,
_id: &Atom,
) -> Result<&[<Self::ConcreteNode as TNode>::ConcreteElement], ()> {
Err(())
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo + PartialEq {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// The concrete `TDocument` type.
type ConcreteDocument: TDocument<ConcreteNode = Self>;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's first child.
fn first_child(&self) -> Option<Self>;
/// Get this node's first child.
fn last_child(&self) -> Option<Self>;
/// Get this node's previous sibling.
fn prev_sibling(&self) -> Option<Self>;
/// Get this node's next sibling.
fn next_sibling(&self) -> Option<Self>;
/// Get the owner document of this node.
fn owner_doc(&self) -> Self::ConcreteDocument;
/// Iterate over the DOM children of a node.
fn dom_children(&self) -> DomChildren<Self> {
DomChildren(self.first_child())
}
/// Returns whether the node is attached to a document.
fn is_in_document(&self) -> bool;
/// Iterate over the DOM children of a node, in preorder.
fn dom_descendants(&self) -> DomDescendants<Self> {
DomDescendants {
previous: Some(*self),
scope: *self,
}
}
/// Returns the next children in pre-order, optionally scoped to a subtree
/// root.
#[inline]
fn next_in_preorder(&self, scoped_to: Option<Self>) -> Option<Self> {
if let Some(c) = self.first_child() {
return Some(c);
}
if Some(*self) == scoped_to {
return None;
}
let mut current = *self;
loop {
if let Some(s) = current.next_sibling() {
return Some(s);
}
let parent = current.parent_node();
if parent == scoped_to {
return None;
}
current = parent.expect("Not a descendant of the scope?");
}
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Get this node as a document, if it's one.
fn as_document(&self) -> Option<Self::ConcreteDocument>;
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
#[cfg(feature = "servo")]
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
#[cfg(feature = "servo")]
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
#[cfg(feature = "servo")]
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// The style scope of this element is a node that represents which rules
/// apply to the element.
///
/// In Servo, where we don't know about Shadow DOM or XBL, the style scope
/// is always the document.
fn style_scope(&self) -> Self::ConcreteNode {
self.as_node().owner_doc().as_node()
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self>
|
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(TraversalFlags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do
|
{
unreachable!("Servo doesn't know about NAC");
}
|
identifier_body
|
codemap.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.
/*!
The CodeMap tracks all the source code used within a single crate, mapping
from integer byte positions to the original source code location. Each bit of
source parsed during crate parsing (typically files, in-memory strings, or
various bits of macro expansion) cover a continuous range of bytes in the
CodeMap and are represented by FileMaps. Byte positions are stored in `spans`
and used pervasively in the compiler. They are absolute positions within the
CodeMap, which upon request can be converted to line and column information,
source code snippets, etc.
*/
use std::cmp;
use extra::serialize::{Encodable, Decodable, Encoder, Decoder};
pub trait Pos {
fn from_uint(n: uint) -> Self;
fn to_uint(&self) -> uint;
}
/// A byte offset. Keep this small (currently 32-bits), as AST contains
/// a lot of them.
#[deriving(Clone, Eq, IterBytes, Ord)]
pub struct BytePos(u32);
/// A character offset. Because of multibyte utf8 characters, a byte offset
/// is not equivalent to a character offset. The CodeMap will convert BytePos
/// values to CharPos values as necessary.
#[deriving(Eq,IterBytes, Ord)]
pub struct CharPos(uint);
// XXX: Lots of boilerplate in these impls, but so far my attempts to fix
// have been unsuccessful
impl Pos for BytePos {
fn from_uint(n: uint) -> BytePos { BytePos(n as u32) }
fn to_uint(&self) -> uint { **self as uint }
}
impl Add<BytePos, BytePos> for BytePos {
fn add(&self, rhs: &BytePos) -> BytePos {
BytePos(**self + **rhs)
}
}
impl Sub<BytePos, BytePos> for BytePos {
fn sub(&self, rhs: &BytePos) -> BytePos {
BytePos(**self - **rhs)
}
}
impl Pos for CharPos {
fn from_uint(n: uint) -> CharPos { CharPos(n) }
fn to_uint(&self) -> uint { **self }
}
impl Add<CharPos,CharPos> for CharPos {
fn add(&self, rhs: &CharPos) -> CharPos {
CharPos(**self + **rhs)
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(**self - **rhs)
}
}
/**
Spans represent a region of code, used for error reporting. Positions in spans
are *absolute* positions from the beginning of the codemap, not positions
relative to FileMaps. Methods on the CodeMap can be used to relate spans back
to the original source.
*/
#[deriving(Clone, IterBytes)]
pub struct Span {
lo: BytePos,
hi: BytePos,
expn_info: Option<@ExpnInfo>
}
#[deriving(Clone, Eq, Encodable, Decodable, IterBytes)]
pub struct Spanned<T> {
node: T,
span: Span,
}
impl cmp::Eq for Span {
fn eq(&self, other: &Span) -> bool {
return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
}
fn ne(&self, other: &Span) -> bool {!(*self).eq(other) }
}
impl<S:Encoder> Encodable<S> for Span {
/* Note #1972 -- spans are encoded but not decoded */
fn encode(&self, s: &mut S) {
s.emit_nil()
}
}
impl<D:Decoder> Decodable<D> for Span {
fn decode(_d: &mut D) -> Span {
dummy_sp()
}
}
pub fn
|
<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
respan(mk_sp(lo, hi), t)
}
pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
Spanned {node: t, span: sp}
}
pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
respan(dummy_sp(), t)
}
/* assuming that we're not in macro expansion */
pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
Span {lo: lo, hi: hi, expn_info: None}
}
// make this a const, once the compiler supports it
pub fn dummy_sp() -> Span { return mk_sp(BytePos(0), BytePos(0)); }
/// A source code location used for error reporting
pub struct Loc {
/// Information about the original source
file: @FileMap,
/// The (1-based) line number
line: uint,
/// The (0-based) column offset
col: CharPos
}
/// A source code location used as the result of lookup_char_pos_adj
// Actually, *none* of the clients use the filename *or* file field;
// perhaps they should just be removed.
pub struct LocWithOpt {
filename: FileName,
line: uint,
col: CharPos,
file: Option<@FileMap>,
}
// used to be structural records. Better names, anyone?
pub struct FileMapAndLine {fm: @FileMap, line: uint}
pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos}
#[deriving(IterBytes)]
pub enum MacroFormat {
// e.g. #[deriving(...)] <item>
MacroAttribute,
// e.g. `format!()`
MacroBang
}
#[deriving(IterBytes)]
pub struct NameAndSpan {
name: @str,
// the format with which the macro was invoked.
format: MacroFormat,
span: Option<Span>
}
/// Extra information for tracking macro expansion of spans
#[deriving(IterBytes)]
pub struct ExpnInfo {
call_site: Span,
callee: NameAndSpan
}
pub type FileName = @str;
pub struct FileLines
{
file: @FileMap,
lines: ~[uint]
}
// represents the origin of a file:
pub enum FileSubstr {
// indicates that this is a normal standalone file:
FssNone,
// indicates that this "file" is actually a substring
// of another file that appears earlier in the codemap
FssInternal(Span),
}
/// Identifies an offset of a multi-byte character in a FileMap
pub struct MultiByteChar {
/// The absolute offset of the character in the CodeMap
pos: BytePos,
/// The number of bytes, >=2
bytes: uint,
}
/// A single source in the CodeMap
pub struct FileMap {
/// The name of the file that the source came from, source that doesn't
/// originate from files has names between angle brackets by convention,
/// e.g. `<anon>`
name: FileName,
/// Extra information used by qquote
substr: FileSubstr,
/// The complete source code
src: @str,
/// The start position of this source in the CodeMap
start_pos: BytePos,
/// Locations of lines beginnings in the source code
lines: @mut ~[BytePos],
/// Locations of multi-byte characters in the source code
multibyte_chars: @mut ~[MultiByteChar],
}
impl FileMap {
// EFFECT: register a start-of-line offset in the
// table of line-beginnings.
// UNCHECKED INVARIANT: these offsets must be added in the right
// order and must be in the right places; there is shared knowledge
// about what ends a line between this file and parse.rs
pub fn next_line(&self, pos: BytePos) {
// the new charpos must be > the last one (or it's the first one).
let lines = &mut *self.lines;
assert!((lines.len() == 0) || (lines[lines.len() - 1] < pos))
lines.push(pos);
}
// get a line from the list of pre-computed line-beginnings
pub fn get_line(&self, line: int) -> ~str {
let begin: BytePos = self.lines[line] - self.start_pos;
let begin = begin.to_uint();
let slice = self.src.slice_from(begin);
match slice.find('\n') {
Some(e) => slice.slice_to(e).to_owned(),
None => slice.to_owned()
}
}
pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) {
assert!(bytes >=2 && bytes <= 4);
let mbc = MultiByteChar {
pos: pos,
bytes: bytes,
};
self.multibyte_chars.push(mbc);
}
}
pub struct CodeMap {
files: @mut ~[@FileMap]
}
impl CodeMap {
pub fn new() -> CodeMap {
CodeMap {
files: @mut ~[],
}
}
/// Add a new FileMap to the CodeMap and return it
pub fn new_filemap(&self, filename: FileName, src: @str) -> @FileMap {
return self.new_filemap_w_substr(filename, FssNone, src);
}
pub fn new_filemap_w_substr(&self,
filename: FileName,
substr: FileSubstr,
src: @str)
-> @FileMap {
let files = &mut *self.files;
let start_pos = if files.len() == 0 {
0
} else {
let last_start = files.last().start_pos.to_uint();
let last_len = files.last().src.len();
last_start + last_len
};
let filemap = @FileMap {
name: filename, substr: substr, src: src,
start_pos: Pos::from_uint(start_pos),
lines: @mut ~[],
multibyte_chars: @mut ~[],
};
files.push(filemap);
return filemap;
}
pub fn mk_substr_filename(&self, sp: Span) -> ~str {
let pos = self.lookup_char_pos(sp.lo);
return format!("<{}:{}:{}>", pos.file.name,
pos.line, pos.col.to_uint());
}
/// Lookup source information about a BytePos
pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
return self.lookup_pos(pos);
}
pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
let loc = self.lookup_char_pos(pos);
match (loc.file.substr) {
FssNone =>
LocWithOpt {
filename: loc.file.name,
line: loc.line,
col: loc.col,
file: Some(loc.file)},
FssInternal(sp) =>
self.lookup_char_pos_adj(
sp.lo + (pos - loc.file.start_pos)),
}
}
pub fn adjust_span(&self, sp: Span) -> Span {
let line = self.lookup_line(sp.lo);
match (line.fm.substr) {
FssNone => sp,
FssInternal(s) => {
self.adjust_span(Span {
lo: s.lo + (sp.lo - line.fm.start_pos),
hi: s.lo + (sp.hi - line.fm.start_pos),
expn_info: sp.expn_info
})
}
}
}
pub fn span_to_str(&self, sp: Span) -> ~str {
let files = &*self.files;
if files.len() == 0 && sp == dummy_sp() {
return ~"no-location";
}
let lo = self.lookup_char_pos_adj(sp.lo);
let hi = self.lookup_char_pos_adj(sp.hi);
return format!("{}:{}:{}: {}:{}", lo.filename,
lo.line, lo.col.to_uint(), hi.line, hi.col.to_uint())
}
pub fn span_to_filename(&self, sp: Span) -> FileName {
let lo = self.lookup_char_pos(sp.lo);
lo.file.name
}
pub fn span_to_lines(&self, sp: Span) -> @FileLines {
let lo = self.lookup_char_pos(sp.lo);
let hi = self.lookup_char_pos(sp.hi);
let mut lines = ~[];
for i in range(lo.line - 1u, hi.line as uint) {
lines.push(i);
};
return @FileLines {file: lo.file, lines: lines};
}
pub fn span_to_snippet(&self, sp: Span) -> Option<~str> {
let begin = self.lookup_byte_offset(sp.lo);
let end = self.lookup_byte_offset(sp.hi);
// FIXME #8256: this used to be an assert but whatever precondition
// it's testing isn't true for all spans in the AST, so to allow the
// caller to not have to fail (and it can't catch it since the CodeMap
// isn't sendable), return None
if begin.fm.start_pos!= end.fm.start_pos {
None
} else {
Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned())
}
}
pub fn get_filemap(&self, filename: &str) -> @FileMap {
for fm in self.files.iter() { if filename == fm.name { return *fm; } }
//XXjdm the following triggers a mismatched type bug
// (or expected function, found _|_)
fail!(); // ("asking for " + filename + " which we don't know about");
}
}
impl CodeMap {
fn lookup_filemap_idx(&self, pos: BytePos) -> uint {
let files = &*self.files;
let len = files.len();
let mut a = 0u;
let mut b = len;
while b - a > 1u {
let m = (a + b) / 2u;
if self.files[m].start_pos > pos {
b = m;
} else {
a = m;
}
}
if (a >= len) {
fail!("position {} does not resolve to a source location", pos.to_uint())
}
return a;
}
fn lookup_line(&self, pos: BytePos) -> FileMapAndLine
{
let idx = self.lookup_filemap_idx(pos);
let f = self.files[idx];
let mut a = 0u;
let lines = &*f.lines;
let mut b = lines.len();
while b - a > 1u {
let m = (a + b) / 2u;
if lines[m] > pos { b = m; } else { a = m; }
}
return FileMapAndLine {fm: f, line: a};
}
fn lookup_pos(&self, pos: BytePos) -> Loc {
let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos);
let line = a + 1u; // Line numbers start at 1
let chpos = self.bytepos_to_local_charpos(pos);
let linebpos = f.lines[a];
let linechpos = self.bytepos_to_local_charpos(linebpos);
debug!("codemap: byte pos {:?} is on the line at byte pos {:?}",
pos, linebpos);
debug!("codemap: char pos {:?} is on the line at char pos {:?}",
chpos, linechpos);
debug!("codemap: byte is on line: {:?}", line);
assert!(chpos >= linechpos);
return Loc {
file: f,
line: line,
col: chpos - linechpos
};
}
fn lookup_byte_offset(&self, bpos: BytePos)
-> FileMapAndBytePos {
let idx = self.lookup_filemap_idx(bpos);
let fm = self.files[idx];
let offset = bpos - fm.start_pos;
return FileMapAndBytePos {fm: fm, pos: offset};
}
// Converts an absolute BytePos to a CharPos relative to the file it is
// located in
fn bytepos_to_local_charpos(&self, bpos: BytePos) -> CharPos {
debug!("codemap: converting {:?} to char pos", bpos);
let idx = self.lookup_filemap_idx(bpos);
let map = self.files[idx];
// The number of extra bytes due to multibyte chars in the FileMap
let mut total_extra_bytes = 0;
for mbc in map.multibyte_chars.iter() {
debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos);
if mbc.pos < bpos {
total_extra_bytes += mbc.bytes;
// We should never see a byte position in the middle of a
// character
assert!(bpos == mbc.pos
|| bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes);
} else {
break;
}
}
CharPos(bpos.to_uint() - total_extra_bytes)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn t1 () {
let cm = CodeMap::new();
let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line");
fm.next_line(BytePos(0));
assert_eq!(&fm.get_line(0),&~"first line.");
// TESTING BROKEN BEHAVIOR:
fm.next_line(BytePos(10));
assert_eq!(&fm.get_line(1),&~".");
}
#[test]
#[should_fail]
fn t2 () {
let cm = CodeMap::new();
let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line");
// TESTING *REALLY* BROKEN BEHAVIOR:
fm.next_line(BytePos(0));
fm.next_line(BytePos(10));
fm.next_line(BytePos(2));
}
}
|
spanned
|
identifier_name
|
codemap.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.
/*!
The CodeMap tracks all the source code used within a single crate, mapping
from integer byte positions to the original source code location. Each bit of
source parsed during crate parsing (typically files, in-memory strings, or
various bits of macro expansion) cover a continuous range of bytes in the
CodeMap and are represented by FileMaps. Byte positions are stored in `spans`
and used pervasively in the compiler. They are absolute positions within the
CodeMap, which upon request can be converted to line and column information,
source code snippets, etc.
*/
use std::cmp;
use extra::serialize::{Encodable, Decodable, Encoder, Decoder};
pub trait Pos {
fn from_uint(n: uint) -> Self;
fn to_uint(&self) -> uint;
}
/// A byte offset. Keep this small (currently 32-bits), as AST contains
/// a lot of them.
#[deriving(Clone, Eq, IterBytes, Ord)]
pub struct BytePos(u32);
/// A character offset. Because of multibyte utf8 characters, a byte offset
/// is not equivalent to a character offset. The CodeMap will convert BytePos
/// values to CharPos values as necessary.
#[deriving(Eq,IterBytes, Ord)]
pub struct CharPos(uint);
// XXX: Lots of boilerplate in these impls, but so far my attempts to fix
// have been unsuccessful
impl Pos for BytePos {
fn from_uint(n: uint) -> BytePos { BytePos(n as u32) }
fn to_uint(&self) -> uint { **self as uint }
}
impl Add<BytePos, BytePos> for BytePos {
fn add(&self, rhs: &BytePos) -> BytePos {
BytePos(**self + **rhs)
}
}
impl Sub<BytePos, BytePos> for BytePos {
fn sub(&self, rhs: &BytePos) -> BytePos {
BytePos(**self - **rhs)
}
}
impl Pos for CharPos {
fn from_uint(n: uint) -> CharPos { CharPos(n) }
fn to_uint(&self) -> uint { **self }
}
impl Add<CharPos,CharPos> for CharPos {
fn add(&self, rhs: &CharPos) -> CharPos {
CharPos(**self + **rhs)
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(**self - **rhs)
}
}
/**
Spans represent a region of code, used for error reporting. Positions in spans
are *absolute* positions from the beginning of the codemap, not positions
relative to FileMaps. Methods on the CodeMap can be used to relate spans back
to the original source.
*/
#[deriving(Clone, IterBytes)]
pub struct Span {
lo: BytePos,
hi: BytePos,
expn_info: Option<@ExpnInfo>
}
#[deriving(Clone, Eq, Encodable, Decodable, IterBytes)]
pub struct Spanned<T> {
node: T,
span: Span,
}
impl cmp::Eq for Span {
fn eq(&self, other: &Span) -> bool {
return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
}
fn ne(&self, other: &Span) -> bool {!(*self).eq(other) }
}
impl<S:Encoder> Encodable<S> for Span {
/* Note #1972 -- spans are encoded but not decoded */
fn encode(&self, s: &mut S) {
s.emit_nil()
}
}
impl<D:Decoder> Decodable<D> for Span {
fn decode(_d: &mut D) -> Span {
dummy_sp()
}
}
pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
respan(mk_sp(lo, hi), t)
}
pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
Spanned {node: t, span: sp}
}
pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
respan(dummy_sp(), t)
}
/* assuming that we're not in macro expansion */
pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
Span {lo: lo, hi: hi, expn_info: None}
}
// make this a const, once the compiler supports it
pub fn dummy_sp() -> Span { return mk_sp(BytePos(0), BytePos(0)); }
/// A source code location used for error reporting
pub struct Loc {
/// Information about the original source
file: @FileMap,
/// The (1-based) line number
line: uint,
/// The (0-based) column offset
col: CharPos
}
/// A source code location used as the result of lookup_char_pos_adj
// Actually, *none* of the clients use the filename *or* file field;
// perhaps they should just be removed.
pub struct LocWithOpt {
filename: FileName,
line: uint,
col: CharPos,
file: Option<@FileMap>,
}
// used to be structural records. Better names, anyone?
pub struct FileMapAndLine {fm: @FileMap, line: uint}
pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos}
#[deriving(IterBytes)]
pub enum MacroFormat {
// e.g. #[deriving(...)] <item>
MacroAttribute,
// e.g. `format!()`
MacroBang
}
#[deriving(IterBytes)]
pub struct NameAndSpan {
name: @str,
// the format with which the macro was invoked.
format: MacroFormat,
span: Option<Span>
}
/// Extra information for tracking macro expansion of spans
#[deriving(IterBytes)]
pub struct ExpnInfo {
call_site: Span,
callee: NameAndSpan
}
pub type FileName = @str;
pub struct FileLines
{
file: @FileMap,
lines: ~[uint]
}
// represents the origin of a file:
pub enum FileSubstr {
// indicates that this is a normal standalone file:
FssNone,
// indicates that this "file" is actually a substring
// of another file that appears earlier in the codemap
FssInternal(Span),
}
/// Identifies an offset of a multi-byte character in a FileMap
pub struct MultiByteChar {
/// The absolute offset of the character in the CodeMap
pos: BytePos,
/// The number of bytes, >=2
bytes: uint,
}
/// A single source in the CodeMap
pub struct FileMap {
/// The name of the file that the source came from, source that doesn't
/// originate from files has names between angle brackets by convention,
/// e.g. `<anon>`
name: FileName,
/// Extra information used by qquote
substr: FileSubstr,
/// The complete source code
src: @str,
/// The start position of this source in the CodeMap
start_pos: BytePos,
/// Locations of lines beginnings in the source code
lines: @mut ~[BytePos],
/// Locations of multi-byte characters in the source code
multibyte_chars: @mut ~[MultiByteChar],
}
impl FileMap {
// EFFECT: register a start-of-line offset in the
// table of line-beginnings.
// UNCHECKED INVARIANT: these offsets must be added in the right
// order and must be in the right places; there is shared knowledge
// about what ends a line between this file and parse.rs
pub fn next_line(&self, pos: BytePos) {
// the new charpos must be > the last one (or it's the first one).
let lines = &mut *self.lines;
assert!((lines.len() == 0) || (lines[lines.len() - 1] < pos))
lines.push(pos);
}
// get a line from the list of pre-computed line-beginnings
pub fn get_line(&self, line: int) -> ~str {
let begin: BytePos = self.lines[line] - self.start_pos;
let begin = begin.to_uint();
let slice = self.src.slice_from(begin);
match slice.find('\n') {
Some(e) => slice.slice_to(e).to_owned(),
None => slice.to_owned()
}
}
pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) {
assert!(bytes >=2 && bytes <= 4);
let mbc = MultiByteChar {
pos: pos,
bytes: bytes,
};
self.multibyte_chars.push(mbc);
}
}
pub struct CodeMap {
files: @mut ~[@FileMap]
}
impl CodeMap {
pub fn new() -> CodeMap {
CodeMap {
files: @mut ~[],
}
}
/// Add a new FileMap to the CodeMap and return it
pub fn new_filemap(&self, filename: FileName, src: @str) -> @FileMap {
return self.new_filemap_w_substr(filename, FssNone, src);
}
pub fn new_filemap_w_substr(&self,
filename: FileName,
substr: FileSubstr,
src: @str)
-> @FileMap {
let files = &mut *self.files;
let start_pos = if files.len() == 0 {
0
} else {
let last_start = files.last().start_pos.to_uint();
let last_len = files.last().src.len();
last_start + last_len
};
let filemap = @FileMap {
name: filename, substr: substr, src: src,
start_pos: Pos::from_uint(start_pos),
lines: @mut ~[],
multibyte_chars: @mut ~[],
};
files.push(filemap);
return filemap;
}
pub fn mk_substr_filename(&self, sp: Span) -> ~str {
let pos = self.lookup_char_pos(sp.lo);
return format!("<{}:{}:{}>", pos.file.name,
pos.line, pos.col.to_uint());
}
/// Lookup source information about a BytePos
pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
return self.lookup_pos(pos);
}
pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
let loc = self.lookup_char_pos(pos);
match (loc.file.substr) {
FssNone =>
LocWithOpt {
filename: loc.file.name,
line: loc.line,
col: loc.col,
file: Some(loc.file)},
FssInternal(sp) =>
self.lookup_char_pos_adj(
sp.lo + (pos - loc.file.start_pos)),
}
}
pub fn adjust_span(&self, sp: Span) -> Span {
let line = self.lookup_line(sp.lo);
match (line.fm.substr) {
FssNone => sp,
FssInternal(s) => {
self.adjust_span(Span {
lo: s.lo + (sp.lo - line.fm.start_pos),
hi: s.lo + (sp.hi - line.fm.start_pos),
expn_info: sp.expn_info
})
}
}
}
pub fn span_to_str(&self, sp: Span) -> ~str {
let files = &*self.files;
if files.len() == 0 && sp == dummy_sp() {
return ~"no-location";
}
let lo = self.lookup_char_pos_adj(sp.lo);
let hi = self.lookup_char_pos_adj(sp.hi);
return format!("{}:{}:{}: {}:{}", lo.filename,
lo.line, lo.col.to_uint(), hi.line, hi.col.to_uint())
}
pub fn span_to_filename(&self, sp: Span) -> FileName {
let lo = self.lookup_char_pos(sp.lo);
lo.file.name
}
pub fn span_to_lines(&self, sp: Span) -> @FileLines {
let lo = self.lookup_char_pos(sp.lo);
let hi = self.lookup_char_pos(sp.hi);
let mut lines = ~[];
for i in range(lo.line - 1u, hi.line as uint) {
lines.push(i);
};
return @FileLines {file: lo.file, lines: lines};
}
pub fn span_to_snippet(&self, sp: Span) -> Option<~str> {
let begin = self.lookup_byte_offset(sp.lo);
let end = self.lookup_byte_offset(sp.hi);
// FIXME #8256: this used to be an assert but whatever precondition
// it's testing isn't true for all spans in the AST, so to allow the
// caller to not have to fail (and it can't catch it since the CodeMap
// isn't sendable), return None
if begin.fm.start_pos!= end.fm.start_pos {
None
} else {
Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned())
}
}
pub fn get_filemap(&self, filename: &str) -> @FileMap {
for fm in self.files.iter() { if filename == fm.name { return *fm; } }
//XXjdm the following triggers a mismatched type bug
// (or expected function, found _|_)
fail!(); // ("asking for " + filename + " which we don't know about");
}
}
impl CodeMap {
fn lookup_filemap_idx(&self, pos: BytePos) -> uint {
let files = &*self.files;
let len = files.len();
let mut a = 0u;
let mut b = len;
while b - a > 1u {
let m = (a + b) / 2u;
if self.files[m].start_pos > pos {
b = m;
} else {
a = m;
}
}
if (a >= len) {
fail!("position {} does not resolve to a source location", pos.to_uint())
}
return a;
}
fn lookup_line(&self, pos: BytePos) -> FileMapAndLine
{
let idx = self.lookup_filemap_idx(pos);
let f = self.files[idx];
let mut a = 0u;
let lines = &*f.lines;
let mut b = lines.len();
while b - a > 1u {
let m = (a + b) / 2u;
if lines[m] > pos { b = m; } else { a = m; }
}
return FileMapAndLine {fm: f, line: a};
}
fn lookup_pos(&self, pos: BytePos) -> Loc {
let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos);
let line = a + 1u; // Line numbers start at 1
|
let linebpos = f.lines[a];
let linechpos = self.bytepos_to_local_charpos(linebpos);
debug!("codemap: byte pos {:?} is on the line at byte pos {:?}",
pos, linebpos);
debug!("codemap: char pos {:?} is on the line at char pos {:?}",
chpos, linechpos);
debug!("codemap: byte is on line: {:?}", line);
assert!(chpos >= linechpos);
return Loc {
file: f,
line: line,
col: chpos - linechpos
};
}
fn lookup_byte_offset(&self, bpos: BytePos)
-> FileMapAndBytePos {
let idx = self.lookup_filemap_idx(bpos);
let fm = self.files[idx];
let offset = bpos - fm.start_pos;
return FileMapAndBytePos {fm: fm, pos: offset};
}
// Converts an absolute BytePos to a CharPos relative to the file it is
// located in
fn bytepos_to_local_charpos(&self, bpos: BytePos) -> CharPos {
debug!("codemap: converting {:?} to char pos", bpos);
let idx = self.lookup_filemap_idx(bpos);
let map = self.files[idx];
// The number of extra bytes due to multibyte chars in the FileMap
let mut total_extra_bytes = 0;
for mbc in map.multibyte_chars.iter() {
debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos);
if mbc.pos < bpos {
total_extra_bytes += mbc.bytes;
// We should never see a byte position in the middle of a
// character
assert!(bpos == mbc.pos
|| bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes);
} else {
break;
}
}
CharPos(bpos.to_uint() - total_extra_bytes)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn t1 () {
let cm = CodeMap::new();
let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line");
fm.next_line(BytePos(0));
assert_eq!(&fm.get_line(0),&~"first line.");
// TESTING BROKEN BEHAVIOR:
fm.next_line(BytePos(10));
assert_eq!(&fm.get_line(1),&~".");
}
#[test]
#[should_fail]
fn t2 () {
let cm = CodeMap::new();
let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line");
// TESTING *REALLY* BROKEN BEHAVIOR:
fm.next_line(BytePos(0));
fm.next_line(BytePos(10));
fm.next_line(BytePos(2));
}
}
|
let chpos = self.bytepos_to_local_charpos(pos);
|
random_line_split
|
ipv4.rs
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
// XXX: On some platforms there might be
// unnatural padding between the fields. We
// should have a static assert that this size
// is actually correct.
// Offsets of the port and address. Same XXX applies.
const PORT_OFF: usize = 2;
const ADDR_OFF: usize = 4;
pub fn validate(bytes: &[u8]) -> Result<usize> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::InvalidArgument);
}
let mut family: sa_family_t = 0;
mem::copy(family.as_mut(), bytes);
match family as c_int {
AF_INET => Ok(IPV4_SOCK_ADDR_SIZE),
_ => Err(error::InvalidArgument),
}
}
/// An Ipv4 address.
#[derive(Pod, Eq)]
pub struct Ipv4Addr(pub u8, pub u8, pub u8, pub u8);
impl Ipv4Addr {
/// Creates a new Ipv4 address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the address.
pub fn from_bytes(bytes: [u8; 4]) -> Ipv4Addr {
Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3])
}
/// Creates a new Ipv4 address from a 32 bit integer in network byte order.
///
/// [argument, addr]
/// The address in network byte order.
pub fn from_be(addr: u32) -> Ipv4Addr {
unsafe { Ipv4Addr::from_bytes(mem::cast(addr)) }
}
/// Turns the address into an array of bytes.
pub fn to_bytes(self) -> [u8; 4] {
[self.0, self.1, self.2, self.3]
}
/// Turns the address into a 32 bit integer in network byte order.
pub fn to_be(self) -> u32 {
unsafe { mem::cast(self.to_bytes()) }
}
/// Compares the address to the current prefix `0.0.0.0/8`.
pub fn is_current(self) -> bool {
self.0 == 0
}
/// Compares the address to the privat prefixes.
///
/// = Remarks
///
/// The privat prefixes are `10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`.
pub fn is_private(self) -> bool {
(self.0 == 10) || (self.0 == 172 && self.1 & 0b1111_0000 == 16) ||
(self.0 == 192 && self.1 == 168)
}
/// Compares the address to the shared prefix `100.64.0.0/10`.
pub fn is_shared(self) -> bool {
self.0 == 100 && self.1 & 0b1100_0000 == 64
}
/// Compares the address to the loopback prefix `127.0.0.0/8`.
pub fn is_loopback(self) -> bool {
self.0 == 127
}
/// Compares the address to the link-local prefix `169.254.0.0/16`.
pub fn is_link_local(self) -> bool {
self.0 == 169 && self.1 == 254
}
/// Compares the address to the 6to4 prefix `192.88.99.0/24`.
pub fn is_6to4(self) -> bool {
self.0 == 192 && self.1 == 88 && self.2 == 99
}
/// Compares the address to the multicast prefix `224.0.0.0/4`.
pub fn is_multicast(self) -> bool {
self.0 & 0b1111_0000 == 224
}
/// Creates the broadcast address `255.255.255.255`.
pub fn broadcast() -> Ipv4Addr {
Ipv4Addr(255, 255, 255, 255)
}
/// Creates the unspecified address `0.0.0.0`.
pub fn any() -> Ipv4Addr {
Ipv4Addr(0, 0, 0, 0)
}
}
/// An Ipv4 socket address.
pub struct Ipv4SockAddr { data: [u8] }
impl Ipv4SockAddr {
/// Creates an Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_bytes(bytes: &[u8]) -> Result<&Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&bytes[..l]) })
}
/// Creates a mutable Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_mut_bytes(bytes: &mut [u8]) -> Result<&mut Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&mut bytes[..l]) })
}
/// Creates an Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a mutable Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_mut_bytes_unchecked(bytes: &mut [u8]) -> &mut Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a new Ipv4 socket address from an address and a port.
///
/// [argument, bytes]
/// The buffer in which the address will be stored.
///
/// [argument, addr]
/// The Ipv6 address of the socket.
///
/// [argument, port]
/// The port of the socket.
pub fn from_addr_port(bytes: &mut [u8], addr: Ipv4Addr,
port: u16) -> Result<&mut Ipv4SockAddr> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::NoMemory);
}
let addr = sockaddr_in {
sin_family: AF_INET as sa_family_t,
sin_port: port.to_be(),
sin_addr: in_addr { s_addr: addr.to_be() },
.. mem::zeroed()
};
mem::copy::<d8>(bytes.as_mut(), addr.as_ref());
Ok(unsafe { mem::cast(&mut bytes[..IPV4_SOCK_ADDR_SIZE]) })
}
/// Returns the Ipv4 address of the socket address.
pub fn addr(&self) -> Ipv4Addr {
let mut addr = 0;
mem::copy(addr.as_mut(), &self.data[ADDR_OFF..]);
Ipv4Addr::from_be(addr)
}
/// Sets the Ipv4 address of the socket address.
pub fn set_addr(&mut self, addr: Ipv4Addr) {
let addr = addr.to_be();
mem::copy(&mut self.data[ADDR_OFF..], addr.as_ref());
}
/// Returns the port of the socket address.
pub fn port(&self) -> u16 {
let mut port: u16 = 0;
mem::copy(port.as_mut(), &self.data[PORT_OFF..]);
port.from_be()
}
/// Sets the port of the socket address.
pub fn set_port(&mut self, port: u16) {
mem::copy(&mut self.data[PORT_OFF..], port.to_be().as_ref());
}
}
impl AsRef<[u8]> for Ipv4SockAddr {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
impl_try_as_ref!([u8], Ipv4SockAddr);
impl AsRef<SockAddr> for Ipv4SockAddr {
fn
|
(&self) -> &SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_ref!(SockAddr, Ipv4SockAddr);
impl AsMut<SockAddr> for Ipv4SockAddr {
fn as_mut(&mut self) -> &mut SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_mut!(SockAddr, Ipv4SockAddr);
impl Debug for Ipv4Addr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
write!(w, "{}.{}.{}.{}", self.0, self.1, self.2, self.3)
}
}
impl Debug for Ipv4SockAddr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
let addr = self.addr();
let port = self.port();
write!(w, "Ipv4SockAddr {{ {:?}:{} }}", addr, port)
}
}
|
as_ref
|
identifier_name
|
ipv4.rs
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
// XXX: On some platforms there might be
// unnatural padding between the fields. We
|
const PORT_OFF: usize = 2;
const ADDR_OFF: usize = 4;
pub fn validate(bytes: &[u8]) -> Result<usize> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::InvalidArgument);
}
let mut family: sa_family_t = 0;
mem::copy(family.as_mut(), bytes);
match family as c_int {
AF_INET => Ok(IPV4_SOCK_ADDR_SIZE),
_ => Err(error::InvalidArgument),
}
}
/// An Ipv4 address.
#[derive(Pod, Eq)]
pub struct Ipv4Addr(pub u8, pub u8, pub u8, pub u8);
impl Ipv4Addr {
/// Creates a new Ipv4 address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the address.
pub fn from_bytes(bytes: [u8; 4]) -> Ipv4Addr {
Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3])
}
/// Creates a new Ipv4 address from a 32 bit integer in network byte order.
///
/// [argument, addr]
/// The address in network byte order.
pub fn from_be(addr: u32) -> Ipv4Addr {
unsafe { Ipv4Addr::from_bytes(mem::cast(addr)) }
}
/// Turns the address into an array of bytes.
pub fn to_bytes(self) -> [u8; 4] {
[self.0, self.1, self.2, self.3]
}
/// Turns the address into a 32 bit integer in network byte order.
pub fn to_be(self) -> u32 {
unsafe { mem::cast(self.to_bytes()) }
}
/// Compares the address to the current prefix `0.0.0.0/8`.
pub fn is_current(self) -> bool {
self.0 == 0
}
/// Compares the address to the privat prefixes.
///
/// = Remarks
///
/// The privat prefixes are `10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`.
pub fn is_private(self) -> bool {
(self.0 == 10) || (self.0 == 172 && self.1 & 0b1111_0000 == 16) ||
(self.0 == 192 && self.1 == 168)
}
/// Compares the address to the shared prefix `100.64.0.0/10`.
pub fn is_shared(self) -> bool {
self.0 == 100 && self.1 & 0b1100_0000 == 64
}
/// Compares the address to the loopback prefix `127.0.0.0/8`.
pub fn is_loopback(self) -> bool {
self.0 == 127
}
/// Compares the address to the link-local prefix `169.254.0.0/16`.
pub fn is_link_local(self) -> bool {
self.0 == 169 && self.1 == 254
}
/// Compares the address to the 6to4 prefix `192.88.99.0/24`.
pub fn is_6to4(self) -> bool {
self.0 == 192 && self.1 == 88 && self.2 == 99
}
/// Compares the address to the multicast prefix `224.0.0.0/4`.
pub fn is_multicast(self) -> bool {
self.0 & 0b1111_0000 == 224
}
/// Creates the broadcast address `255.255.255.255`.
pub fn broadcast() -> Ipv4Addr {
Ipv4Addr(255, 255, 255, 255)
}
/// Creates the unspecified address `0.0.0.0`.
pub fn any() -> Ipv4Addr {
Ipv4Addr(0, 0, 0, 0)
}
}
/// An Ipv4 socket address.
pub struct Ipv4SockAddr { data: [u8] }
impl Ipv4SockAddr {
/// Creates an Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_bytes(bytes: &[u8]) -> Result<&Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&bytes[..l]) })
}
/// Creates a mutable Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_mut_bytes(bytes: &mut [u8]) -> Result<&mut Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&mut bytes[..l]) })
}
/// Creates an Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a mutable Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_mut_bytes_unchecked(bytes: &mut [u8]) -> &mut Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a new Ipv4 socket address from an address and a port.
///
/// [argument, bytes]
/// The buffer in which the address will be stored.
///
/// [argument, addr]
/// The Ipv6 address of the socket.
///
/// [argument, port]
/// The port of the socket.
pub fn from_addr_port(bytes: &mut [u8], addr: Ipv4Addr,
port: u16) -> Result<&mut Ipv4SockAddr> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::NoMemory);
}
let addr = sockaddr_in {
sin_family: AF_INET as sa_family_t,
sin_port: port.to_be(),
sin_addr: in_addr { s_addr: addr.to_be() },
.. mem::zeroed()
};
mem::copy::<d8>(bytes.as_mut(), addr.as_ref());
Ok(unsafe { mem::cast(&mut bytes[..IPV4_SOCK_ADDR_SIZE]) })
}
/// Returns the Ipv4 address of the socket address.
pub fn addr(&self) -> Ipv4Addr {
let mut addr = 0;
mem::copy(addr.as_mut(), &self.data[ADDR_OFF..]);
Ipv4Addr::from_be(addr)
}
/// Sets the Ipv4 address of the socket address.
pub fn set_addr(&mut self, addr: Ipv4Addr) {
let addr = addr.to_be();
mem::copy(&mut self.data[ADDR_OFF..], addr.as_ref());
}
/// Returns the port of the socket address.
pub fn port(&self) -> u16 {
let mut port: u16 = 0;
mem::copy(port.as_mut(), &self.data[PORT_OFF..]);
port.from_be()
}
/// Sets the port of the socket address.
pub fn set_port(&mut self, port: u16) {
mem::copy(&mut self.data[PORT_OFF..], port.to_be().as_ref());
}
}
impl AsRef<[u8]> for Ipv4SockAddr {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
impl_try_as_ref!([u8], Ipv4SockAddr);
impl AsRef<SockAddr> for Ipv4SockAddr {
fn as_ref(&self) -> &SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_ref!(SockAddr, Ipv4SockAddr);
impl AsMut<SockAddr> for Ipv4SockAddr {
fn as_mut(&mut self) -> &mut SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_mut!(SockAddr, Ipv4SockAddr);
impl Debug for Ipv4Addr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
write!(w, "{}.{}.{}.{}", self.0, self.1, self.2, self.3)
}
}
impl Debug for Ipv4SockAddr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
let addr = self.addr();
let port = self.port();
write!(w, "Ipv4SockAddr {{ {:?}:{} }}", addr, port)
}
}
|
// should have a static assert that this size
// is actually correct.
// Offsets of the port and address. Same XXX applies.
|
random_line_split
|
ipv4.rs
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
// XXX: On some platforms there might be
// unnatural padding between the fields. We
// should have a static assert that this size
// is actually correct.
// Offsets of the port and address. Same XXX applies.
const PORT_OFF: usize = 2;
const ADDR_OFF: usize = 4;
pub fn validate(bytes: &[u8]) -> Result<usize> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::InvalidArgument);
}
let mut family: sa_family_t = 0;
mem::copy(family.as_mut(), bytes);
match family as c_int {
AF_INET => Ok(IPV4_SOCK_ADDR_SIZE),
_ => Err(error::InvalidArgument),
}
}
/// An Ipv4 address.
#[derive(Pod, Eq)]
pub struct Ipv4Addr(pub u8, pub u8, pub u8, pub u8);
impl Ipv4Addr {
/// Creates a new Ipv4 address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the address.
pub fn from_bytes(bytes: [u8; 4]) -> Ipv4Addr {
Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3])
}
/// Creates a new Ipv4 address from a 32 bit integer in network byte order.
///
/// [argument, addr]
/// The address in network byte order.
pub fn from_be(addr: u32) -> Ipv4Addr {
unsafe { Ipv4Addr::from_bytes(mem::cast(addr)) }
}
/// Turns the address into an array of bytes.
pub fn to_bytes(self) -> [u8; 4]
|
/// Turns the address into a 32 bit integer in network byte order.
pub fn to_be(self) -> u32 {
unsafe { mem::cast(self.to_bytes()) }
}
/// Compares the address to the current prefix `0.0.0.0/8`.
pub fn is_current(self) -> bool {
self.0 == 0
}
/// Compares the address to the privat prefixes.
///
/// = Remarks
///
/// The privat prefixes are `10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`.
pub fn is_private(self) -> bool {
(self.0 == 10) || (self.0 == 172 && self.1 & 0b1111_0000 == 16) ||
(self.0 == 192 && self.1 == 168)
}
/// Compares the address to the shared prefix `100.64.0.0/10`.
pub fn is_shared(self) -> bool {
self.0 == 100 && self.1 & 0b1100_0000 == 64
}
/// Compares the address to the loopback prefix `127.0.0.0/8`.
pub fn is_loopback(self) -> bool {
self.0 == 127
}
/// Compares the address to the link-local prefix `169.254.0.0/16`.
pub fn is_link_local(self) -> bool {
self.0 == 169 && self.1 == 254
}
/// Compares the address to the 6to4 prefix `192.88.99.0/24`.
pub fn is_6to4(self) -> bool {
self.0 == 192 && self.1 == 88 && self.2 == 99
}
/// Compares the address to the multicast prefix `224.0.0.0/4`.
pub fn is_multicast(self) -> bool {
self.0 & 0b1111_0000 == 224
}
/// Creates the broadcast address `255.255.255.255`.
pub fn broadcast() -> Ipv4Addr {
Ipv4Addr(255, 255, 255, 255)
}
/// Creates the unspecified address `0.0.0.0`.
pub fn any() -> Ipv4Addr {
Ipv4Addr(0, 0, 0, 0)
}
}
/// An Ipv4 socket address.
pub struct Ipv4SockAddr { data: [u8] }
impl Ipv4SockAddr {
/// Creates an Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_bytes(bytes: &[u8]) -> Result<&Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&bytes[..l]) })
}
/// Creates a mutable Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_mut_bytes(bytes: &mut [u8]) -> Result<&mut Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&mut bytes[..l]) })
}
/// Creates an Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a mutable Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_mut_bytes_unchecked(bytes: &mut [u8]) -> &mut Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a new Ipv4 socket address from an address and a port.
///
/// [argument, bytes]
/// The buffer in which the address will be stored.
///
/// [argument, addr]
/// The Ipv6 address of the socket.
///
/// [argument, port]
/// The port of the socket.
pub fn from_addr_port(bytes: &mut [u8], addr: Ipv4Addr,
port: u16) -> Result<&mut Ipv4SockAddr> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::NoMemory);
}
let addr = sockaddr_in {
sin_family: AF_INET as sa_family_t,
sin_port: port.to_be(),
sin_addr: in_addr { s_addr: addr.to_be() },
.. mem::zeroed()
};
mem::copy::<d8>(bytes.as_mut(), addr.as_ref());
Ok(unsafe { mem::cast(&mut bytes[..IPV4_SOCK_ADDR_SIZE]) })
}
/// Returns the Ipv4 address of the socket address.
pub fn addr(&self) -> Ipv4Addr {
let mut addr = 0;
mem::copy(addr.as_mut(), &self.data[ADDR_OFF..]);
Ipv4Addr::from_be(addr)
}
/// Sets the Ipv4 address of the socket address.
pub fn set_addr(&mut self, addr: Ipv4Addr) {
let addr = addr.to_be();
mem::copy(&mut self.data[ADDR_OFF..], addr.as_ref());
}
/// Returns the port of the socket address.
pub fn port(&self) -> u16 {
let mut port: u16 = 0;
mem::copy(port.as_mut(), &self.data[PORT_OFF..]);
port.from_be()
}
/// Sets the port of the socket address.
pub fn set_port(&mut self, port: u16) {
mem::copy(&mut self.data[PORT_OFF..], port.to_be().as_ref());
}
}
impl AsRef<[u8]> for Ipv4SockAddr {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
impl_try_as_ref!([u8], Ipv4SockAddr);
impl AsRef<SockAddr> for Ipv4SockAddr {
fn as_ref(&self) -> &SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_ref!(SockAddr, Ipv4SockAddr);
impl AsMut<SockAddr> for Ipv4SockAddr {
fn as_mut(&mut self) -> &mut SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_mut!(SockAddr, Ipv4SockAddr);
impl Debug for Ipv4Addr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
write!(w, "{}.{}.{}.{}", self.0, self.1, self.2, self.3)
}
}
impl Debug for Ipv4SockAddr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
let addr = self.addr();
let port = self.port();
write!(w, "Ipv4SockAddr {{ {:?}:{} }}", addr, port)
}
}
|
{
[self.0, self.1, self.2, self.3]
}
|
identifier_body
|
ipv4.rs
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
// XXX: On some platforms there might be
// unnatural padding between the fields. We
// should have a static assert that this size
// is actually correct.
// Offsets of the port and address. Same XXX applies.
const PORT_OFF: usize = 2;
const ADDR_OFF: usize = 4;
pub fn validate(bytes: &[u8]) -> Result<usize> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE
|
let mut family: sa_family_t = 0;
mem::copy(family.as_mut(), bytes);
match family as c_int {
AF_INET => Ok(IPV4_SOCK_ADDR_SIZE),
_ => Err(error::InvalidArgument),
}
}
/// An Ipv4 address.
#[derive(Pod, Eq)]
pub struct Ipv4Addr(pub u8, pub u8, pub u8, pub u8);
impl Ipv4Addr {
/// Creates a new Ipv4 address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the address.
pub fn from_bytes(bytes: [u8; 4]) -> Ipv4Addr {
Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3])
}
/// Creates a new Ipv4 address from a 32 bit integer in network byte order.
///
/// [argument, addr]
/// The address in network byte order.
pub fn from_be(addr: u32) -> Ipv4Addr {
unsafe { Ipv4Addr::from_bytes(mem::cast(addr)) }
}
/// Turns the address into an array of bytes.
pub fn to_bytes(self) -> [u8; 4] {
[self.0, self.1, self.2, self.3]
}
/// Turns the address into a 32 bit integer in network byte order.
pub fn to_be(self) -> u32 {
unsafe { mem::cast(self.to_bytes()) }
}
/// Compares the address to the current prefix `0.0.0.0/8`.
pub fn is_current(self) -> bool {
self.0 == 0
}
/// Compares the address to the privat prefixes.
///
/// = Remarks
///
/// The privat prefixes are `10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`.
pub fn is_private(self) -> bool {
(self.0 == 10) || (self.0 == 172 && self.1 & 0b1111_0000 == 16) ||
(self.0 == 192 && self.1 == 168)
}
/// Compares the address to the shared prefix `100.64.0.0/10`.
pub fn is_shared(self) -> bool {
self.0 == 100 && self.1 & 0b1100_0000 == 64
}
/// Compares the address to the loopback prefix `127.0.0.0/8`.
pub fn is_loopback(self) -> bool {
self.0 == 127
}
/// Compares the address to the link-local prefix `169.254.0.0/16`.
pub fn is_link_local(self) -> bool {
self.0 == 169 && self.1 == 254
}
/// Compares the address to the 6to4 prefix `192.88.99.0/24`.
pub fn is_6to4(self) -> bool {
self.0 == 192 && self.1 == 88 && self.2 == 99
}
/// Compares the address to the multicast prefix `224.0.0.0/4`.
pub fn is_multicast(self) -> bool {
self.0 & 0b1111_0000 == 224
}
/// Creates the broadcast address `255.255.255.255`.
pub fn broadcast() -> Ipv4Addr {
Ipv4Addr(255, 255, 255, 255)
}
/// Creates the unspecified address `0.0.0.0`.
pub fn any() -> Ipv4Addr {
Ipv4Addr(0, 0, 0, 0)
}
}
/// An Ipv4 socket address.
pub struct Ipv4SockAddr { data: [u8] }
impl Ipv4SockAddr {
/// Creates an Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_bytes(bytes: &[u8]) -> Result<&Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&bytes[..l]) })
}
/// Creates a mutable Ipv4 socket address from given bytes.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub fn from_mut_bytes(bytes: &mut [u8]) -> Result<&mut Ipv4SockAddr> {
validate(bytes).map(|l| unsafe { mem::cast(&mut bytes[..l]) })
}
/// Creates an Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a mutable Ipv4 socket address from given bytes without validation.
///
/// [argument, bytes]
/// The bytes that contain the socket address.
pub unsafe fn from_mut_bytes_unchecked(bytes: &mut [u8]) -> &mut Ipv4SockAddr {
mem::cast(bytes)
}
/// Creates a new Ipv4 socket address from an address and a port.
///
/// [argument, bytes]
/// The buffer in which the address will be stored.
///
/// [argument, addr]
/// The Ipv6 address of the socket.
///
/// [argument, port]
/// The port of the socket.
pub fn from_addr_port(bytes: &mut [u8], addr: Ipv4Addr,
port: u16) -> Result<&mut Ipv4SockAddr> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::NoMemory);
}
let addr = sockaddr_in {
sin_family: AF_INET as sa_family_t,
sin_port: port.to_be(),
sin_addr: in_addr { s_addr: addr.to_be() },
.. mem::zeroed()
};
mem::copy::<d8>(bytes.as_mut(), addr.as_ref());
Ok(unsafe { mem::cast(&mut bytes[..IPV4_SOCK_ADDR_SIZE]) })
}
/// Returns the Ipv4 address of the socket address.
pub fn addr(&self) -> Ipv4Addr {
let mut addr = 0;
mem::copy(addr.as_mut(), &self.data[ADDR_OFF..]);
Ipv4Addr::from_be(addr)
}
/// Sets the Ipv4 address of the socket address.
pub fn set_addr(&mut self, addr: Ipv4Addr) {
let addr = addr.to_be();
mem::copy(&mut self.data[ADDR_OFF..], addr.as_ref());
}
/// Returns the port of the socket address.
pub fn port(&self) -> u16 {
let mut port: u16 = 0;
mem::copy(port.as_mut(), &self.data[PORT_OFF..]);
port.from_be()
}
/// Sets the port of the socket address.
pub fn set_port(&mut self, port: u16) {
mem::copy(&mut self.data[PORT_OFF..], port.to_be().as_ref());
}
}
impl AsRef<[u8]> for Ipv4SockAddr {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
impl_try_as_ref!([u8], Ipv4SockAddr);
impl AsRef<SockAddr> for Ipv4SockAddr {
fn as_ref(&self) -> &SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_ref!(SockAddr, Ipv4SockAddr);
impl AsMut<SockAddr> for Ipv4SockAddr {
fn as_mut(&mut self) -> &mut SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_mut!(SockAddr, Ipv4SockAddr);
impl Debug for Ipv4Addr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
write!(w, "{}.{}.{}.{}", self.0, self.1, self.2, self.3)
}
}
impl Debug for Ipv4SockAddr {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
let addr = self.addr();
let port = self.port();
write!(w, "Ipv4SockAddr {{ {:?}:{} }}", addr, port)
}
}
|
{
return Err(error::InvalidArgument);
}
|
conditional_block
|
data.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElement;
use invalidation::element::invalidator::InvalidationResult;
use invalidation::element::restyle_hints::RestyleHint;
#[cfg(feature = "gecko")]
use malloc_size_of::MallocSizeOfOps;
use properties::ComputedValues;
use properties::longhands::display::computed_value as display;
use rule_tree::StrongRuleNode;
use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage};
use selectors::NthIndexCache;
use servo_arc::Arc;
use shared_lock::StylesheetGuards;
use smallvec::SmallVec;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
bitflags! {
/// Various flags stored on ElementData.
#[derive(Default)]
pub struct ElementDataFlags: u8 {
/// Whether the styles changed for this restyle.
const WAS_RESTYLED = 1 << 0;
/// Whether the last traversal of this element did not do
/// any style computation. This is not true during the initial
/// styling pass, nor is it true when we restyle (in which case
/// WAS_RESTYLED is set).
///
/// This bit always corresponds to the last time the element was
/// traversed, so each traversal simply updates it with the appropriate
/// value.
const TRAVERSED_WITHOUT_STYLING = 1 << 1;
/// Whether we reframed/reconstructed any ancestor or self.
const ANCESTOR_WAS_RECONSTRUCTED = 1 << 2;
/// Whether the primary style of this element data was reused from another
/// element via a rule node comparison. This allows us to differentiate
/// between elements that shared styles because they met all the criteria
/// of the style sharing cache, compared to elements that reused style
|
}
}
/// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
///
/// We use an Arc so that sharing these styles via the style sharing cache does
/// not require duplicate allocations. We leverage the copy-on-write semantics of
/// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
/// in servo_arc.
#[derive(Clone, Debug, Default)]
pub struct EagerPseudoStyles(Option<Arc<EagerPseudoArray>>);
#[derive(Default)]
struct EagerPseudoArray(EagerPseudoArrayInner);
type EagerPseudoArrayInner = [Option<Arc<ComputedValues>>; EAGER_PSEUDO_COUNT];
impl Deref for EagerPseudoArray {
type Target = EagerPseudoArrayInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for EagerPseudoArray {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
// Manually implement `Clone` here because the derived impl of `Clone` for
// array types assumes the value inside is `Copy`.
impl Clone for EagerPseudoArray {
fn clone(&self) -> Self {
let mut clone = Self::default();
for i in 0..EAGER_PSEUDO_COUNT {
clone[i] = self.0[i].clone();
}
clone
}
}
// Override Debug to print which pseudos we have, and substitute the rule node
// for the much-more-verbose ComputedValues stringification.
impl fmt::Debug for EagerPseudoArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EagerPseudoArray {{ ")?;
for i in 0..EAGER_PSEUDO_COUNT {
if let Some(ref values) = self[i] {
write!(f, "{:?}: {:?}, ", PseudoElement::from_eager_index(i), &values.rules)?;
}
}
write!(f, "}}")
}
}
// Can't use [None; EAGER_PSEUDO_COUNT] here because it complains
// about Copy not being implemented for our Arc type.
#[cfg(feature = "gecko")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
#[cfg(feature = "servo")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None];
impl EagerPseudoStyles {
/// Returns whether there are any pseudo styles.
pub fn is_empty(&self) -> bool {
self.0.is_none()
}
/// Grabs a reference to the list of styles, if they exist.
pub fn as_optional_array(&self) -> Option<&EagerPseudoArrayInner> {
match self.0 {
None => None,
Some(ref x) => Some(&x.0),
}
}
/// Grabs a reference to the list of styles or a list of None if
/// there are no styles to be had.
pub fn as_array(&self) -> &EagerPseudoArrayInner {
self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
}
/// Returns a reference to the style for a given eager pseudo, if it exists.
pub fn get(&self, pseudo: &PseudoElement) -> Option<&Arc<ComputedValues>> {
debug_assert!(pseudo.is_eager());
self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref())
}
/// Sets the style for the eager pseudo.
pub fn set(&mut self, pseudo: &PseudoElement, value: Arc<ComputedValues>) {
if self.0.is_none() {
self.0 = Some(Arc::new(Default::default()));
}
let arr = Arc::make_mut(self.0.as_mut().unwrap());
arr[pseudo.eager_index()] = Some(value);
}
}
/// The styles associated with a node, including the styles for any
/// pseudo-elements.
#[derive(Clone, Default)]
pub struct ElementStyles {
/// The element's style.
pub primary: Option<Arc<ComputedValues>>,
/// A list of the styles for the element's eagerly-cascaded pseudo-elements.
pub pseudos: EagerPseudoStyles,
}
impl ElementStyles {
/// Returns the primary style.
pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
self.primary.as_ref()
}
/// Returns the primary style. Panic if no style available.
pub fn primary(&self) -> &Arc<ComputedValues> {
self.primary.as_ref().unwrap()
}
/// Whether this element `display` value is `none`.
pub fn is_display_none(&self) -> bool {
self.primary().get_box().clone_display() == display::T::none
}
#[cfg(feature = "gecko")]
fn size_of_excluding_cvs(&self, _ops: &mut MallocSizeOfOps) -> usize {
// As the method name suggests, we don't measures the ComputedValues
// here, because they are measured on the C++ side.
// XXX: measure the EagerPseudoArray itself, but not the ComputedValues
// within it.
0
}
}
// We manually implement Debug for ElementStyles so that we can avoid the
// verbose stringification of every property in the ComputedValues. We
// substitute the rule node instead.
impl fmt::Debug for ElementStyles {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
self.primary.as_ref().map(|x| &x.rules), self.pseudos)
}
}
/// Style system data associated with an Element.
///
/// In Gecko, this hangs directly off the Element. Servo, this is embedded
/// inside of layout data, which itself hangs directly off the Element. In
/// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety.
#[derive(Debug, Default)]
pub struct ElementData {
/// The styles for the element and its pseudo-elements.
pub styles: ElementStyles,
/// The restyle damage, indicating what kind of layout changes are required
/// afte restyling.
pub damage: RestyleDamage,
/// The restyle hint, which indicates whether selectors need to be rematched
/// for this element, its children, and its descendants.
pub hint: RestyleHint,
/// Flags.
pub flags: ElementDataFlags,
}
/// The kind of restyle that a single element should do.
#[derive(Debug)]
pub enum RestyleKind {
/// We need to run selector matching plus re-cascade, that is, a full
/// restyle.
MatchAndCascade,
/// We need to recascade with some replacement rule, such as the style
/// attribute, or animation rules.
CascadeWithReplacements(RestyleHint),
/// We only need to recascade, for example, because only inherited
/// properties in the parent changed.
CascadeOnly,
}
impl ElementData {
/// Invalidates style for this element, its descendants, and later siblings,
/// based on the snapshot of the element that we took when attributes or
/// state changed.
pub fn invalidate_style_if_needed<'a, E: TElement>(
&mut self,
element: E,
shared_context: &SharedStyleContext,
stack_limit_checker: Option<&StackLimitChecker>,
nth_index_cache: Option<&mut NthIndexCache>,
) -> InvalidationResult {
// In animation-only restyle we shouldn't touch snapshot at all.
if shared_context.traversal_flags.for_animation_only() {
return InvalidationResult::empty();
}
use invalidation::element::collector::StateAndAttrInvalidationProcessor;
use invalidation::element::invalidator::TreeStyleInvalidator;
debug!("invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
handled_snapshot: {}, pseudo: {:?}",
element,
shared_context.traversal_flags,
element.has_snapshot(),
element.handled_snapshot(),
element.implemented_pseudo_element());
if!element.has_snapshot() || element.handled_snapshot() {
return InvalidationResult::empty();
}
let mut xbl_stylists = SmallVec::<[_; 3]>::new();
let cut_off_inheritance =
element.each_xbl_stylist(|s| xbl_stylists.push(s));
let mut processor = StateAndAttrInvalidationProcessor::new(
shared_context,
&xbl_stylists,
cut_off_inheritance,
element,
self,
nth_index_cache,
);
let invalidator = TreeStyleInvalidator::new(
element,
stack_limit_checker,
&mut processor,
);
let result = invalidator.invalidate();
unsafe { element.set_handled_snapshot() }
debug_assert!(element.handled_snapshot());
result
}
/// Returns true if this element has styles.
#[inline]
pub fn has_styles(&self) -> bool {
self.styles.primary.is_some()
}
/// Returns this element's styles as resolved styles to use for sharing.
pub fn share_styles(&self) -> ResolvedElementStyles {
ResolvedElementStyles {
primary: self.share_primary_style(),
pseudos: self.styles.pseudos.clone(),
}
}
/// Returns this element's primary style as a resolved style to use for sharing.
pub fn share_primary_style(&self) -> PrimaryStyle {
let reused_via_rule_node =
self.flags.contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
PrimaryStyle {
style: ResolvedStyle(self.styles.primary().clone()),
reused_via_rule_node,
}
}
/// Sets a new set of styles, returning the old ones.
pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
if new_styles.primary.reused_via_rule_node {
self.flags.insert(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
} else {
self.flags.remove(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
}
mem::replace(&mut self.styles, new_styles.into())
}
/// Returns the kind of restyling that we're going to need to do on this
/// element, based of the stored restyle hint.
pub fn restyle_kind(
&self,
shared_context: &SharedStyleContext
) -> RestyleKind {
if shared_context.traversal_flags.for_animation_only() {
return self.restyle_kind_for_animation(shared_context);
}
if!self.has_styles() {
return RestyleKind::MatchAndCascade;
}
if self.hint.match_self() {
return RestyleKind::MatchAndCascade;
}
if self.hint.has_replacements() {
debug_assert!(!self.hint.has_animation_hint(),
"Animation only restyle hint should have already processed");
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::replacements());
}
debug_assert!(self.hint.has_recascade_self(),
"We definitely need to do something: {:?}!", self.hint);
return RestyleKind::CascadeOnly;
}
/// Returns the kind of restyling for animation-only restyle.
fn restyle_kind_for_animation(
&self,
shared_context: &SharedStyleContext,
) -> RestyleKind {
debug_assert!(shared_context.traversal_flags.for_animation_only());
debug_assert!(self.has_styles(),
"Unstyled element shouldn't be traversed during \
animation-only traversal");
// return either CascadeWithReplacements or CascadeOnly in case of
// animation-only restyle. I.e. animation-only restyle never does
// selector matching.
if self.hint.has_animation_hint() {
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::for_animations());
}
return RestyleKind::CascadeOnly;
}
/// Return true if important rules are different.
/// We use this to make sure the cascade of off-main thread animations is correct.
/// Note: Ignore custom properties for now because we only support opacity and transform
/// properties for animations running on compositor. Actually, we only care about opacity
/// and transform for now, but it's fine to compare all properties and let the user
/// the check which properties do they want.
/// If it costs too much, get_properties_overriding_animations() should return a set
/// containing only opacity and transform properties.
pub fn important_rules_are_different(
&self,
rules: &StrongRuleNode,
guards: &StylesheetGuards
) -> bool {
debug_assert!(self.has_styles());
let (important_rules, _custom) =
self.styles.primary().rules().get_properties_overriding_animations(&guards);
let (other_important_rules, _custom) = rules.get_properties_overriding_animations(&guards);
important_rules!= other_important_rules
}
/// Drops any restyle state from the element.
///
/// FIXME(bholley): The only caller of this should probably just assert that
/// the hint is empty and call clear_flags_and_damage().
#[inline]
pub fn clear_restyle_state(&mut self) {
self.hint = RestyleHint::empty();
self.clear_restyle_flags_and_damage();
}
/// Drops restyle flags and damage from the element.
#[inline]
pub fn clear_restyle_flags_and_damage(&mut self) {
self.damage = RestyleDamage::empty();
self.flags.remove(ElementDataFlags::WAS_RESTYLED | ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Returns whether this element or any ancestor is going to be
/// reconstructed.
pub fn reconstructed_self_or_ancestor(&self) -> bool {
self.reconstructed_ancestor() || self.reconstructed_self()
}
/// Returns whether this element is going to be reconstructed.
pub fn reconstructed_self(&self) -> bool {
self.damage.contains(RestyleDamage::reconstruct())
}
/// Returns whether any ancestor of this element is going to be
/// reconstructed.
fn reconstructed_ancestor(&self) -> bool {
self.flags.contains(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Sets the flag that tells us whether we've reconstructed an ancestor.
pub fn set_reconstructed_ancestor(&mut self, reconstructed: bool) {
if reconstructed {
// If it weren't for animation-only traversals, we could assert
// `!self.reconstructed_ancestor()` here.
self.flags.insert(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
} else {
self.flags.remove(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
}
}
/// Mark this element as restyled, which is useful to know whether we need
/// to do a post-traversal.
pub fn set_restyled(&mut self) {
self.flags.insert(ElementDataFlags::WAS_RESTYLED);
self.flags.remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns true if this element was restyled.
#[inline]
pub fn is_restyle(&self) -> bool {
self.flags.contains(ElementDataFlags::WAS_RESTYLED)
}
/// Mark that we traversed this element without computing any style for it.
pub fn set_traversed_without_styling(&mut self) {
self.flags.insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns whether the element was traversed without computing any style for
/// it.
pub fn traversed_without_styling(&self) -> bool {
self.flags.contains(ElementDataFlags::TRAVERSED_WITHOUT_STYLING)
}
/// Returns whether this element has been part of a restyle.
#[inline]
pub fn contains_restyle_data(&self) -> bool {
self.is_restyle() ||!self.hint.is_empty() ||!self.damage.is_empty()
}
/// If an ancestor is already getting reconstructed by Gecko's top-down
/// frame constructor, no need to apply damage. Similarly if we already
/// have an explicitly stored ReconstructFrame hint.
///
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1301258#c12
/// for followup work to make the optimization here more optimal by considering
/// each bit individually.
#[cfg(feature = "gecko")]
pub fn skip_applying_damage(&self) -> bool { self.reconstructed_self_or_ancestor() }
/// N/A in Servo.
#[cfg(feature = "servo")]
pub fn skip_applying_damage(&self) -> bool { false }
/// Returns whether it is safe to perform cousin sharing based on the ComputedValues
/// identity of the primary style in this ElementData. There are a few subtle things
/// to check.
///
/// First, if a parent element was already styled and we traversed past it without
/// restyling it, that may be because our clever invalidation logic was able to prove
/// that the styles of that element would remain unchanged despite changes to the id
/// or class attributes. However, style sharing relies on the strong guarantee that all
/// the classes and ids up the respective parent chains are identical. As such, if we
/// skipped styling for one (or both) of the parents on this traversal, we can't share
/// styles across cousins. Note that this is a somewhat conservative check. We could
/// tighten it by having the invalidation logic explicitly flag elements for which it
/// ellided styling.
///
/// Second, we want to only consider elements whose ComputedValues match due to a hit
/// in the style sharing cache, rather than due to the rule-node-based reuse that
/// happens later in the styling pipeline. The former gives us the stronger guarantees
/// we need for style sharing, the latter does not.
pub fn safe_for_cousin_sharing(&self) -> bool {
!self.flags.intersects(ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
}
/// Measures memory usage.
#[cfg(feature = "gecko")]
pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
let n = self.styles.size_of_excluding_cvs(ops);
// We may measure more fields in the future if DMD says it's worth it.
n
}
}
|
/// structs via rule node identity. The former gives us stronger transitive
/// guarantees that allows us to apply the style sharing cache to cousins.
const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3;
|
random_line_split
|
data.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElement;
use invalidation::element::invalidator::InvalidationResult;
use invalidation::element::restyle_hints::RestyleHint;
#[cfg(feature = "gecko")]
use malloc_size_of::MallocSizeOfOps;
use properties::ComputedValues;
use properties::longhands::display::computed_value as display;
use rule_tree::StrongRuleNode;
use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage};
use selectors::NthIndexCache;
use servo_arc::Arc;
use shared_lock::StylesheetGuards;
use smallvec::SmallVec;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
bitflags! {
/// Various flags stored on ElementData.
#[derive(Default)]
pub struct ElementDataFlags: u8 {
/// Whether the styles changed for this restyle.
const WAS_RESTYLED = 1 << 0;
/// Whether the last traversal of this element did not do
/// any style computation. This is not true during the initial
/// styling pass, nor is it true when we restyle (in which case
/// WAS_RESTYLED is set).
///
/// This bit always corresponds to the last time the element was
/// traversed, so each traversal simply updates it with the appropriate
/// value.
const TRAVERSED_WITHOUT_STYLING = 1 << 1;
/// Whether we reframed/reconstructed any ancestor or self.
const ANCESTOR_WAS_RECONSTRUCTED = 1 << 2;
/// Whether the primary style of this element data was reused from another
/// element via a rule node comparison. This allows us to differentiate
/// between elements that shared styles because they met all the criteria
/// of the style sharing cache, compared to elements that reused style
/// structs via rule node identity. The former gives us stronger transitive
/// guarantees that allows us to apply the style sharing cache to cousins.
const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3;
}
}
/// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
///
/// We use an Arc so that sharing these styles via the style sharing cache does
/// not require duplicate allocations. We leverage the copy-on-write semantics of
/// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
/// in servo_arc.
#[derive(Clone, Debug, Default)]
pub struct EagerPseudoStyles(Option<Arc<EagerPseudoArray>>);
#[derive(Default)]
struct EagerPseudoArray(EagerPseudoArrayInner);
type EagerPseudoArrayInner = [Option<Arc<ComputedValues>>; EAGER_PSEUDO_COUNT];
impl Deref for EagerPseudoArray {
type Target = EagerPseudoArrayInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for EagerPseudoArray {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
// Manually implement `Clone` here because the derived impl of `Clone` for
// array types assumes the value inside is `Copy`.
impl Clone for EagerPseudoArray {
fn clone(&self) -> Self {
let mut clone = Self::default();
for i in 0..EAGER_PSEUDO_COUNT {
clone[i] = self.0[i].clone();
}
clone
}
}
// Override Debug to print which pseudos we have, and substitute the rule node
// for the much-more-verbose ComputedValues stringification.
impl fmt::Debug for EagerPseudoArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EagerPseudoArray {{ ")?;
for i in 0..EAGER_PSEUDO_COUNT {
if let Some(ref values) = self[i] {
write!(f, "{:?}: {:?}, ", PseudoElement::from_eager_index(i), &values.rules)?;
}
}
write!(f, "}}")
}
}
// Can't use [None; EAGER_PSEUDO_COUNT] here because it complains
// about Copy not being implemented for our Arc type.
#[cfg(feature = "gecko")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
#[cfg(feature = "servo")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None];
impl EagerPseudoStyles {
/// Returns whether there are any pseudo styles.
pub fn is_empty(&self) -> bool {
self.0.is_none()
}
/// Grabs a reference to the list of styles, if they exist.
pub fn as_optional_array(&self) -> Option<&EagerPseudoArrayInner> {
match self.0 {
None => None,
Some(ref x) => Some(&x.0),
}
}
/// Grabs a reference to the list of styles or a list of None if
/// there are no styles to be had.
pub fn as_array(&self) -> &EagerPseudoArrayInner {
self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
}
/// Returns a reference to the style for a given eager pseudo, if it exists.
pub fn get(&self, pseudo: &PseudoElement) -> Option<&Arc<ComputedValues>> {
debug_assert!(pseudo.is_eager());
self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref())
}
/// Sets the style for the eager pseudo.
pub fn set(&mut self, pseudo: &PseudoElement, value: Arc<ComputedValues>) {
if self.0.is_none() {
self.0 = Some(Arc::new(Default::default()));
}
let arr = Arc::make_mut(self.0.as_mut().unwrap());
arr[pseudo.eager_index()] = Some(value);
}
}
/// The styles associated with a node, including the styles for any
/// pseudo-elements.
#[derive(Clone, Default)]
pub struct ElementStyles {
/// The element's style.
pub primary: Option<Arc<ComputedValues>>,
/// A list of the styles for the element's eagerly-cascaded pseudo-elements.
pub pseudos: EagerPseudoStyles,
}
impl ElementStyles {
/// Returns the primary style.
pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
self.primary.as_ref()
}
/// Returns the primary style. Panic if no style available.
pub fn primary(&self) -> &Arc<ComputedValues> {
self.primary.as_ref().unwrap()
}
/// Whether this element `display` value is `none`.
pub fn is_display_none(&self) -> bool {
self.primary().get_box().clone_display() == display::T::none
}
#[cfg(feature = "gecko")]
fn size_of_excluding_cvs(&self, _ops: &mut MallocSizeOfOps) -> usize {
// As the method name suggests, we don't measures the ComputedValues
// here, because they are measured on the C++ side.
// XXX: measure the EagerPseudoArray itself, but not the ComputedValues
// within it.
0
}
}
// We manually implement Debug for ElementStyles so that we can avoid the
// verbose stringification of every property in the ComputedValues. We
// substitute the rule node instead.
impl fmt::Debug for ElementStyles {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
self.primary.as_ref().map(|x| &x.rules), self.pseudos)
}
}
/// Style system data associated with an Element.
///
/// In Gecko, this hangs directly off the Element. Servo, this is embedded
/// inside of layout data, which itself hangs directly off the Element. In
/// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety.
#[derive(Debug, Default)]
pub struct ElementData {
/// The styles for the element and its pseudo-elements.
pub styles: ElementStyles,
/// The restyle damage, indicating what kind of layout changes are required
/// afte restyling.
pub damage: RestyleDamage,
/// The restyle hint, which indicates whether selectors need to be rematched
/// for this element, its children, and its descendants.
pub hint: RestyleHint,
/// Flags.
pub flags: ElementDataFlags,
}
/// The kind of restyle that a single element should do.
#[derive(Debug)]
pub enum RestyleKind {
/// We need to run selector matching plus re-cascade, that is, a full
/// restyle.
MatchAndCascade,
/// We need to recascade with some replacement rule, such as the style
/// attribute, or animation rules.
CascadeWithReplacements(RestyleHint),
/// We only need to recascade, for example, because only inherited
/// properties in the parent changed.
CascadeOnly,
}
impl ElementData {
/// Invalidates style for this element, its descendants, and later siblings,
/// based on the snapshot of the element that we took when attributes or
/// state changed.
pub fn invalidate_style_if_needed<'a, E: TElement>(
&mut self,
element: E,
shared_context: &SharedStyleContext,
stack_limit_checker: Option<&StackLimitChecker>,
nth_index_cache: Option<&mut NthIndexCache>,
) -> InvalidationResult {
// In animation-only restyle we shouldn't touch snapshot at all.
if shared_context.traversal_flags.for_animation_only() {
return InvalidationResult::empty();
}
use invalidation::element::collector::StateAndAttrInvalidationProcessor;
use invalidation::element::invalidator::TreeStyleInvalidator;
debug!("invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
handled_snapshot: {}, pseudo: {:?}",
element,
shared_context.traversal_flags,
element.has_snapshot(),
element.handled_snapshot(),
element.implemented_pseudo_element());
if!element.has_snapshot() || element.handled_snapshot() {
return InvalidationResult::empty();
}
let mut xbl_stylists = SmallVec::<[_; 3]>::new();
let cut_off_inheritance =
element.each_xbl_stylist(|s| xbl_stylists.push(s));
let mut processor = StateAndAttrInvalidationProcessor::new(
shared_context,
&xbl_stylists,
cut_off_inheritance,
element,
self,
nth_index_cache,
);
let invalidator = TreeStyleInvalidator::new(
element,
stack_limit_checker,
&mut processor,
);
let result = invalidator.invalidate();
unsafe { element.set_handled_snapshot() }
debug_assert!(element.handled_snapshot());
result
}
/// Returns true if this element has styles.
#[inline]
pub fn has_styles(&self) -> bool {
self.styles.primary.is_some()
}
/// Returns this element's styles as resolved styles to use for sharing.
pub fn share_styles(&self) -> ResolvedElementStyles {
ResolvedElementStyles {
primary: self.share_primary_style(),
pseudos: self.styles.pseudos.clone(),
}
}
/// Returns this element's primary style as a resolved style to use for sharing.
pub fn share_primary_style(&self) -> PrimaryStyle {
let reused_via_rule_node =
self.flags.contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
PrimaryStyle {
style: ResolvedStyle(self.styles.primary().clone()),
reused_via_rule_node,
}
}
/// Sets a new set of styles, returning the old ones.
pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
if new_styles.primary.reused_via_rule_node {
self.flags.insert(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
} else {
self.flags.remove(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
}
mem::replace(&mut self.styles, new_styles.into())
}
/// Returns the kind of restyling that we're going to need to do on this
/// element, based of the stored restyle hint.
pub fn restyle_kind(
&self,
shared_context: &SharedStyleContext
) -> RestyleKind {
if shared_context.traversal_flags.for_animation_only() {
return self.restyle_kind_for_animation(shared_context);
}
if!self.has_styles() {
return RestyleKind::MatchAndCascade;
}
if self.hint.match_self() {
return RestyleKind::MatchAndCascade;
}
if self.hint.has_replacements() {
debug_assert!(!self.hint.has_animation_hint(),
"Animation only restyle hint should have already processed");
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::replacements());
}
debug_assert!(self.hint.has_recascade_self(),
"We definitely need to do something: {:?}!", self.hint);
return RestyleKind::CascadeOnly;
}
/// Returns the kind of restyling for animation-only restyle.
fn restyle_kind_for_animation(
&self,
shared_context: &SharedStyleContext,
) -> RestyleKind {
debug_assert!(shared_context.traversal_flags.for_animation_only());
debug_assert!(self.has_styles(),
"Unstyled element shouldn't be traversed during \
animation-only traversal");
// return either CascadeWithReplacements or CascadeOnly in case of
// animation-only restyle. I.e. animation-only restyle never does
// selector matching.
if self.hint.has_animation_hint() {
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::for_animations());
}
return RestyleKind::CascadeOnly;
}
/// Return true if important rules are different.
/// We use this to make sure the cascade of off-main thread animations is correct.
/// Note: Ignore custom properties for now because we only support opacity and transform
/// properties for animations running on compositor. Actually, we only care about opacity
/// and transform for now, but it's fine to compare all properties and let the user
/// the check which properties do they want.
/// If it costs too much, get_properties_overriding_animations() should return a set
/// containing only opacity and transform properties.
pub fn important_rules_are_different(
&self,
rules: &StrongRuleNode,
guards: &StylesheetGuards
) -> bool {
debug_assert!(self.has_styles());
let (important_rules, _custom) =
self.styles.primary().rules().get_properties_overriding_animations(&guards);
let (other_important_rules, _custom) = rules.get_properties_overriding_animations(&guards);
important_rules!= other_important_rules
}
/// Drops any restyle state from the element.
///
/// FIXME(bholley): The only caller of this should probably just assert that
/// the hint is empty and call clear_flags_and_damage().
#[inline]
pub fn clear_restyle_state(&mut self) {
self.hint = RestyleHint::empty();
self.clear_restyle_flags_and_damage();
}
/// Drops restyle flags and damage from the element.
#[inline]
pub fn clear_restyle_flags_and_damage(&mut self) {
self.damage = RestyleDamage::empty();
self.flags.remove(ElementDataFlags::WAS_RESTYLED | ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Returns whether this element or any ancestor is going to be
/// reconstructed.
pub fn reconstructed_self_or_ancestor(&self) -> bool {
self.reconstructed_ancestor() || self.reconstructed_self()
}
/// Returns whether this element is going to be reconstructed.
pub fn reconstructed_self(&self) -> bool {
self.damage.contains(RestyleDamage::reconstruct())
}
/// Returns whether any ancestor of this element is going to be
/// reconstructed.
fn reconstructed_ancestor(&self) -> bool {
self.flags.contains(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Sets the flag that tells us whether we've reconstructed an ancestor.
pub fn set_reconstructed_ancestor(&mut self, reconstructed: bool) {
if reconstructed {
// If it weren't for animation-only traversals, we could assert
// `!self.reconstructed_ancestor()` here.
self.flags.insert(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
} else
|
}
/// Mark this element as restyled, which is useful to know whether we need
/// to do a post-traversal.
pub fn set_restyled(&mut self) {
self.flags.insert(ElementDataFlags::WAS_RESTYLED);
self.flags.remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns true if this element was restyled.
#[inline]
pub fn is_restyle(&self) -> bool {
self.flags.contains(ElementDataFlags::WAS_RESTYLED)
}
/// Mark that we traversed this element without computing any style for it.
pub fn set_traversed_without_styling(&mut self) {
self.flags.insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns whether the element was traversed without computing any style for
/// it.
pub fn traversed_without_styling(&self) -> bool {
self.flags.contains(ElementDataFlags::TRAVERSED_WITHOUT_STYLING)
}
/// Returns whether this element has been part of a restyle.
#[inline]
pub fn contains_restyle_data(&self) -> bool {
self.is_restyle() ||!self.hint.is_empty() ||!self.damage.is_empty()
}
/// If an ancestor is already getting reconstructed by Gecko's top-down
/// frame constructor, no need to apply damage. Similarly if we already
/// have an explicitly stored ReconstructFrame hint.
///
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1301258#c12
/// for followup work to make the optimization here more optimal by considering
/// each bit individually.
#[cfg(feature = "gecko")]
pub fn skip_applying_damage(&self) -> bool { self.reconstructed_self_or_ancestor() }
/// N/A in Servo.
#[cfg(feature = "servo")]
pub fn skip_applying_damage(&self) -> bool { false }
/// Returns whether it is safe to perform cousin sharing based on the ComputedValues
/// identity of the primary style in this ElementData. There are a few subtle things
/// to check.
///
/// First, if a parent element was already styled and we traversed past it without
/// restyling it, that may be because our clever invalidation logic was able to prove
/// that the styles of that element would remain unchanged despite changes to the id
/// or class attributes. However, style sharing relies on the strong guarantee that all
/// the classes and ids up the respective parent chains are identical. As such, if we
/// skipped styling for one (or both) of the parents on this traversal, we can't share
/// styles across cousins. Note that this is a somewhat conservative check. We could
/// tighten it by having the invalidation logic explicitly flag elements for which it
/// ellided styling.
///
/// Second, we want to only consider elements whose ComputedValues match due to a hit
/// in the style sharing cache, rather than due to the rule-node-based reuse that
/// happens later in the styling pipeline. The former gives us the stronger guarantees
/// we need for style sharing, the latter does not.
pub fn safe_for_cousin_sharing(&self) -> bool {
!self.flags.intersects(ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
}
/// Measures memory usage.
#[cfg(feature = "gecko")]
pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
let n = self.styles.size_of_excluding_cvs(ops);
// We may measure more fields in the future if DMD says it's worth it.
n
}
}
|
{
self.flags.remove(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
}
|
conditional_block
|
data.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElement;
use invalidation::element::invalidator::InvalidationResult;
use invalidation::element::restyle_hints::RestyleHint;
#[cfg(feature = "gecko")]
use malloc_size_of::MallocSizeOfOps;
use properties::ComputedValues;
use properties::longhands::display::computed_value as display;
use rule_tree::StrongRuleNode;
use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage};
use selectors::NthIndexCache;
use servo_arc::Arc;
use shared_lock::StylesheetGuards;
use smallvec::SmallVec;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
bitflags! {
/// Various flags stored on ElementData.
#[derive(Default)]
pub struct ElementDataFlags: u8 {
/// Whether the styles changed for this restyle.
const WAS_RESTYLED = 1 << 0;
/// Whether the last traversal of this element did not do
/// any style computation. This is not true during the initial
/// styling pass, nor is it true when we restyle (in which case
/// WAS_RESTYLED is set).
///
/// This bit always corresponds to the last time the element was
/// traversed, so each traversal simply updates it with the appropriate
/// value.
const TRAVERSED_WITHOUT_STYLING = 1 << 1;
/// Whether we reframed/reconstructed any ancestor or self.
const ANCESTOR_WAS_RECONSTRUCTED = 1 << 2;
/// Whether the primary style of this element data was reused from another
/// element via a rule node comparison. This allows us to differentiate
/// between elements that shared styles because they met all the criteria
/// of the style sharing cache, compared to elements that reused style
/// structs via rule node identity. The former gives us stronger transitive
/// guarantees that allows us to apply the style sharing cache to cousins.
const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3;
}
}
/// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
///
/// We use an Arc so that sharing these styles via the style sharing cache does
/// not require duplicate allocations. We leverage the copy-on-write semantics of
/// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
/// in servo_arc.
#[derive(Clone, Debug, Default)]
pub struct EagerPseudoStyles(Option<Arc<EagerPseudoArray>>);
#[derive(Default)]
struct EagerPseudoArray(EagerPseudoArrayInner);
type EagerPseudoArrayInner = [Option<Arc<ComputedValues>>; EAGER_PSEUDO_COUNT];
impl Deref for EagerPseudoArray {
type Target = EagerPseudoArrayInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for EagerPseudoArray {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
// Manually implement `Clone` here because the derived impl of `Clone` for
// array types assumes the value inside is `Copy`.
impl Clone for EagerPseudoArray {
fn clone(&self) -> Self {
let mut clone = Self::default();
for i in 0..EAGER_PSEUDO_COUNT {
clone[i] = self.0[i].clone();
}
clone
}
}
// Override Debug to print which pseudos we have, and substitute the rule node
// for the much-more-verbose ComputedValues stringification.
impl fmt::Debug for EagerPseudoArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EagerPseudoArray {{ ")?;
for i in 0..EAGER_PSEUDO_COUNT {
if let Some(ref values) = self[i] {
write!(f, "{:?}: {:?}, ", PseudoElement::from_eager_index(i), &values.rules)?;
}
}
write!(f, "}}")
}
}
// Can't use [None; EAGER_PSEUDO_COUNT] here because it complains
// about Copy not being implemented for our Arc type.
#[cfg(feature = "gecko")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
#[cfg(feature = "servo")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None];
impl EagerPseudoStyles {
/// Returns whether there are any pseudo styles.
pub fn is_empty(&self) -> bool {
self.0.is_none()
}
/// Grabs a reference to the list of styles, if they exist.
pub fn as_optional_array(&self) -> Option<&EagerPseudoArrayInner> {
match self.0 {
None => None,
Some(ref x) => Some(&x.0),
}
}
/// Grabs a reference to the list of styles or a list of None if
/// there are no styles to be had.
pub fn as_array(&self) -> &EagerPseudoArrayInner {
self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
}
/// Returns a reference to the style for a given eager pseudo, if it exists.
pub fn get(&self, pseudo: &PseudoElement) -> Option<&Arc<ComputedValues>> {
debug_assert!(pseudo.is_eager());
self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref())
}
/// Sets the style for the eager pseudo.
pub fn set(&mut self, pseudo: &PseudoElement, value: Arc<ComputedValues>) {
if self.0.is_none() {
self.0 = Some(Arc::new(Default::default()));
}
let arr = Arc::make_mut(self.0.as_mut().unwrap());
arr[pseudo.eager_index()] = Some(value);
}
}
/// The styles associated with a node, including the styles for any
/// pseudo-elements.
#[derive(Clone, Default)]
pub struct ElementStyles {
/// The element's style.
pub primary: Option<Arc<ComputedValues>>,
/// A list of the styles for the element's eagerly-cascaded pseudo-elements.
pub pseudos: EagerPseudoStyles,
}
impl ElementStyles {
/// Returns the primary style.
pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
self.primary.as_ref()
}
/// Returns the primary style. Panic if no style available.
pub fn primary(&self) -> &Arc<ComputedValues> {
self.primary.as_ref().unwrap()
}
/// Whether this element `display` value is `none`.
pub fn is_display_none(&self) -> bool {
self.primary().get_box().clone_display() == display::T::none
}
#[cfg(feature = "gecko")]
fn size_of_excluding_cvs(&self, _ops: &mut MallocSizeOfOps) -> usize {
// As the method name suggests, we don't measures the ComputedValues
// here, because they are measured on the C++ side.
// XXX: measure the EagerPseudoArray itself, but not the ComputedValues
// within it.
0
}
}
// We manually implement Debug for ElementStyles so that we can avoid the
// verbose stringification of every property in the ComputedValues. We
// substitute the rule node instead.
impl fmt::Debug for ElementStyles {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
self.primary.as_ref().map(|x| &x.rules), self.pseudos)
}
}
/// Style system data associated with an Element.
///
/// In Gecko, this hangs directly off the Element. Servo, this is embedded
/// inside of layout data, which itself hangs directly off the Element. In
/// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety.
#[derive(Debug, Default)]
pub struct ElementData {
/// The styles for the element and its pseudo-elements.
pub styles: ElementStyles,
/// The restyle damage, indicating what kind of layout changes are required
/// afte restyling.
pub damage: RestyleDamage,
/// The restyle hint, which indicates whether selectors need to be rematched
/// for this element, its children, and its descendants.
pub hint: RestyleHint,
/// Flags.
pub flags: ElementDataFlags,
}
/// The kind of restyle that a single element should do.
#[derive(Debug)]
pub enum RestyleKind {
/// We need to run selector matching plus re-cascade, that is, a full
/// restyle.
MatchAndCascade,
/// We need to recascade with some replacement rule, such as the style
/// attribute, or animation rules.
CascadeWithReplacements(RestyleHint),
/// We only need to recascade, for example, because only inherited
/// properties in the parent changed.
CascadeOnly,
}
impl ElementData {
/// Invalidates style for this element, its descendants, and later siblings,
/// based on the snapshot of the element that we took when attributes or
/// state changed.
pub fn invalidate_style_if_needed<'a, E: TElement>(
&mut self,
element: E,
shared_context: &SharedStyleContext,
stack_limit_checker: Option<&StackLimitChecker>,
nth_index_cache: Option<&mut NthIndexCache>,
) -> InvalidationResult {
// In animation-only restyle we shouldn't touch snapshot at all.
if shared_context.traversal_flags.for_animation_only() {
return InvalidationResult::empty();
}
use invalidation::element::collector::StateAndAttrInvalidationProcessor;
use invalidation::element::invalidator::TreeStyleInvalidator;
debug!("invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
handled_snapshot: {}, pseudo: {:?}",
element,
shared_context.traversal_flags,
element.has_snapshot(),
element.handled_snapshot(),
element.implemented_pseudo_element());
if!element.has_snapshot() || element.handled_snapshot() {
return InvalidationResult::empty();
}
let mut xbl_stylists = SmallVec::<[_; 3]>::new();
let cut_off_inheritance =
element.each_xbl_stylist(|s| xbl_stylists.push(s));
let mut processor = StateAndAttrInvalidationProcessor::new(
shared_context,
&xbl_stylists,
cut_off_inheritance,
element,
self,
nth_index_cache,
);
let invalidator = TreeStyleInvalidator::new(
element,
stack_limit_checker,
&mut processor,
);
let result = invalidator.invalidate();
unsafe { element.set_handled_snapshot() }
debug_assert!(element.handled_snapshot());
result
}
/// Returns true if this element has styles.
#[inline]
pub fn has_styles(&self) -> bool {
self.styles.primary.is_some()
}
/// Returns this element's styles as resolved styles to use for sharing.
pub fn share_styles(&self) -> ResolvedElementStyles {
ResolvedElementStyles {
primary: self.share_primary_style(),
pseudos: self.styles.pseudos.clone(),
}
}
/// Returns this element's primary style as a resolved style to use for sharing.
pub fn share_primary_style(&self) -> PrimaryStyle {
let reused_via_rule_node =
self.flags.contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
PrimaryStyle {
style: ResolvedStyle(self.styles.primary().clone()),
reused_via_rule_node,
}
}
/// Sets a new set of styles, returning the old ones.
pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
if new_styles.primary.reused_via_rule_node {
self.flags.insert(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
} else {
self.flags.remove(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
}
mem::replace(&mut self.styles, new_styles.into())
}
/// Returns the kind of restyling that we're going to need to do on this
/// element, based of the stored restyle hint.
pub fn restyle_kind(
&self,
shared_context: &SharedStyleContext
) -> RestyleKind {
if shared_context.traversal_flags.for_animation_only() {
return self.restyle_kind_for_animation(shared_context);
}
if!self.has_styles() {
return RestyleKind::MatchAndCascade;
}
if self.hint.match_self() {
return RestyleKind::MatchAndCascade;
}
if self.hint.has_replacements() {
debug_assert!(!self.hint.has_animation_hint(),
"Animation only restyle hint should have already processed");
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::replacements());
}
debug_assert!(self.hint.has_recascade_self(),
"We definitely need to do something: {:?}!", self.hint);
return RestyleKind::CascadeOnly;
}
/// Returns the kind of restyling for animation-only restyle.
fn restyle_kind_for_animation(
&self,
shared_context: &SharedStyleContext,
) -> RestyleKind {
debug_assert!(shared_context.traversal_flags.for_animation_only());
debug_assert!(self.has_styles(),
"Unstyled element shouldn't be traversed during \
animation-only traversal");
// return either CascadeWithReplacements or CascadeOnly in case of
// animation-only restyle. I.e. animation-only restyle never does
// selector matching.
if self.hint.has_animation_hint() {
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::for_animations());
}
return RestyleKind::CascadeOnly;
}
/// Return true if important rules are different.
/// We use this to make sure the cascade of off-main thread animations is correct.
/// Note: Ignore custom properties for now because we only support opacity and transform
/// properties for animations running on compositor. Actually, we only care about opacity
/// and transform for now, but it's fine to compare all properties and let the user
/// the check which properties do they want.
/// If it costs too much, get_properties_overriding_animations() should return a set
/// containing only opacity and transform properties.
pub fn important_rules_are_different(
&self,
rules: &StrongRuleNode,
guards: &StylesheetGuards
) -> bool {
debug_assert!(self.has_styles());
let (important_rules, _custom) =
self.styles.primary().rules().get_properties_overriding_animations(&guards);
let (other_important_rules, _custom) = rules.get_properties_overriding_animations(&guards);
important_rules!= other_important_rules
}
/// Drops any restyle state from the element.
///
/// FIXME(bholley): The only caller of this should probably just assert that
/// the hint is empty and call clear_flags_and_damage().
#[inline]
pub fn clear_restyle_state(&mut self) {
self.hint = RestyleHint::empty();
self.clear_restyle_flags_and_damage();
}
/// Drops restyle flags and damage from the element.
#[inline]
pub fn clear_restyle_flags_and_damage(&mut self) {
self.damage = RestyleDamage::empty();
self.flags.remove(ElementDataFlags::WAS_RESTYLED | ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Returns whether this element or any ancestor is going to be
/// reconstructed.
pub fn reconstructed_self_or_ancestor(&self) -> bool {
self.reconstructed_ancestor() || self.reconstructed_self()
}
/// Returns whether this element is going to be reconstructed.
pub fn reconstructed_self(&self) -> bool {
self.damage.contains(RestyleDamage::reconstruct())
}
/// Returns whether any ancestor of this element is going to be
/// reconstructed.
fn reconstructed_ancestor(&self) -> bool {
self.flags.contains(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Sets the flag that tells us whether we've reconstructed an ancestor.
pub fn set_reconstructed_ancestor(&mut self, reconstructed: bool) {
if reconstructed {
// If it weren't for animation-only traversals, we could assert
// `!self.reconstructed_ancestor()` here.
self.flags.insert(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
} else {
self.flags.remove(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
}
}
/// Mark this element as restyled, which is useful to know whether we need
/// to do a post-traversal.
pub fn set_restyled(&mut self) {
self.flags.insert(ElementDataFlags::WAS_RESTYLED);
self.flags.remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns true if this element was restyled.
#[inline]
pub fn is_restyle(&self) -> bool {
self.flags.contains(ElementDataFlags::WAS_RESTYLED)
}
/// Mark that we traversed this element without computing any style for it.
pub fn set_traversed_without_styling(&mut self) {
self.flags.insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns whether the element was traversed without computing any style for
/// it.
pub fn traversed_without_styling(&self) -> bool {
self.flags.contains(ElementDataFlags::TRAVERSED_WITHOUT_STYLING)
}
/// Returns whether this element has been part of a restyle.
#[inline]
pub fn contains_restyle_data(&self) -> bool
|
/// If an ancestor is already getting reconstructed by Gecko's top-down
/// frame constructor, no need to apply damage. Similarly if we already
/// have an explicitly stored ReconstructFrame hint.
///
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1301258#c12
/// for followup work to make the optimization here more optimal by considering
/// each bit individually.
#[cfg(feature = "gecko")]
pub fn skip_applying_damage(&self) -> bool { self.reconstructed_self_or_ancestor() }
/// N/A in Servo.
#[cfg(feature = "servo")]
pub fn skip_applying_damage(&self) -> bool { false }
/// Returns whether it is safe to perform cousin sharing based on the ComputedValues
/// identity of the primary style in this ElementData. There are a few subtle things
/// to check.
///
/// First, if a parent element was already styled and we traversed past it without
/// restyling it, that may be because our clever invalidation logic was able to prove
/// that the styles of that element would remain unchanged despite changes to the id
/// or class attributes. However, style sharing relies on the strong guarantee that all
/// the classes and ids up the respective parent chains are identical. As such, if we
/// skipped styling for one (or both) of the parents on this traversal, we can't share
/// styles across cousins. Note that this is a somewhat conservative check. We could
/// tighten it by having the invalidation logic explicitly flag elements for which it
/// ellided styling.
///
/// Second, we want to only consider elements whose ComputedValues match due to a hit
/// in the style sharing cache, rather than due to the rule-node-based reuse that
/// happens later in the styling pipeline. The former gives us the stronger guarantees
/// we need for style sharing, the latter does not.
pub fn safe_for_cousin_sharing(&self) -> bool {
!self.flags.intersects(ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
}
/// Measures memory usage.
#[cfg(feature = "gecko")]
pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
let n = self.styles.size_of_excluding_cvs(ops);
// We may measure more fields in the future if DMD says it's worth it.
n
}
}
|
{
self.is_restyle() || !self.hint.is_empty() || !self.damage.is_empty()
}
|
identifier_body
|
data.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElement;
use invalidation::element::invalidator::InvalidationResult;
use invalidation::element::restyle_hints::RestyleHint;
#[cfg(feature = "gecko")]
use malloc_size_of::MallocSizeOfOps;
use properties::ComputedValues;
use properties::longhands::display::computed_value as display;
use rule_tree::StrongRuleNode;
use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, RestyleDamage};
use selectors::NthIndexCache;
use servo_arc::Arc;
use shared_lock::StylesheetGuards;
use smallvec::SmallVec;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
bitflags! {
/// Various flags stored on ElementData.
#[derive(Default)]
pub struct ElementDataFlags: u8 {
/// Whether the styles changed for this restyle.
const WAS_RESTYLED = 1 << 0;
/// Whether the last traversal of this element did not do
/// any style computation. This is not true during the initial
/// styling pass, nor is it true when we restyle (in which case
/// WAS_RESTYLED is set).
///
/// This bit always corresponds to the last time the element was
/// traversed, so each traversal simply updates it with the appropriate
/// value.
const TRAVERSED_WITHOUT_STYLING = 1 << 1;
/// Whether we reframed/reconstructed any ancestor or self.
const ANCESTOR_WAS_RECONSTRUCTED = 1 << 2;
/// Whether the primary style of this element data was reused from another
/// element via a rule node comparison. This allows us to differentiate
/// between elements that shared styles because they met all the criteria
/// of the style sharing cache, compared to elements that reused style
/// structs via rule node identity. The former gives us stronger transitive
/// guarantees that allows us to apply the style sharing cache to cousins.
const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3;
}
}
/// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
///
/// We use an Arc so that sharing these styles via the style sharing cache does
/// not require duplicate allocations. We leverage the copy-on-write semantics of
/// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
/// in servo_arc.
#[derive(Clone, Debug, Default)]
pub struct EagerPseudoStyles(Option<Arc<EagerPseudoArray>>);
#[derive(Default)]
struct EagerPseudoArray(EagerPseudoArrayInner);
type EagerPseudoArrayInner = [Option<Arc<ComputedValues>>; EAGER_PSEUDO_COUNT];
impl Deref for EagerPseudoArray {
type Target = EagerPseudoArrayInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for EagerPseudoArray {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
// Manually implement `Clone` here because the derived impl of `Clone` for
// array types assumes the value inside is `Copy`.
impl Clone for EagerPseudoArray {
fn clone(&self) -> Self {
let mut clone = Self::default();
for i in 0..EAGER_PSEUDO_COUNT {
clone[i] = self.0[i].clone();
}
clone
}
}
// Override Debug to print which pseudos we have, and substitute the rule node
// for the much-more-verbose ComputedValues stringification.
impl fmt::Debug for EagerPseudoArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EagerPseudoArray {{ ")?;
for i in 0..EAGER_PSEUDO_COUNT {
if let Some(ref values) = self[i] {
write!(f, "{:?}: {:?}, ", PseudoElement::from_eager_index(i), &values.rules)?;
}
}
write!(f, "}}")
}
}
// Can't use [None; EAGER_PSEUDO_COUNT] here because it complains
// about Copy not being implemented for our Arc type.
#[cfg(feature = "gecko")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
#[cfg(feature = "servo")]
const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None];
impl EagerPseudoStyles {
/// Returns whether there are any pseudo styles.
pub fn is_empty(&self) -> bool {
self.0.is_none()
}
/// Grabs a reference to the list of styles, if they exist.
pub fn as_optional_array(&self) -> Option<&EagerPseudoArrayInner> {
match self.0 {
None => None,
Some(ref x) => Some(&x.0),
}
}
/// Grabs a reference to the list of styles or a list of None if
/// there are no styles to be had.
pub fn as_array(&self) -> &EagerPseudoArrayInner {
self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
}
/// Returns a reference to the style for a given eager pseudo, if it exists.
pub fn get(&self, pseudo: &PseudoElement) -> Option<&Arc<ComputedValues>> {
debug_assert!(pseudo.is_eager());
self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref())
}
/// Sets the style for the eager pseudo.
pub fn set(&mut self, pseudo: &PseudoElement, value: Arc<ComputedValues>) {
if self.0.is_none() {
self.0 = Some(Arc::new(Default::default()));
}
let arr = Arc::make_mut(self.0.as_mut().unwrap());
arr[pseudo.eager_index()] = Some(value);
}
}
/// The styles associated with a node, including the styles for any
/// pseudo-elements.
#[derive(Clone, Default)]
pub struct ElementStyles {
/// The element's style.
pub primary: Option<Arc<ComputedValues>>,
/// A list of the styles for the element's eagerly-cascaded pseudo-elements.
pub pseudos: EagerPseudoStyles,
}
impl ElementStyles {
/// Returns the primary style.
pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
self.primary.as_ref()
}
/// Returns the primary style. Panic if no style available.
pub fn primary(&self) -> &Arc<ComputedValues> {
self.primary.as_ref().unwrap()
}
/// Whether this element `display` value is `none`.
pub fn is_display_none(&self) -> bool {
self.primary().get_box().clone_display() == display::T::none
}
#[cfg(feature = "gecko")]
fn size_of_excluding_cvs(&self, _ops: &mut MallocSizeOfOps) -> usize {
// As the method name suggests, we don't measures the ComputedValues
// here, because they are measured on the C++ side.
// XXX: measure the EagerPseudoArray itself, but not the ComputedValues
// within it.
0
}
}
// We manually implement Debug for ElementStyles so that we can avoid the
// verbose stringification of every property in the ComputedValues. We
// substitute the rule node instead.
impl fmt::Debug for ElementStyles {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
self.primary.as_ref().map(|x| &x.rules), self.pseudos)
}
}
/// Style system data associated with an Element.
///
/// In Gecko, this hangs directly off the Element. Servo, this is embedded
/// inside of layout data, which itself hangs directly off the Element. In
/// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety.
#[derive(Debug, Default)]
pub struct ElementData {
/// The styles for the element and its pseudo-elements.
pub styles: ElementStyles,
/// The restyle damage, indicating what kind of layout changes are required
/// afte restyling.
pub damage: RestyleDamage,
/// The restyle hint, which indicates whether selectors need to be rematched
/// for this element, its children, and its descendants.
pub hint: RestyleHint,
/// Flags.
pub flags: ElementDataFlags,
}
/// The kind of restyle that a single element should do.
#[derive(Debug)]
pub enum RestyleKind {
/// We need to run selector matching plus re-cascade, that is, a full
/// restyle.
MatchAndCascade,
/// We need to recascade with some replacement rule, such as the style
/// attribute, or animation rules.
CascadeWithReplacements(RestyleHint),
/// We only need to recascade, for example, because only inherited
/// properties in the parent changed.
CascadeOnly,
}
impl ElementData {
/// Invalidates style for this element, its descendants, and later siblings,
/// based on the snapshot of the element that we took when attributes or
/// state changed.
pub fn invalidate_style_if_needed<'a, E: TElement>(
&mut self,
element: E,
shared_context: &SharedStyleContext,
stack_limit_checker: Option<&StackLimitChecker>,
nth_index_cache: Option<&mut NthIndexCache>,
) -> InvalidationResult {
// In animation-only restyle we shouldn't touch snapshot at all.
if shared_context.traversal_flags.for_animation_only() {
return InvalidationResult::empty();
}
use invalidation::element::collector::StateAndAttrInvalidationProcessor;
use invalidation::element::invalidator::TreeStyleInvalidator;
debug!("invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
handled_snapshot: {}, pseudo: {:?}",
element,
shared_context.traversal_flags,
element.has_snapshot(),
element.handled_snapshot(),
element.implemented_pseudo_element());
if!element.has_snapshot() || element.handled_snapshot() {
return InvalidationResult::empty();
}
let mut xbl_stylists = SmallVec::<[_; 3]>::new();
let cut_off_inheritance =
element.each_xbl_stylist(|s| xbl_stylists.push(s));
let mut processor = StateAndAttrInvalidationProcessor::new(
shared_context,
&xbl_stylists,
cut_off_inheritance,
element,
self,
nth_index_cache,
);
let invalidator = TreeStyleInvalidator::new(
element,
stack_limit_checker,
&mut processor,
);
let result = invalidator.invalidate();
unsafe { element.set_handled_snapshot() }
debug_assert!(element.handled_snapshot());
result
}
/// Returns true if this element has styles.
#[inline]
pub fn has_styles(&self) -> bool {
self.styles.primary.is_some()
}
/// Returns this element's styles as resolved styles to use for sharing.
pub fn share_styles(&self) -> ResolvedElementStyles {
ResolvedElementStyles {
primary: self.share_primary_style(),
pseudos: self.styles.pseudos.clone(),
}
}
/// Returns this element's primary style as a resolved style to use for sharing.
pub fn share_primary_style(&self) -> PrimaryStyle {
let reused_via_rule_node =
self.flags.contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
PrimaryStyle {
style: ResolvedStyle(self.styles.primary().clone()),
reused_via_rule_node,
}
}
/// Sets a new set of styles, returning the old ones.
pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
if new_styles.primary.reused_via_rule_node {
self.flags.insert(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
} else {
self.flags.remove(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
}
mem::replace(&mut self.styles, new_styles.into())
}
/// Returns the kind of restyling that we're going to need to do on this
/// element, based of the stored restyle hint.
pub fn restyle_kind(
&self,
shared_context: &SharedStyleContext
) -> RestyleKind {
if shared_context.traversal_flags.for_animation_only() {
return self.restyle_kind_for_animation(shared_context);
}
if!self.has_styles() {
return RestyleKind::MatchAndCascade;
}
if self.hint.match_self() {
return RestyleKind::MatchAndCascade;
}
if self.hint.has_replacements() {
debug_assert!(!self.hint.has_animation_hint(),
"Animation only restyle hint should have already processed");
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::replacements());
}
debug_assert!(self.hint.has_recascade_self(),
"We definitely need to do something: {:?}!", self.hint);
return RestyleKind::CascadeOnly;
}
/// Returns the kind of restyling for animation-only restyle.
fn restyle_kind_for_animation(
&self,
shared_context: &SharedStyleContext,
) -> RestyleKind {
debug_assert!(shared_context.traversal_flags.for_animation_only());
debug_assert!(self.has_styles(),
"Unstyled element shouldn't be traversed during \
animation-only traversal");
// return either CascadeWithReplacements or CascadeOnly in case of
// animation-only restyle. I.e. animation-only restyle never does
// selector matching.
if self.hint.has_animation_hint() {
return RestyleKind::CascadeWithReplacements(self.hint & RestyleHint::for_animations());
}
return RestyleKind::CascadeOnly;
}
/// Return true if important rules are different.
/// We use this to make sure the cascade of off-main thread animations is correct.
/// Note: Ignore custom properties for now because we only support opacity and transform
/// properties for animations running on compositor. Actually, we only care about opacity
/// and transform for now, but it's fine to compare all properties and let the user
/// the check which properties do they want.
/// If it costs too much, get_properties_overriding_animations() should return a set
/// containing only opacity and transform properties.
pub fn important_rules_are_different(
&self,
rules: &StrongRuleNode,
guards: &StylesheetGuards
) -> bool {
debug_assert!(self.has_styles());
let (important_rules, _custom) =
self.styles.primary().rules().get_properties_overriding_animations(&guards);
let (other_important_rules, _custom) = rules.get_properties_overriding_animations(&guards);
important_rules!= other_important_rules
}
/// Drops any restyle state from the element.
///
/// FIXME(bholley): The only caller of this should probably just assert that
/// the hint is empty and call clear_flags_and_damage().
#[inline]
pub fn clear_restyle_state(&mut self) {
self.hint = RestyleHint::empty();
self.clear_restyle_flags_and_damage();
}
/// Drops restyle flags and damage from the element.
#[inline]
pub fn clear_restyle_flags_and_damage(&mut self) {
self.damage = RestyleDamage::empty();
self.flags.remove(ElementDataFlags::WAS_RESTYLED | ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Returns whether this element or any ancestor is going to be
/// reconstructed.
pub fn reconstructed_self_or_ancestor(&self) -> bool {
self.reconstructed_ancestor() || self.reconstructed_self()
}
/// Returns whether this element is going to be reconstructed.
pub fn reconstructed_self(&self) -> bool {
self.damage.contains(RestyleDamage::reconstruct())
}
/// Returns whether any ancestor of this element is going to be
/// reconstructed.
fn reconstructed_ancestor(&self) -> bool {
self.flags.contains(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
}
/// Sets the flag that tells us whether we've reconstructed an ancestor.
pub fn set_reconstructed_ancestor(&mut self, reconstructed: bool) {
if reconstructed {
// If it weren't for animation-only traversals, we could assert
// `!self.reconstructed_ancestor()` here.
self.flags.insert(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
} else {
self.flags.remove(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
}
}
/// Mark this element as restyled, which is useful to know whether we need
/// to do a post-traversal.
pub fn set_restyled(&mut self) {
self.flags.insert(ElementDataFlags::WAS_RESTYLED);
self.flags.remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns true if this element was restyled.
#[inline]
pub fn is_restyle(&self) -> bool {
self.flags.contains(ElementDataFlags::WAS_RESTYLED)
}
/// Mark that we traversed this element without computing any style for it.
pub fn set_traversed_without_styling(&mut self) {
self.flags.insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
}
/// Returns whether the element was traversed without computing any style for
/// it.
pub fn traversed_without_styling(&self) -> bool {
self.flags.contains(ElementDataFlags::TRAVERSED_WITHOUT_STYLING)
}
/// Returns whether this element has been part of a restyle.
#[inline]
pub fn contains_restyle_data(&self) -> bool {
self.is_restyle() ||!self.hint.is_empty() ||!self.damage.is_empty()
}
/// If an ancestor is already getting reconstructed by Gecko's top-down
/// frame constructor, no need to apply damage. Similarly if we already
/// have an explicitly stored ReconstructFrame hint.
///
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1301258#c12
/// for followup work to make the optimization here more optimal by considering
/// each bit individually.
#[cfg(feature = "gecko")]
pub fn
|
(&self) -> bool { self.reconstructed_self_or_ancestor() }
/// N/A in Servo.
#[cfg(feature = "servo")]
pub fn skip_applying_damage(&self) -> bool { false }
/// Returns whether it is safe to perform cousin sharing based on the ComputedValues
/// identity of the primary style in this ElementData. There are a few subtle things
/// to check.
///
/// First, if a parent element was already styled and we traversed past it without
/// restyling it, that may be because our clever invalidation logic was able to prove
/// that the styles of that element would remain unchanged despite changes to the id
/// or class attributes. However, style sharing relies on the strong guarantee that all
/// the classes and ids up the respective parent chains are identical. As such, if we
/// skipped styling for one (or both) of the parents on this traversal, we can't share
/// styles across cousins. Note that this is a somewhat conservative check. We could
/// tighten it by having the invalidation logic explicitly flag elements for which it
/// ellided styling.
///
/// Second, we want to only consider elements whose ComputedValues match due to a hit
/// in the style sharing cache, rather than due to the rule-node-based reuse that
/// happens later in the styling pipeline. The former gives us the stronger guarantees
/// we need for style sharing, the latter does not.
pub fn safe_for_cousin_sharing(&self) -> bool {
!self.flags.intersects(ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
}
/// Measures memory usage.
#[cfg(feature = "gecko")]
pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
let n = self.styles.size_of_excluding_cvs(ops);
// We may measure more fields in the future if DMD says it's worth it.
n
}
}
|
skip_applying_damage
|
identifier_name
|
lib.rs
|
//! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display("error: '{}', line {}: not valid UTF-8", file, lineno)
}
MalformedAnchor(file: String, lineno: usize, anchor: String) {
description("could not parse anchor tag")
display("warn: '{}', line {}: ignoring malformed anchor: '{}'", file, lineno, anchor)
}
DuplicateAnchor(file: String, lineno: usize, tag: String) {
description("found a duplicate anchor tag")
display("warn: '{}', line {}: ignoring duplicate anchor tag: '{}'", file, lineno, tag)
}
MissingTag(file: String, lineno: usize, tag: String) {
description("nonexistent tag name")
display("warn: '{}', line {}: nonexistent tag name: '{}'", file, lineno, tag)
}
}
}
}
use std::rc::Rc;
use std::io;
use std::result;
use std::default::Default;
use std::collections::BTreeMap;
use input::File;
use list::List;
pub struct OutputOptions {
pub comment: Option<String>
}
impl Default for OutputOptions {
fn default() -> Self {
OutputOptions {
comment: None
}
}
}
struct Block {
lines: Vec<String>,
file: Rc<String>,
lineno: usize
}
impl Block {
fn new(file: Rc<String>, lineno: usize) -> Self {
Block {
lines: Vec::new(),
file: file,
lineno: lineno
}
}
}
struct Anchor {
indentation: usize, // The *absolute* level of indentation.
tangled: Tangled
}
impl Anchor {
fn new(indentation: usize) -> Self {
Anchor {
indentation: indentation,
tangled: List::new()
}
}
}
/// An `Either` represents the situation when *either* arm is a valid
/// value, as opposed to a `Result`, where one arm designates an error.
enum Either<T, U> {
Left(T),
Right(U)
}
struct AnchorRef(String);
type Tangled = List<Either<Block, AnchorRef>>;
enum OutputTarget {
Insert,
Before(AnchorRef),
After(AnchorRef)
}
/// Process all the literate programming directives in the contents of the
/// given files, return a Vec of output lines (suitable for immediate
/// printing to, say, `stdout`)
pub fn tangle_output(inputs: Vec<File>, options: OutputOptions) -> (Vec<String>, Vec<processing_errors::Error>) {
use std::io::{BufReader, BufRead};
use parsing::Anchor;
use processing_errors::ErrorKind;
let mut tangled = List::new();
let mut anchors = BTreeMap::new();
let mut errors = Vec::new(); // Errors that we accrue during processing.
for input in inputs {
let filename = Rc::new(input.name);
let mut lines = BufReader::new(input.contents)
.lines()
.enumerate()
.map(|(lineno, line)| (lineno + 1, line));
let mut state = OutputTarget::Insert;
let mut tangled_section = List::new();
let mut block = Block::new(filename.clone(), 1);
macro_rules! emplace_section {
() => {
match state {
OutputTarget::Insert => tangled.append_back(&mut tangled_section),
OutputTarget::Before(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_front(&mut tangled_section);
},
OutputTarget::After(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_back(&mut tangled_section);
}
}
}
}
loop {
let next_anchor = process_block_lines(&mut lines, &mut block, &mut errors);
if!block.lines.is_empty() {
tangled_section.push_back(Either::Left(block));
}
match next_anchor {
Some((lineno, indentation, anchor)) => {
macro_rules! has_anchor {
($anchor_name:expr) => {{
if anchors.contains_key($anchor_name) {
true
} else {
let filename: &String = &filename;
let error = ErrorKind::MissingTag(filename.clone(), lineno, $anchor_name.clone()).into();
errors.push(error);
false
}
}}
}
block = Block::new(filename.clone(), lineno);
match anchor {
Anchor::Insert => {
emplace_section!();
tangled_section = List::new();
state = OutputTarget::Insert;
},
Anchor::Before(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::Before(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::After(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::After(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::Label(anchor_name) => {
let anchor = ::Anchor::new(indentation);
anchors.insert(anchor_name.clone(), anchor);
tangled_section.push_back(Either::Right(AnchorRef(anchor_name)));
}
};
},
None => {
emplace_section!();
break;
}
};
}
}
(collect_tangled_output(tangled, anchors, options), errors)
}
fn collect_tangled_output(tangled: Tangled,
mut anchors: BTreeMap<String, Anchor>,
options: OutputOptions) -> Vec<String>
{
let mut lines = Vec::new();
collect_anchor_lines(tangled, &mut anchors, &mut lines, 0, &options);
lines
}
fn maybe_block_header(block: &Block, options: &OutputOptions) -> Option<String> {
match &options.comment {
&Some(ref comment_prefix) =>
|
&None => None
}
}
fn collect_anchor_lines(tangled: Tangled,
anchors: &mut BTreeMap<String, Anchor>,
lines: &mut Vec<String>,
indentation: usize,
options: &OutputOptions)
{
use std::iter;
let indent_prefix = iter::repeat(' ').take(indentation).collect::<String>();
for knot in tangled {
match knot {
Either::Left(block) => {
if let Some(comment) = maybe_block_header(&block, options) {
lines.push(indent_prefix.clone() + &comment);
}
for line in block.lines {
lines.push(indent_prefix.clone() + &line);
}
},
Either::Right(AnchorRef(ref anchor_name)) => {
let anchor = anchors.remove(anchor_name)
.expect("invariant violated: anchor name does not exist");
collect_anchor_lines(
anchor.tangled,
anchors,
lines,
indentation + anchor.indentation,
options
);
}
};
}
}
/// We scan through each file block by block.
/// Each block will end in either an anchor tag, or the end of the file.
fn process_block_lines<I>(lines: &mut I, block: &mut Block, errors: &mut Vec<processing_errors::Error>) -> Option<(usize, usize, parsing::Anchor)> where
I: Iterator<Item=(usize, result::Result<String, io::Error>)>
{
use processing_errors::ErrorKind;
use std::ops::Deref;
let filename = block.file.deref();
for (lineno, line) in lines {
match line {
Ok(line) => {
let result = parsing::might_be_anchor(&line)
.ok_or(None)
.and_then(|found| {
parsing::parse(found.as_str())
.map_err(|_| Some(ErrorKind::MalformedAnchor(
filename.clone(),
lineno,
found.as_str().to_string()
).into()))
});
match result {
Ok(anchor) => return Some((lineno, indentation_level(&line), anchor)),
Err(Some(error)) => {
errors.push(error);
block.lines.push(line);
},
Err(None) => {
block.lines.push(line);
}
};
},
Err(_) => errors.push(ErrorKind::NotUTF8(filename.clone(), lineno).into())
};
}
None
}
/// Index of first non-whitespace character.
fn indentation_level(line: &str) -> usize {
use regex::Regex;
let nonwhitespace = Regex::new(r"[^\s]").unwrap();
match nonwhitespace.find(line) {
Some(found) => found.start(),
None => 0
}
}
|
{
let header = format!(
"{} '{}', line {}",
comment_prefix,
&block.file,
block.lineno
);
Some(header)
}
|
conditional_block
|
lib.rs
|
//! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display("error: '{}', line {}: not valid UTF-8", file, lineno)
}
MalformedAnchor(file: String, lineno: usize, anchor: String) {
description("could not parse anchor tag")
display("warn: '{}', line {}: ignoring malformed anchor: '{}'", file, lineno, anchor)
}
DuplicateAnchor(file: String, lineno: usize, tag: String) {
description("found a duplicate anchor tag")
display("warn: '{}', line {}: ignoring duplicate anchor tag: '{}'", file, lineno, tag)
}
MissingTag(file: String, lineno: usize, tag: String) {
description("nonexistent tag name")
display("warn: '{}', line {}: nonexistent tag name: '{}'", file, lineno, tag)
}
}
}
}
use std::rc::Rc;
use std::io;
use std::result;
use std::default::Default;
use std::collections::BTreeMap;
use input::File;
use list::List;
pub struct OutputOptions {
pub comment: Option<String>
}
impl Default for OutputOptions {
fn default() -> Self {
OutputOptions {
comment: None
}
}
}
struct Block {
lines: Vec<String>,
file: Rc<String>,
lineno: usize
}
impl Block {
fn new(file: Rc<String>, lineno: usize) -> Self {
Block {
lines: Vec::new(),
file: file,
lineno: lineno
}
}
}
struct Anchor {
indentation: usize, // The *absolute* level of indentation.
tangled: Tangled
}
impl Anchor {
fn new(indentation: usize) -> Self {
Anchor {
indentation: indentation,
tangled: List::new()
}
}
}
/// An `Either` represents the situation when *either* arm is a valid
/// value, as opposed to a `Result`, where one arm designates an error.
enum Either<T, U> {
Left(T),
Right(U)
}
struct AnchorRef(String);
type Tangled = List<Either<Block, AnchorRef>>;
enum OutputTarget {
Insert,
Before(AnchorRef),
After(AnchorRef)
}
/// Process all the literate programming directives in the contents of the
/// given files, return a Vec of output lines (suitable for immediate
/// printing to, say, `stdout`)
pub fn tangle_output(inputs: Vec<File>, options: OutputOptions) -> (Vec<String>, Vec<processing_errors::Error>) {
use std::io::{BufReader, BufRead};
use parsing::Anchor;
use processing_errors::ErrorKind;
let mut tangled = List::new();
let mut anchors = BTreeMap::new();
let mut errors = Vec::new(); // Errors that we accrue during processing.
for input in inputs {
let filename = Rc::new(input.name);
let mut lines = BufReader::new(input.contents)
.lines()
.enumerate()
.map(|(lineno, line)| (lineno + 1, line));
let mut state = OutputTarget::Insert;
let mut tangled_section = List::new();
let mut block = Block::new(filename.clone(), 1);
macro_rules! emplace_section {
() => {
match state {
OutputTarget::Insert => tangled.append_back(&mut tangled_section),
OutputTarget::Before(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_front(&mut tangled_section);
},
OutputTarget::After(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_back(&mut tangled_section);
}
}
}
}
|
loop {
let next_anchor = process_block_lines(&mut lines, &mut block, &mut errors);
if!block.lines.is_empty() {
tangled_section.push_back(Either::Left(block));
}
match next_anchor {
Some((lineno, indentation, anchor)) => {
macro_rules! has_anchor {
($anchor_name:expr) => {{
if anchors.contains_key($anchor_name) {
true
} else {
let filename: &String = &filename;
let error = ErrorKind::MissingTag(filename.clone(), lineno, $anchor_name.clone()).into();
errors.push(error);
false
}
}}
}
block = Block::new(filename.clone(), lineno);
match anchor {
Anchor::Insert => {
emplace_section!();
tangled_section = List::new();
state = OutputTarget::Insert;
},
Anchor::Before(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::Before(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::After(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::After(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::Label(anchor_name) => {
let anchor = ::Anchor::new(indentation);
anchors.insert(anchor_name.clone(), anchor);
tangled_section.push_back(Either::Right(AnchorRef(anchor_name)));
}
};
},
None => {
emplace_section!();
break;
}
};
}
}
(collect_tangled_output(tangled, anchors, options), errors)
}
fn collect_tangled_output(tangled: Tangled,
mut anchors: BTreeMap<String, Anchor>,
options: OutputOptions) -> Vec<String>
{
let mut lines = Vec::new();
collect_anchor_lines(tangled, &mut anchors, &mut lines, 0, &options);
lines
}
fn maybe_block_header(block: &Block, options: &OutputOptions) -> Option<String> {
match &options.comment {
&Some(ref comment_prefix) => {
let header = format!(
"{} '{}', line {}",
comment_prefix,
&block.file,
block.lineno
);
Some(header)
}
&None => None
}
}
fn collect_anchor_lines(tangled: Tangled,
anchors: &mut BTreeMap<String, Anchor>,
lines: &mut Vec<String>,
indentation: usize,
options: &OutputOptions)
{
use std::iter;
let indent_prefix = iter::repeat(' ').take(indentation).collect::<String>();
for knot in tangled {
match knot {
Either::Left(block) => {
if let Some(comment) = maybe_block_header(&block, options) {
lines.push(indent_prefix.clone() + &comment);
}
for line in block.lines {
lines.push(indent_prefix.clone() + &line);
}
},
Either::Right(AnchorRef(ref anchor_name)) => {
let anchor = anchors.remove(anchor_name)
.expect("invariant violated: anchor name does not exist");
collect_anchor_lines(
anchor.tangled,
anchors,
lines,
indentation + anchor.indentation,
options
);
}
};
}
}
/// We scan through each file block by block.
/// Each block will end in either an anchor tag, or the end of the file.
fn process_block_lines<I>(lines: &mut I, block: &mut Block, errors: &mut Vec<processing_errors::Error>) -> Option<(usize, usize, parsing::Anchor)> where
I: Iterator<Item=(usize, result::Result<String, io::Error>)>
{
use processing_errors::ErrorKind;
use std::ops::Deref;
let filename = block.file.deref();
for (lineno, line) in lines {
match line {
Ok(line) => {
let result = parsing::might_be_anchor(&line)
.ok_or(None)
.and_then(|found| {
parsing::parse(found.as_str())
.map_err(|_| Some(ErrorKind::MalformedAnchor(
filename.clone(),
lineno,
found.as_str().to_string()
).into()))
});
match result {
Ok(anchor) => return Some((lineno, indentation_level(&line), anchor)),
Err(Some(error)) => {
errors.push(error);
block.lines.push(line);
},
Err(None) => {
block.lines.push(line);
}
};
},
Err(_) => errors.push(ErrorKind::NotUTF8(filename.clone(), lineno).into())
};
}
None
}
/// Index of first non-whitespace character.
fn indentation_level(line: &str) -> usize {
use regex::Regex;
let nonwhitespace = Regex::new(r"[^\s]").unwrap();
match nonwhitespace.find(line) {
Some(found) => found.start(),
None => 0
}
}
|
random_line_split
|
|
lib.rs
|
//! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display("error: '{}', line {}: not valid UTF-8", file, lineno)
}
MalformedAnchor(file: String, lineno: usize, anchor: String) {
description("could not parse anchor tag")
display("warn: '{}', line {}: ignoring malformed anchor: '{}'", file, lineno, anchor)
}
DuplicateAnchor(file: String, lineno: usize, tag: String) {
description("found a duplicate anchor tag")
display("warn: '{}', line {}: ignoring duplicate anchor tag: '{}'", file, lineno, tag)
}
MissingTag(file: String, lineno: usize, tag: String) {
description("nonexistent tag name")
display("warn: '{}', line {}: nonexistent tag name: '{}'", file, lineno, tag)
}
}
}
}
use std::rc::Rc;
use std::io;
use std::result;
use std::default::Default;
use std::collections::BTreeMap;
use input::File;
use list::List;
pub struct OutputOptions {
pub comment: Option<String>
}
impl Default for OutputOptions {
fn default() -> Self {
OutputOptions {
comment: None
}
}
}
struct Block {
lines: Vec<String>,
file: Rc<String>,
lineno: usize
}
impl Block {
fn new(file: Rc<String>, lineno: usize) -> Self {
Block {
lines: Vec::new(),
file: file,
lineno: lineno
}
}
}
struct
|
{
indentation: usize, // The *absolute* level of indentation.
tangled: Tangled
}
impl Anchor {
fn new(indentation: usize) -> Self {
Anchor {
indentation: indentation,
tangled: List::new()
}
}
}
/// An `Either` represents the situation when *either* arm is a valid
/// value, as opposed to a `Result`, where one arm designates an error.
enum Either<T, U> {
Left(T),
Right(U)
}
struct AnchorRef(String);
type Tangled = List<Either<Block, AnchorRef>>;
enum OutputTarget {
Insert,
Before(AnchorRef),
After(AnchorRef)
}
/// Process all the literate programming directives in the contents of the
/// given files, return a Vec of output lines (suitable for immediate
/// printing to, say, `stdout`)
pub fn tangle_output(inputs: Vec<File>, options: OutputOptions) -> (Vec<String>, Vec<processing_errors::Error>) {
use std::io::{BufReader, BufRead};
use parsing::Anchor;
use processing_errors::ErrorKind;
let mut tangled = List::new();
let mut anchors = BTreeMap::new();
let mut errors = Vec::new(); // Errors that we accrue during processing.
for input in inputs {
let filename = Rc::new(input.name);
let mut lines = BufReader::new(input.contents)
.lines()
.enumerate()
.map(|(lineno, line)| (lineno + 1, line));
let mut state = OutputTarget::Insert;
let mut tangled_section = List::new();
let mut block = Block::new(filename.clone(), 1);
macro_rules! emplace_section {
() => {
match state {
OutputTarget::Insert => tangled.append_back(&mut tangled_section),
OutputTarget::Before(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_front(&mut tangled_section);
},
OutputTarget::After(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_back(&mut tangled_section);
}
}
}
}
loop {
let next_anchor = process_block_lines(&mut lines, &mut block, &mut errors);
if!block.lines.is_empty() {
tangled_section.push_back(Either::Left(block));
}
match next_anchor {
Some((lineno, indentation, anchor)) => {
macro_rules! has_anchor {
($anchor_name:expr) => {{
if anchors.contains_key($anchor_name) {
true
} else {
let filename: &String = &filename;
let error = ErrorKind::MissingTag(filename.clone(), lineno, $anchor_name.clone()).into();
errors.push(error);
false
}
}}
}
block = Block::new(filename.clone(), lineno);
match anchor {
Anchor::Insert => {
emplace_section!();
tangled_section = List::new();
state = OutputTarget::Insert;
},
Anchor::Before(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::Before(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::After(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::After(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::Label(anchor_name) => {
let anchor = ::Anchor::new(indentation);
anchors.insert(anchor_name.clone(), anchor);
tangled_section.push_back(Either::Right(AnchorRef(anchor_name)));
}
};
},
None => {
emplace_section!();
break;
}
};
}
}
(collect_tangled_output(tangled, anchors, options), errors)
}
fn collect_tangled_output(tangled: Tangled,
mut anchors: BTreeMap<String, Anchor>,
options: OutputOptions) -> Vec<String>
{
let mut lines = Vec::new();
collect_anchor_lines(tangled, &mut anchors, &mut lines, 0, &options);
lines
}
fn maybe_block_header(block: &Block, options: &OutputOptions) -> Option<String> {
match &options.comment {
&Some(ref comment_prefix) => {
let header = format!(
"{} '{}', line {}",
comment_prefix,
&block.file,
block.lineno
);
Some(header)
}
&None => None
}
}
fn collect_anchor_lines(tangled: Tangled,
anchors: &mut BTreeMap<String, Anchor>,
lines: &mut Vec<String>,
indentation: usize,
options: &OutputOptions)
{
use std::iter;
let indent_prefix = iter::repeat(' ').take(indentation).collect::<String>();
for knot in tangled {
match knot {
Either::Left(block) => {
if let Some(comment) = maybe_block_header(&block, options) {
lines.push(indent_prefix.clone() + &comment);
}
for line in block.lines {
lines.push(indent_prefix.clone() + &line);
}
},
Either::Right(AnchorRef(ref anchor_name)) => {
let anchor = anchors.remove(anchor_name)
.expect("invariant violated: anchor name does not exist");
collect_anchor_lines(
anchor.tangled,
anchors,
lines,
indentation + anchor.indentation,
options
);
}
};
}
}
/// We scan through each file block by block.
/// Each block will end in either an anchor tag, or the end of the file.
fn process_block_lines<I>(lines: &mut I, block: &mut Block, errors: &mut Vec<processing_errors::Error>) -> Option<(usize, usize, parsing::Anchor)> where
I: Iterator<Item=(usize, result::Result<String, io::Error>)>
{
use processing_errors::ErrorKind;
use std::ops::Deref;
let filename = block.file.deref();
for (lineno, line) in lines {
match line {
Ok(line) => {
let result = parsing::might_be_anchor(&line)
.ok_or(None)
.and_then(|found| {
parsing::parse(found.as_str())
.map_err(|_| Some(ErrorKind::MalformedAnchor(
filename.clone(),
lineno,
found.as_str().to_string()
).into()))
});
match result {
Ok(anchor) => return Some((lineno, indentation_level(&line), anchor)),
Err(Some(error)) => {
errors.push(error);
block.lines.push(line);
},
Err(None) => {
block.lines.push(line);
}
};
},
Err(_) => errors.push(ErrorKind::NotUTF8(filename.clone(), lineno).into())
};
}
None
}
/// Index of first non-whitespace character.
fn indentation_level(line: &str) -> usize {
use regex::Regex;
let nonwhitespace = Regex::new(r"[^\s]").unwrap();
match nonwhitespace.find(line) {
Some(found) => found.start(),
None => 0
}
}
|
Anchor
|
identifier_name
|
lib.rs
|
//! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display("error: '{}', line {}: not valid UTF-8", file, lineno)
}
MalformedAnchor(file: String, lineno: usize, anchor: String) {
description("could not parse anchor tag")
display("warn: '{}', line {}: ignoring malformed anchor: '{}'", file, lineno, anchor)
}
DuplicateAnchor(file: String, lineno: usize, tag: String) {
description("found a duplicate anchor tag")
display("warn: '{}', line {}: ignoring duplicate anchor tag: '{}'", file, lineno, tag)
}
MissingTag(file: String, lineno: usize, tag: String) {
description("nonexistent tag name")
display("warn: '{}', line {}: nonexistent tag name: '{}'", file, lineno, tag)
}
}
}
}
use std::rc::Rc;
use std::io;
use std::result;
use std::default::Default;
use std::collections::BTreeMap;
use input::File;
use list::List;
pub struct OutputOptions {
pub comment: Option<String>
}
impl Default for OutputOptions {
fn default() -> Self {
OutputOptions {
comment: None
}
}
}
struct Block {
lines: Vec<String>,
file: Rc<String>,
lineno: usize
}
impl Block {
fn new(file: Rc<String>, lineno: usize) -> Self {
Block {
lines: Vec::new(),
file: file,
lineno: lineno
}
}
}
struct Anchor {
indentation: usize, // The *absolute* level of indentation.
tangled: Tangled
}
impl Anchor {
fn new(indentation: usize) -> Self {
Anchor {
indentation: indentation,
tangled: List::new()
}
}
}
/// An `Either` represents the situation when *either* arm is a valid
/// value, as opposed to a `Result`, where one arm designates an error.
enum Either<T, U> {
Left(T),
Right(U)
}
struct AnchorRef(String);
type Tangled = List<Either<Block, AnchorRef>>;
enum OutputTarget {
Insert,
Before(AnchorRef),
After(AnchorRef)
}
/// Process all the literate programming directives in the contents of the
/// given files, return a Vec of output lines (suitable for immediate
/// printing to, say, `stdout`)
pub fn tangle_output(inputs: Vec<File>, options: OutputOptions) -> (Vec<String>, Vec<processing_errors::Error>) {
use std::io::{BufReader, BufRead};
use parsing::Anchor;
use processing_errors::ErrorKind;
let mut tangled = List::new();
let mut anchors = BTreeMap::new();
let mut errors = Vec::new(); // Errors that we accrue during processing.
for input in inputs {
let filename = Rc::new(input.name);
let mut lines = BufReader::new(input.contents)
.lines()
.enumerate()
.map(|(lineno, line)| (lineno + 1, line));
let mut state = OutputTarget::Insert;
let mut tangled_section = List::new();
let mut block = Block::new(filename.clone(), 1);
macro_rules! emplace_section {
() => {
match state {
OutputTarget::Insert => tangled.append_back(&mut tangled_section),
OutputTarget::Before(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_front(&mut tangled_section);
},
OutputTarget::After(AnchorRef(anchor_name)) => {
let anchor: &mut ::Anchor = anchors.get_mut(&anchor_name)
.expect("invariant violated: anchor name does not exist");
anchor.tangled.append_back(&mut tangled_section);
}
}
}
}
loop {
let next_anchor = process_block_lines(&mut lines, &mut block, &mut errors);
if!block.lines.is_empty() {
tangled_section.push_back(Either::Left(block));
}
match next_anchor {
Some((lineno, indentation, anchor)) => {
macro_rules! has_anchor {
($anchor_name:expr) => {{
if anchors.contains_key($anchor_name) {
true
} else {
let filename: &String = &filename;
let error = ErrorKind::MissingTag(filename.clone(), lineno, $anchor_name.clone()).into();
errors.push(error);
false
}
}}
}
block = Block::new(filename.clone(), lineno);
match anchor {
Anchor::Insert => {
emplace_section!();
tangled_section = List::new();
state = OutputTarget::Insert;
},
Anchor::Before(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::Before(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::After(anchor_name) => {
emplace_section!();
tangled_section = List::new();
if has_anchor!(&anchor_name) {
state = OutputTarget::After(AnchorRef(anchor_name));
} else {
state = OutputTarget::Insert;
}
},
Anchor::Label(anchor_name) => {
let anchor = ::Anchor::new(indentation);
anchors.insert(anchor_name.clone(), anchor);
tangled_section.push_back(Either::Right(AnchorRef(anchor_name)));
}
};
},
None => {
emplace_section!();
break;
}
};
}
}
(collect_tangled_output(tangled, anchors, options), errors)
}
fn collect_tangled_output(tangled: Tangled,
mut anchors: BTreeMap<String, Anchor>,
options: OutputOptions) -> Vec<String>
{
let mut lines = Vec::new();
collect_anchor_lines(tangled, &mut anchors, &mut lines, 0, &options);
lines
}
fn maybe_block_header(block: &Block, options: &OutputOptions) -> Option<String>
|
fn collect_anchor_lines(tangled: Tangled,
anchors: &mut BTreeMap<String, Anchor>,
lines: &mut Vec<String>,
indentation: usize,
options: &OutputOptions)
{
use std::iter;
let indent_prefix = iter::repeat(' ').take(indentation).collect::<String>();
for knot in tangled {
match knot {
Either::Left(block) => {
if let Some(comment) = maybe_block_header(&block, options) {
lines.push(indent_prefix.clone() + &comment);
}
for line in block.lines {
lines.push(indent_prefix.clone() + &line);
}
},
Either::Right(AnchorRef(ref anchor_name)) => {
let anchor = anchors.remove(anchor_name)
.expect("invariant violated: anchor name does not exist");
collect_anchor_lines(
anchor.tangled,
anchors,
lines,
indentation + anchor.indentation,
options
);
}
};
}
}
/// We scan through each file block by block.
/// Each block will end in either an anchor tag, or the end of the file.
fn process_block_lines<I>(lines: &mut I, block: &mut Block, errors: &mut Vec<processing_errors::Error>) -> Option<(usize, usize, parsing::Anchor)> where
I: Iterator<Item=(usize, result::Result<String, io::Error>)>
{
use processing_errors::ErrorKind;
use std::ops::Deref;
let filename = block.file.deref();
for (lineno, line) in lines {
match line {
Ok(line) => {
let result = parsing::might_be_anchor(&line)
.ok_or(None)
.and_then(|found| {
parsing::parse(found.as_str())
.map_err(|_| Some(ErrorKind::MalformedAnchor(
filename.clone(),
lineno,
found.as_str().to_string()
).into()))
});
match result {
Ok(anchor) => return Some((lineno, indentation_level(&line), anchor)),
Err(Some(error)) => {
errors.push(error);
block.lines.push(line);
},
Err(None) => {
block.lines.push(line);
}
};
},
Err(_) => errors.push(ErrorKind::NotUTF8(filename.clone(), lineno).into())
};
}
None
}
/// Index of first non-whitespace character.
fn indentation_level(line: &str) -> usize {
use regex::Regex;
let nonwhitespace = Regex::new(r"[^\s]").unwrap();
match nonwhitespace.find(line) {
Some(found) => found.start(),
None => 0
}
}
|
{
match &options.comment {
&Some(ref comment_prefix) => {
let header = format!(
"{} '{}', line {}",
comment_prefix,
&block.file,
block.lineno
);
Some(header)
}
&None => None
}
}
|
identifier_body
|
cargo_test.rs
|
use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
pub only_doc: bool,
}
pub fn run_tests(ws: &Workspace,
options: &TestOptions,
test_args: &[String]) -> CargoResult<Option<CargoTestError>> {
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, mut errors) = if options.only_doc {
assert!(options.compile_opts.filter.is_specific());
run_doc_tests(options, test_args, &compilation)?
} else {
run_unit_tests(options, test_args, &compilation)?
};
// If we have an error and want to fail fast, return
if!errors.is_empty() &&!options.no_fail_fast {
return Ok(Some(CargoTestError::new(test, errors)))
}
// If a specific test was requested or we're not running any tests at all,
// don't run any doc tests.
if options.compile_opts.filter.is_specific() {
match errors.len() {
0 => return Ok(None),
_ => return Ok(Some(CargoTestError::new(test, errors)))
}
}
let (doctest, docerrors) = run_doc_tests(options, test_args, &compilation)?;
let test = if docerrors.is_empty() { test } else { doctest };
errors.extend(docerrors);
if errors.is_empty()
|
else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(ws: &Workspace,
options: &TestOptions,
args: &[String]) -> CargoResult<Option<CargoTestError>> {
let mut args = args.to_vec();
args.push("--bench".to_string());
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, errors) = run_unit_tests(options, &args, &compilation)?;
match errors.len() {
0 => Ok(None),
_ => Ok(Some(CargoTestError::new(test, errors))),
}
}
fn compile_tests<'a>(ws: &Workspace<'a>,
options: &TestOptions<'a>)
-> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2))
});
Ok(compilation)
}
/// Run the unit and integration tests of a project.
fn run_unit_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let config = options.compile_opts.config;
let cwd = options.compile_opts.config.cwd();
let mut errors = Vec::new();
for &(ref pkg, ref kind, ref test, ref exe) in &compilation.tests {
let to_display = match util::without_prefix(exe, cwd) {
Some(path) => path,
None => &**exe,
};
let mut cmd = compilation.target_process(exe, pkg)?;
cmd.args(test_args);
config.shell().concise(|shell| {
shell.status("Running", to_display.display().to_string())
})?;
config.shell().verbose(|shell| {
shell.status("Running", cmd.to_string())
})?;
let result = cmd.exec();
match result {
Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) => {
errors.push((kind.clone(), test.clone(), e));
if!options.no_fail_fast {
break;
}
}
Err(e) => {
//This is an unexpected Cargo error rather than a test failure
return Err(e)
}
Ok(()) => {}
}
}
if errors.len() == 1 {
let (kind, test, e) = errors.pop().unwrap();
Ok((Test::UnitTest(kind, test), vec![e]))
} else {
Ok((Test::Multiple, errors.into_iter().map((|(_, _, e)| e)).collect()))
}
}
fn run_doc_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let mut errors = Vec::new();
let config = options.compile_opts.config;
// We don't build/rust doctests if target!= host
if config.rustc()?.host!= compilation.target {
return Ok((Test::Doc, errors));
}
let libs = compilation.to_doc_test.iter().map(|package| {
(package, package.targets().iter().filter(|t| t.doctested())
.map(|t| (t.src_path(), t.name(), t.crate_name())))
});
for (package, tests) in libs {
for (lib, name, crate_name) in tests {
config.shell().status("Doc-tests", name)?;
let mut p = compilation.rustdoc_process(package)?;
p.arg("--test").arg(lib)
.arg("--crate-name").arg(&crate_name);
for &rust_dep in &[&compilation.deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(rust_dep);
p.arg("-L").arg(arg);
}
for native_dep in compilation.native_dirs.iter() {
p.arg("-L").arg(native_dep);
}
for &host_rust_dep in &[&compilation.host_deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(host_rust_dep);
p.arg("-L").arg(arg);
}
for arg in test_args {
p.arg("--test-args").arg(arg);
}
if let Some(cfgs) = compilation.cfgs.get(package.package_id()) {
for cfg in cfgs.iter() {
p.arg("--cfg").arg(cfg);
}
}
let libs = &compilation.libraries[package.package_id()];
for &(ref target, ref lib) in libs.iter() {
// Note that we can *only* doctest rlib outputs here. A
// staticlib output cannot be linked by the compiler (it just
// doesn't do that). A dylib output, however, can be linked by
// the compiler, but will always fail. Currently all dylibs are
// built as "static dylibs" where the standard library is
// statically linked into the dylib. The doc tests fail,
// however, for now as they try to link the standard library
// dynamically as well, causing problems. As a result we only
// pass `--extern` for rlib deps and skip out on all other
// artifacts.
if lib.extension()!= Some(OsStr::new("rlib")) &&
!target.for_host() {
continue
}
let mut arg = OsString::from(target.crate_name());
arg.push("=");
arg.push(lib);
p.arg("--extern").arg(&arg);
}
config.shell().verbose(|shell| {
shell.status("Running", p.to_string())
})?;
if let Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) = p.exec() {
errors.push(e);
if!options.no_fail_fast {
return Ok((Test::Doc, errors));
}
}
}
}
Ok((Test::Doc, errors))
}
|
{
Ok(None)
}
|
conditional_block
|
cargo_test.rs
|
use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
pub only_doc: bool,
}
pub fn run_tests(ws: &Workspace,
options: &TestOptions,
test_args: &[String]) -> CargoResult<Option<CargoTestError>> {
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, mut errors) = if options.only_doc {
assert!(options.compile_opts.filter.is_specific());
run_doc_tests(options, test_args, &compilation)?
} else {
run_unit_tests(options, test_args, &compilation)?
};
// If we have an error and want to fail fast, return
if!errors.is_empty() &&!options.no_fail_fast {
return Ok(Some(CargoTestError::new(test, errors)))
}
// If a specific test was requested or we're not running any tests at all,
// don't run any doc tests.
if options.compile_opts.filter.is_specific() {
match errors.len() {
0 => return Ok(None),
_ => return Ok(Some(CargoTestError::new(test, errors)))
}
}
let (doctest, docerrors) = run_doc_tests(options, test_args, &compilation)?;
let test = if docerrors.is_empty() { test } else { doctest };
errors.extend(docerrors);
if errors.is_empty() {
Ok(None)
} else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(ws: &Workspace,
options: &TestOptions,
args: &[String]) -> CargoResult<Option<CargoTestError>> {
let mut args = args.to_vec();
args.push("--bench".to_string());
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, errors) = run_unit_tests(options, &args, &compilation)?;
match errors.len() {
0 => Ok(None),
_ => Ok(Some(CargoTestError::new(test, errors))),
}
}
fn
|
<'a>(ws: &Workspace<'a>,
options: &TestOptions<'a>)
-> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2))
});
Ok(compilation)
}
/// Run the unit and integration tests of a project.
fn run_unit_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let config = options.compile_opts.config;
let cwd = options.compile_opts.config.cwd();
let mut errors = Vec::new();
for &(ref pkg, ref kind, ref test, ref exe) in &compilation.tests {
let to_display = match util::without_prefix(exe, cwd) {
Some(path) => path,
None => &**exe,
};
let mut cmd = compilation.target_process(exe, pkg)?;
cmd.args(test_args);
config.shell().concise(|shell| {
shell.status("Running", to_display.display().to_string())
})?;
config.shell().verbose(|shell| {
shell.status("Running", cmd.to_string())
})?;
let result = cmd.exec();
match result {
Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) => {
errors.push((kind.clone(), test.clone(), e));
if!options.no_fail_fast {
break;
}
}
Err(e) => {
//This is an unexpected Cargo error rather than a test failure
return Err(e)
}
Ok(()) => {}
}
}
if errors.len() == 1 {
let (kind, test, e) = errors.pop().unwrap();
Ok((Test::UnitTest(kind, test), vec![e]))
} else {
Ok((Test::Multiple, errors.into_iter().map((|(_, _, e)| e)).collect()))
}
}
fn run_doc_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let mut errors = Vec::new();
let config = options.compile_opts.config;
// We don't build/rust doctests if target!= host
if config.rustc()?.host!= compilation.target {
return Ok((Test::Doc, errors));
}
let libs = compilation.to_doc_test.iter().map(|package| {
(package, package.targets().iter().filter(|t| t.doctested())
.map(|t| (t.src_path(), t.name(), t.crate_name())))
});
for (package, tests) in libs {
for (lib, name, crate_name) in tests {
config.shell().status("Doc-tests", name)?;
let mut p = compilation.rustdoc_process(package)?;
p.arg("--test").arg(lib)
.arg("--crate-name").arg(&crate_name);
for &rust_dep in &[&compilation.deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(rust_dep);
p.arg("-L").arg(arg);
}
for native_dep in compilation.native_dirs.iter() {
p.arg("-L").arg(native_dep);
}
for &host_rust_dep in &[&compilation.host_deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(host_rust_dep);
p.arg("-L").arg(arg);
}
for arg in test_args {
p.arg("--test-args").arg(arg);
}
if let Some(cfgs) = compilation.cfgs.get(package.package_id()) {
for cfg in cfgs.iter() {
p.arg("--cfg").arg(cfg);
}
}
let libs = &compilation.libraries[package.package_id()];
for &(ref target, ref lib) in libs.iter() {
// Note that we can *only* doctest rlib outputs here. A
// staticlib output cannot be linked by the compiler (it just
// doesn't do that). A dylib output, however, can be linked by
// the compiler, but will always fail. Currently all dylibs are
// built as "static dylibs" where the standard library is
// statically linked into the dylib. The doc tests fail,
// however, for now as they try to link the standard library
// dynamically as well, causing problems. As a result we only
// pass `--extern` for rlib deps and skip out on all other
// artifacts.
if lib.extension()!= Some(OsStr::new("rlib")) &&
!target.for_host() {
continue
}
let mut arg = OsString::from(target.crate_name());
arg.push("=");
arg.push(lib);
p.arg("--extern").arg(&arg);
}
config.shell().verbose(|shell| {
shell.status("Running", p.to_string())
})?;
if let Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) = p.exec() {
errors.push(e);
if!options.no_fail_fast {
return Ok((Test::Doc, errors));
}
}
}
}
Ok((Test::Doc, errors))
}
|
compile_tests
|
identifier_name
|
cargo_test.rs
|
use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
pub only_doc: bool,
}
pub fn run_tests(ws: &Workspace,
options: &TestOptions,
test_args: &[String]) -> CargoResult<Option<CargoTestError>> {
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, mut errors) = if options.only_doc {
assert!(options.compile_opts.filter.is_specific());
run_doc_tests(options, test_args, &compilation)?
} else {
run_unit_tests(options, test_args, &compilation)?
};
// If we have an error and want to fail fast, return
if!errors.is_empty() &&!options.no_fail_fast {
return Ok(Some(CargoTestError::new(test, errors)))
}
// If a specific test was requested or we're not running any tests at all,
// don't run any doc tests.
if options.compile_opts.filter.is_specific() {
match errors.len() {
0 => return Ok(None),
_ => return Ok(Some(CargoTestError::new(test, errors)))
}
}
let (doctest, docerrors) = run_doc_tests(options, test_args, &compilation)?;
let test = if docerrors.is_empty() { test } else { doctest };
errors.extend(docerrors);
if errors.is_empty() {
Ok(None)
} else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(ws: &Workspace,
options: &TestOptions,
args: &[String]) -> CargoResult<Option<CargoTestError>> {
let mut args = args.to_vec();
args.push("--bench".to_string());
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, errors) = run_unit_tests(options, &args, &compilation)?;
match errors.len() {
0 => Ok(None),
_ => Ok(Some(CargoTestError::new(test, errors))),
}
}
fn compile_tests<'a>(ws: &Workspace<'a>,
options: &TestOptions<'a>)
-> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
|
});
Ok(compilation)
}
/// Run the unit and integration tests of a project.
fn run_unit_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let config = options.compile_opts.config;
let cwd = options.compile_opts.config.cwd();
let mut errors = Vec::new();
for &(ref pkg, ref kind, ref test, ref exe) in &compilation.tests {
let to_display = match util::without_prefix(exe, cwd) {
Some(path) => path,
None => &**exe,
};
let mut cmd = compilation.target_process(exe, pkg)?;
cmd.args(test_args);
config.shell().concise(|shell| {
shell.status("Running", to_display.display().to_string())
})?;
config.shell().verbose(|shell| {
shell.status("Running", cmd.to_string())
})?;
let result = cmd.exec();
match result {
Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) => {
errors.push((kind.clone(), test.clone(), e));
if!options.no_fail_fast {
break;
}
}
Err(e) => {
//This is an unexpected Cargo error rather than a test failure
return Err(e)
}
Ok(()) => {}
}
}
if errors.len() == 1 {
let (kind, test, e) = errors.pop().unwrap();
Ok((Test::UnitTest(kind, test), vec![e]))
} else {
Ok((Test::Multiple, errors.into_iter().map((|(_, _, e)| e)).collect()))
}
}
fn run_doc_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let mut errors = Vec::new();
let config = options.compile_opts.config;
// We don't build/rust doctests if target!= host
if config.rustc()?.host!= compilation.target {
return Ok((Test::Doc, errors));
}
let libs = compilation.to_doc_test.iter().map(|package| {
(package, package.targets().iter().filter(|t| t.doctested())
.map(|t| (t.src_path(), t.name(), t.crate_name())))
});
for (package, tests) in libs {
for (lib, name, crate_name) in tests {
config.shell().status("Doc-tests", name)?;
let mut p = compilation.rustdoc_process(package)?;
p.arg("--test").arg(lib)
.arg("--crate-name").arg(&crate_name);
for &rust_dep in &[&compilation.deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(rust_dep);
p.arg("-L").arg(arg);
}
for native_dep in compilation.native_dirs.iter() {
p.arg("-L").arg(native_dep);
}
for &host_rust_dep in &[&compilation.host_deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(host_rust_dep);
p.arg("-L").arg(arg);
}
for arg in test_args {
p.arg("--test-args").arg(arg);
}
if let Some(cfgs) = compilation.cfgs.get(package.package_id()) {
for cfg in cfgs.iter() {
p.arg("--cfg").arg(cfg);
}
}
let libs = &compilation.libraries[package.package_id()];
for &(ref target, ref lib) in libs.iter() {
// Note that we can *only* doctest rlib outputs here. A
// staticlib output cannot be linked by the compiler (it just
// doesn't do that). A dylib output, however, can be linked by
// the compiler, but will always fail. Currently all dylibs are
// built as "static dylibs" where the standard library is
// statically linked into the dylib. The doc tests fail,
// however, for now as they try to link the standard library
// dynamically as well, causing problems. As a result we only
// pass `--extern` for rlib deps and skip out on all other
// artifacts.
if lib.extension()!= Some(OsStr::new("rlib")) &&
!target.for_host() {
continue
}
let mut arg = OsString::from(target.crate_name());
arg.push("=");
arg.push(lib);
p.arg("--extern").arg(&arg);
}
config.shell().verbose(|shell| {
shell.status("Running", p.to_string())
})?;
if let Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) = p.exec() {
errors.push(e);
if!options.no_fail_fast {
return Ok((Test::Doc, errors));
}
}
}
}
Ok((Test::Doc, errors))
}
|
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2))
|
random_line_split
|
cargo_test.rs
|
use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
pub only_doc: bool,
}
pub fn run_tests(ws: &Workspace,
options: &TestOptions,
test_args: &[String]) -> CargoResult<Option<CargoTestError>> {
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, mut errors) = if options.only_doc {
assert!(options.compile_opts.filter.is_specific());
run_doc_tests(options, test_args, &compilation)?
} else {
run_unit_tests(options, test_args, &compilation)?
};
// If we have an error and want to fail fast, return
if!errors.is_empty() &&!options.no_fail_fast {
return Ok(Some(CargoTestError::new(test, errors)))
}
// If a specific test was requested or we're not running any tests at all,
// don't run any doc tests.
if options.compile_opts.filter.is_specific() {
match errors.len() {
0 => return Ok(None),
_ => return Ok(Some(CargoTestError::new(test, errors)))
}
}
let (doctest, docerrors) = run_doc_tests(options, test_args, &compilation)?;
let test = if docerrors.is_empty() { test } else { doctest };
errors.extend(docerrors);
if errors.is_empty() {
Ok(None)
} else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(ws: &Workspace,
options: &TestOptions,
args: &[String]) -> CargoResult<Option<CargoTestError>>
|
fn compile_tests<'a>(ws: &Workspace<'a>,
options: &TestOptions<'a>)
-> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2))
});
Ok(compilation)
}
/// Run the unit and integration tests of a project.
fn run_unit_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let config = options.compile_opts.config;
let cwd = options.compile_opts.config.cwd();
let mut errors = Vec::new();
for &(ref pkg, ref kind, ref test, ref exe) in &compilation.tests {
let to_display = match util::without_prefix(exe, cwd) {
Some(path) => path,
None => &**exe,
};
let mut cmd = compilation.target_process(exe, pkg)?;
cmd.args(test_args);
config.shell().concise(|shell| {
shell.status("Running", to_display.display().to_string())
})?;
config.shell().verbose(|shell| {
shell.status("Running", cmd.to_string())
})?;
let result = cmd.exec();
match result {
Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) => {
errors.push((kind.clone(), test.clone(), e));
if!options.no_fail_fast {
break;
}
}
Err(e) => {
//This is an unexpected Cargo error rather than a test failure
return Err(e)
}
Ok(()) => {}
}
}
if errors.len() == 1 {
let (kind, test, e) = errors.pop().unwrap();
Ok((Test::UnitTest(kind, test), vec![e]))
} else {
Ok((Test::Multiple, errors.into_iter().map((|(_, _, e)| e)).collect()))
}
}
fn run_doc_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let mut errors = Vec::new();
let config = options.compile_opts.config;
// We don't build/rust doctests if target!= host
if config.rustc()?.host!= compilation.target {
return Ok((Test::Doc, errors));
}
let libs = compilation.to_doc_test.iter().map(|package| {
(package, package.targets().iter().filter(|t| t.doctested())
.map(|t| (t.src_path(), t.name(), t.crate_name())))
});
for (package, tests) in libs {
for (lib, name, crate_name) in tests {
config.shell().status("Doc-tests", name)?;
let mut p = compilation.rustdoc_process(package)?;
p.arg("--test").arg(lib)
.arg("--crate-name").arg(&crate_name);
for &rust_dep in &[&compilation.deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(rust_dep);
p.arg("-L").arg(arg);
}
for native_dep in compilation.native_dirs.iter() {
p.arg("-L").arg(native_dep);
}
for &host_rust_dep in &[&compilation.host_deps_output] {
let mut arg = OsString::from("dependency=");
arg.push(host_rust_dep);
p.arg("-L").arg(arg);
}
for arg in test_args {
p.arg("--test-args").arg(arg);
}
if let Some(cfgs) = compilation.cfgs.get(package.package_id()) {
for cfg in cfgs.iter() {
p.arg("--cfg").arg(cfg);
}
}
let libs = &compilation.libraries[package.package_id()];
for &(ref target, ref lib) in libs.iter() {
// Note that we can *only* doctest rlib outputs here. A
// staticlib output cannot be linked by the compiler (it just
// doesn't do that). A dylib output, however, can be linked by
// the compiler, but will always fail. Currently all dylibs are
// built as "static dylibs" where the standard library is
// statically linked into the dylib. The doc tests fail,
// however, for now as they try to link the standard library
// dynamically as well, causing problems. As a result we only
// pass `--extern` for rlib deps and skip out on all other
// artifacts.
if lib.extension()!= Some(OsStr::new("rlib")) &&
!target.for_host() {
continue
}
let mut arg = OsString::from(target.crate_name());
arg.push("=");
arg.push(lib);
p.arg("--extern").arg(&arg);
}
config.shell().verbose(|shell| {
shell.status("Running", p.to_string())
})?;
if let Err(CargoError(CargoErrorKind::ProcessErrorKind(e),.. )) = p.exec() {
errors.push(e);
if!options.no_fail_fast {
return Ok((Test::Doc, errors));
}
}
}
}
Ok((Test::Doc, errors))
}
|
{
let mut args = args.to_vec();
args.push("--bench".to_string());
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, errors) = run_unit_tests(options, &args, &compilation)?;
match errors.len() {
0 => Ok(None),
_ => Ok(Some(CargoTestError::new(test, errors))),
}
}
|
identifier_body
|
tests.rs
|
pub use datatypes::{GridSettings, Region, ResizeRule, SplitKind, SaveGrid};
pub use datatypes::ResizeRule::*;
pub use datatypes::SplitKind::*;
pub use terminal::interfaces::{Resizeable, ConstructGrid};
pub use super::panel::Panel;
pub use super::panel::Panel::*;
pub use super::ring::Ring;
pub use super::section::ScreenSection;
pub use super::split::SplitSection;
|
(self.0, self.1)
}
fn resize_width(&mut self, width: u32) {
self.0 = width;
}
fn resize_height(&mut self, height: u32) {
self.1 = height;
}
}
impl ConstructGrid for MockFill {
fn new(settings: GridSettings) -> MockFill {
MockFill(settings.width, settings.height)
}
}
pub const GRID: MockFill = MockFill(8, 8);
pub const OLD_AREA: Region = Region { left: 0, top: 2, right: 8, bottom: 10 };
pub const NEW_AREA: Region = Region { left: 1, top: 1, right: 7, bottom: 11 };
|
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MockFill(pub u32, pub u32);
impl Resizeable for MockFill {
fn dims(&self) -> (u32, u32) {
|
random_line_split
|
tests.rs
|
pub use datatypes::{GridSettings, Region, ResizeRule, SplitKind, SaveGrid};
pub use datatypes::ResizeRule::*;
pub use datatypes::SplitKind::*;
pub use terminal::interfaces::{Resizeable, ConstructGrid};
pub use super::panel::Panel;
pub use super::panel::Panel::*;
pub use super::ring::Ring;
pub use super::section::ScreenSection;
pub use super::split::SplitSection;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MockFill(pub u32, pub u32);
impl Resizeable for MockFill {
fn dims(&self) -> (u32, u32) {
(self.0, self.1)
}
fn resize_width(&mut self, width: u32) {
self.0 = width;
}
fn resize_height(&mut self, height: u32)
|
}
impl ConstructGrid for MockFill {
fn new(settings: GridSettings) -> MockFill {
MockFill(settings.width, settings.height)
}
}
pub const GRID: MockFill = MockFill(8, 8);
pub const OLD_AREA: Region = Region { left: 0, top: 2, right: 8, bottom: 10 };
pub const NEW_AREA: Region = Region { left: 1, top: 1, right: 7, bottom: 11 };
|
{
self.1 = height;
}
|
identifier_body
|
tests.rs
|
pub use datatypes::{GridSettings, Region, ResizeRule, SplitKind, SaveGrid};
pub use datatypes::ResizeRule::*;
pub use datatypes::SplitKind::*;
pub use terminal::interfaces::{Resizeable, ConstructGrid};
pub use super::panel::Panel;
pub use super::panel::Panel::*;
pub use super::ring::Ring;
pub use super::section::ScreenSection;
pub use super::split::SplitSection;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MockFill(pub u32, pub u32);
impl Resizeable for MockFill {
fn
|
(&self) -> (u32, u32) {
(self.0, self.1)
}
fn resize_width(&mut self, width: u32) {
self.0 = width;
}
fn resize_height(&mut self, height: u32) {
self.1 = height;
}
}
impl ConstructGrid for MockFill {
fn new(settings: GridSettings) -> MockFill {
MockFill(settings.width, settings.height)
}
}
pub const GRID: MockFill = MockFill(8, 8);
pub const OLD_AREA: Region = Region { left: 0, top: 2, right: 8, bottom: 10 };
pub const NEW_AREA: Region = Region { left: 1, top: 1, right: 7, bottom: 11 };
|
dims
|
identifier_name
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
use std::os;
use std::task;
use std::time::Duration;
use std::uint;
fn move_out<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.recv_opt() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
count += b;
}
Err(..) => { done = true; }
_ => { }
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1].as_slice()).unwrap();
let workers = from_str::<uint>(args[2].as_slice()).unwrap();
let num_bytes = 100;
let mut result = None;
let mut to_parent = Some(to_parent);
let dur = Duration::span(|| {
let to_parent = to_parent.take().unwrap();
let mut worker_results = Vec::new();
let from_parent = if workers == 1 {
let (to_child, from_parent) = channel();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
from_parent
} else {
let (to_child, from_parent) = channel();
for _ in range(0u, workers) {
let to_child = to_child.clone();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
}
from_parent
};
task::spawn(proc() {
server(&from_parent, &to_parent);
});
for r in worker_results.into_iter() {
r.unwrap();
}
//println!("sending stop message");
//to_child.send(stop);
//move_out(to_child);
result = Some(from_child.recv());
});
let result = result.unwrap();
print!("Count is {}\n", result);
print!("Test took {} ms\n", dur.num_milliseconds());
let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64);
print!("Throughput={} per sec\n", thruput / 1000.0);
assert_eq!(result, num_bytes * size);
}
fn main()
|
{
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "1000000".to_string(), "8".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
args.clone().into_iter().map(|x| x.to_string()).collect()
};
println!("{}", args);
run(args.as_slice());
}
|
identifier_body
|
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
use std::os;
use std::task;
use std::time::Duration;
use std::uint;
fn move_out<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.recv_opt() {
Ok(request::get_count) =>
|
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
count += b;
}
Err(..) => { done = true; }
_ => { }
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1].as_slice()).unwrap();
let workers = from_str::<uint>(args[2].as_slice()).unwrap();
let num_bytes = 100;
let mut result = None;
let mut to_parent = Some(to_parent);
let dur = Duration::span(|| {
let to_parent = to_parent.take().unwrap();
let mut worker_results = Vec::new();
let from_parent = if workers == 1 {
let (to_child, from_parent) = channel();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
from_parent
} else {
let (to_child, from_parent) = channel();
for _ in range(0u, workers) {
let to_child = to_child.clone();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
}
from_parent
};
task::spawn(proc() {
server(&from_parent, &to_parent);
});
for r in worker_results.into_iter() {
r.unwrap();
}
//println!("sending stop message");
//to_child.send(stop);
//move_out(to_child);
result = Some(from_child.recv());
});
let result = result.unwrap();
print!("Count is {}\n", result);
print!("Test took {} ms\n", dur.num_milliseconds());
let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64);
print!("Throughput={} per sec\n", thruput / 1000.0);
assert_eq!(result, num_bytes * size);
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "1000000".to_string(), "8".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
args.clone().into_iter().map(|x| x.to_string()).collect()
};
println!("{}", args);
run(args.as_slice());
}
|
{ responses.send(count.clone()); }
|
conditional_block
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
use std::os;
use std::task;
use std::time::Duration;
use std::uint;
fn
|
<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.recv_opt() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
count += b;
}
Err(..) => { done = true; }
_ => { }
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1].as_slice()).unwrap();
let workers = from_str::<uint>(args[2].as_slice()).unwrap();
let num_bytes = 100;
let mut result = None;
let mut to_parent = Some(to_parent);
let dur = Duration::span(|| {
let to_parent = to_parent.take().unwrap();
let mut worker_results = Vec::new();
let from_parent = if workers == 1 {
let (to_child, from_parent) = channel();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
from_parent
} else {
let (to_child, from_parent) = channel();
for _ in range(0u, workers) {
let to_child = to_child.clone();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
}
from_parent
};
task::spawn(proc() {
server(&from_parent, &to_parent);
});
for r in worker_results.into_iter() {
r.unwrap();
}
//println!("sending stop message");
//to_child.send(stop);
//move_out(to_child);
result = Some(from_child.recv());
});
let result = result.unwrap();
print!("Count is {}\n", result);
print!("Test took {} ms\n", dur.num_milliseconds());
let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64);
print!("Throughput={} per sec\n", thruput / 1000.0);
assert_eq!(result, num_bytes * size);
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "1000000".to_string(), "8".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
args.clone().into_iter().map(|x| x.to_string()).collect()
};
println!("{}", args);
run(args.as_slice());
}
|
move_out
|
identifier_name
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
use std::os;
use std::task;
use std::time::Duration;
use std::uint;
fn move_out<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.recv_opt() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
|
_ => { }
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1].as_slice()).unwrap();
let workers = from_str::<uint>(args[2].as_slice()).unwrap();
let num_bytes = 100;
let mut result = None;
let mut to_parent = Some(to_parent);
let dur = Duration::span(|| {
let to_parent = to_parent.take().unwrap();
let mut worker_results = Vec::new();
let from_parent = if workers == 1 {
let (to_child, from_parent) = channel();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
from_parent
} else {
let (to_child, from_parent) = channel();
for _ in range(0u, workers) {
let to_child = to_child.clone();
worker_results.push(task::try_future(proc() {
for _ in range(0u, size / workers) {
//println!("worker {}: sending {} bytes", i, num_bytes);
to_child.send(request::bytes(num_bytes));
}
//println!("worker {} exiting", i);
}));
}
from_parent
};
task::spawn(proc() {
server(&from_parent, &to_parent);
});
for r in worker_results.into_iter() {
r.unwrap();
}
//println!("sending stop message");
//to_child.send(stop);
//move_out(to_child);
result = Some(from_child.recv());
});
let result = result.unwrap();
print!("Count is {}\n", result);
print!("Test took {} ms\n", dur.num_milliseconds());
let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64);
print!("Throughput={} per sec\n", thruput / 1000.0);
assert_eq!(result, num_bytes * size);
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "1000000".to_string(), "8".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
args.clone().into_iter().map(|x| x.to_string()).collect()
};
println!("{}", args);
run(args.as_slice());
}
|
count += b;
}
Err(..) => { done = true; }
|
random_line_split
|
union-borrow-move-parent-sibling.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.
#![feature(untagged_unions)]
#![allow(unused)]
#[allow(unions_with_drop_fields)]
union U {
x: ((Vec<u8>, Vec<u8>), Vec<u8>),
y: Box<Vec<u8>>,
}
|
unsafe fn parent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut u.x.0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn parent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = u.x.0;
let b = u.y; //~ ERROR use of moved value: `u.y`
}
unsafe fn grandparent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut (u.x.0).0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn grandparent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = (u.x.0).0;
let b = u.y; //~ ERROR use of moved value: `u.y`
}
unsafe fn deref_sibling_borrow() {
let mut u = U { y: Box::default() };
let a = &mut *u.y;
let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`)
use_borrow(a);
}
unsafe fn deref_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = *u.y;
let b = u.x; //~ ERROR use of moved value: `u.x`
}
fn main() {}
|
fn use_borrow<T>(_: &T) {}
|
random_line_split
|
union-borrow-move-parent-sibling.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.
#![feature(untagged_unions)]
#![allow(unused)]
#[allow(unions_with_drop_fields)]
union U {
x: ((Vec<u8>, Vec<u8>), Vec<u8>),
y: Box<Vec<u8>>,
}
fn use_borrow<T>(_: &T) {}
unsafe fn parent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut u.x.0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn parent_sibling_move()
|
unsafe fn grandparent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut (u.x.0).0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn grandparent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = (u.x.0).0;
let b = u.y; //~ ERROR use of moved value: `u.y`
}
unsafe fn deref_sibling_borrow() {
let mut u = U { y: Box::default() };
let a = &mut *u.y;
let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`)
use_borrow(a);
}
unsafe fn deref_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = *u.y;
let b = u.x; //~ ERROR use of moved value: `u.x`
}
fn main() {}
|
{
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = u.x.0;
let b = u.y; //~ ERROR use of moved value: `u.y`
}
|
identifier_body
|
union-borrow-move-parent-sibling.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.
#![feature(untagged_unions)]
#![allow(unused)]
#[allow(unions_with_drop_fields)]
union U {
x: ((Vec<u8>, Vec<u8>), Vec<u8>),
y: Box<Vec<u8>>,
}
fn use_borrow<T>(_: &T) {}
unsafe fn parent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut u.x.0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn parent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = u.x.0;
let b = u.y; //~ ERROR use of moved value: `u.y`
}
unsafe fn grandparent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut (u.x.0).0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn grandparent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = (u.x.0).0;
let b = u.y; //~ ERROR use of moved value: `u.y`
}
unsafe fn
|
() {
let mut u = U { y: Box::default() };
let a = &mut *u.y;
let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`)
use_borrow(a);
}
unsafe fn deref_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = *u.y;
let b = u.x; //~ ERROR use of moved value: `u.x`
}
fn main() {}
|
deref_sibling_borrow
|
identifier_name
|
send_receive.rs
|
#![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn
|
() {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } else { 0 };
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } else { size - 1 };
let previous_process = world.process_at_rank(previous_rank);
let (msg, status): (Rank, _) = p2p::send_receive(&rank, &previous_process, &next_process);
println!("Process {} got message {}.\nStatus is: {:?}", rank, msg, status);
world.barrier();
assert_eq!(msg, next_rank);
if rank > 0 {
let msg = vec![rank, rank + 1, rank - 1];
world.process_at_rank(0).send(&msg[..]);
} else {
for _ in 1..size {
let (msg, status) = world.any_process().receive_vec::<Rank>();
println!("Process {} got long message {:?}.\nStatus is: {:?}", rank, msg, status);
let x = status.source_rank();
let v = vec![x, x + 1, x - 1];
assert_eq!(v, msg);
}
}
world.barrier();
let mut x = rank;
p2p::send_receive_replace_into(&mut x, &next_process, &previous_process);
assert_eq!(x, previous_rank);
}
|
main
|
identifier_name
|
send_receive.rs
|
#![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn main() {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } else
|
;
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } else { size - 1 };
let previous_process = world.process_at_rank(previous_rank);
let (msg, status): (Rank, _) = p2p::send_receive(&rank, &previous_process, &next_process);
println!("Process {} got message {}.\nStatus is: {:?}", rank, msg, status);
world.barrier();
assert_eq!(msg, next_rank);
if rank > 0 {
let msg = vec![rank, rank + 1, rank - 1];
world.process_at_rank(0).send(&msg[..]);
} else {
for _ in 1..size {
let (msg, status) = world.any_process().receive_vec::<Rank>();
println!("Process {} got long message {:?}.\nStatus is: {:?}", rank, msg, status);
let x = status.source_rank();
let v = vec![x, x + 1, x - 1];
assert_eq!(v, msg);
}
}
world.barrier();
let mut x = rank;
p2p::send_receive_replace_into(&mut x, &next_process, &previous_process);
assert_eq!(x, previous_rank);
}
|
{ 0 }
|
conditional_block
|
send_receive.rs
|
#![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn main() {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } else { 0 };
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } else { size - 1 };
let previous_process = world.process_at_rank(previous_rank);
let (msg, status): (Rank, _) = p2p::send_receive(&rank, &previous_process, &next_process);
println!("Process {} got message {}.\nStatus is: {:?}", rank, msg, status);
world.barrier();
assert_eq!(msg, next_rank);
if rank > 0 {
let msg = vec![rank, rank + 1, rank - 1];
world.process_at_rank(0).send(&msg[..]);
} else {
for _ in 1..size {
|
let x = status.source_rank();
let v = vec![x, x + 1, x - 1];
assert_eq!(v, msg);
}
}
world.barrier();
let mut x = rank;
p2p::send_receive_replace_into(&mut x, &next_process, &previous_process);
assert_eq!(x, previous_rank);
}
|
let (msg, status) = world.any_process().receive_vec::<Rank>();
println!("Process {} got long message {:?}.\nStatus is: {:?}", rank, msg, status);
|
random_line_split
|
send_receive.rs
|
#![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn main()
|
for _ in 1..size {
let (msg, status) = world.any_process().receive_vec::<Rank>();
println!("Process {} got long message {:?}.\nStatus is: {:?}", rank, msg, status);
let x = status.source_rank();
let v = vec![x, x + 1, x - 1];
assert_eq!(v, msg);
}
}
world.barrier();
let mut x = rank;
p2p::send_receive_replace_into(&mut x, &next_process, &previous_process);
assert_eq!(x, previous_rank);
}
|
{
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } else { 0 };
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } else { size - 1 };
let previous_process = world.process_at_rank(previous_rank);
let (msg, status): (Rank, _) = p2p::send_receive(&rank, &previous_process, &next_process);
println!("Process {} got message {}.\nStatus is: {:?}", rank, msg, status);
world.barrier();
assert_eq!(msg, next_rank);
if rank > 0 {
let msg = vec![rank, rank + 1, rank - 1];
world.process_at_rank(0).send(&msg[..]);
} else {
|
identifier_body
|
table_caption.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::BlockFlow;
use construct::FlowConstructor;
use context::LayoutContext;
use flow::{TableCaptionFlowClass, FlowClass, Flow};
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_node(constructor: &mut FlowConstructor,
node: &ThreadSafeLayoutNode)
-> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_node(constructor, node)
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
TableCaptionFlowClass
}
fn as_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn
|
(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
}
impl fmt::Show for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {}", self.block_flow)
}
}
|
update_late_computed_block_position_if_necessary
|
identifier_name
|
table_caption.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::BlockFlow;
use construct::FlowConstructor;
use context::LayoutContext;
use flow::{TableCaptionFlowClass, FlowClass, Flow};
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_node(constructor: &mut FlowConstructor,
node: &ThreadSafeLayoutNode)
-> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_node(constructor, node)
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
TableCaptionFlowClass
}
fn as_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow
|
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
}
impl fmt::Show for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {}", self.block_flow)
}
}
|
{
&mut self.block_flow
}
|
identifier_body
|
table_caption.rs
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::BlockFlow;
use construct::FlowConstructor;
use context::LayoutContext;
use flow::{TableCaptionFlowClass, FlowClass, Flow};
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_node(constructor: &mut FlowConstructor,
node: &ThreadSafeLayoutNode)
-> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_node(constructor, node)
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
TableCaptionFlowClass
}
fn as_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
}
impl fmt::Show for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {}", self.block_flow)
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
random_line_split
|
|
malformed-param-list.rs
|
#![feature(plugin)]
#![plugin(rocket_codegen)]
#[get("/><")] //~ ERROR malformed
fn get() -> &'static str { "hi" }
#[get("/<name><")] //~ ERROR malformed
fn get1(name: &str) -> &'static str { "hi" }
#[get("/<<<<name><")] //~ ERROR malformed
fn get2(name: &str) -> &'static str { "hi" }
#[get("/<!>")] //~ ERROR identifiers
fn get3() -> &'static str { "hi" }
#[get("/<_>")] //~ ERROR ignored
fn get4() -> &'static str { "hi" }
#[get("/<1>")] //~ ERROR identifiers
fn get5() -> &'static str { "hi" }
#[get("/<>name><")] //~ ERROR malformed
fn get6() -> &'static str { "hi" }
#[get("/<name>:<id>")] //~ ERROR identifiers
fn get7() -> &'static str
|
#[get("/<>")] //~ ERROR empty
fn get8() -> &'static str { "hi" }
fn main() { }
|
{ "hi" }
|
identifier_body
|
malformed-param-list.rs
|
#![feature(plugin)]
#![plugin(rocket_codegen)]
#[get("/><")] //~ ERROR malformed
fn get() -> &'static str { "hi" }
#[get("/<name><")] //~ ERROR malformed
fn get1(name: &str) -> &'static str { "hi" }
#[get("/<<<<name><")] //~ ERROR malformed
fn get2(name: &str) -> &'static str { "hi" }
#[get("/<!>")] //~ ERROR identifiers
fn get3() -> &'static str { "hi" }
#[get("/<_>")] //~ ERROR ignored
fn get4() -> &'static str { "hi" }
#[get("/<1>")] //~ ERROR identifiers
fn get5() -> &'static str { "hi" }
|
#[get("/<>")] //~ ERROR empty
fn get8() -> &'static str { "hi" }
fn main() { }
|
#[get("/<>name><")] //~ ERROR malformed
fn get6() -> &'static str { "hi" }
#[get("/<name>:<id>")] //~ ERROR identifiers
fn get7() -> &'static str { "hi" }
|
random_line_split
|
malformed-param-list.rs
|
#![feature(plugin)]
#![plugin(rocket_codegen)]
#[get("/><")] //~ ERROR malformed
fn
|
() -> &'static str { "hi" }
#[get("/<name><")] //~ ERROR malformed
fn get1(name: &str) -> &'static str { "hi" }
#[get("/<<<<name><")] //~ ERROR malformed
fn get2(name: &str) -> &'static str { "hi" }
#[get("/<!>")] //~ ERROR identifiers
fn get3() -> &'static str { "hi" }
#[get("/<_>")] //~ ERROR ignored
fn get4() -> &'static str { "hi" }
#[get("/<1>")] //~ ERROR identifiers
fn get5() -> &'static str { "hi" }
#[get("/<>name><")] //~ ERROR malformed
fn get6() -> &'static str { "hi" }
#[get("/<name>:<id>")] //~ ERROR identifiers
fn get7() -> &'static str { "hi" }
#[get("/<>")] //~ ERROR empty
fn get8() -> &'static str { "hi" }
fn main() { }
|
get
|
identifier_name
|
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_c_int_width: "32".to_string(),
target_os: "emscripten".to_string(),
target_env: String::new(),
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,
})
}
|
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
|
random_line_split
|
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>
|
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: String::new(),
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,
})
}
|
{
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,
|
identifier_body
|
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
|
() -> 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: String::new(),
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,
})
}
|
target
|
identifier_name
|
lib.rs
|
#[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
/// # Errors
///
|
) -> Result<D, Vec<String>> {
let data = req.send().await.map_err(|e| vec![format!("{:?}", e)])?;
let decode: reqwest::Result<graphql_client::Response<D>> = data.json().await;
let body = decode.map_err(|e| vec![format!("{:?}", e)])?;
match body.data {
Some(d) => Ok(d),
None => Err(match body.errors {
Some(errors) => parse_errors(errors),
None => vec!["hasura missing data".to_string()],
}),
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn hasura_request<T: serde::Serialize, D: serde::de::DeserializeOwned>(
client: &reqwest::Client,
graphql_endpoint: &url::Url,
hasura_admin_secret: &str,
body: T,
) -> Result<D, Vec<String>> {
let req = client
.post(graphql_endpoint.as_str())
.header("x-hasura-admin-secret", hasura_admin_secret.as_bytes())
.json(&body);
graphql_request(req).await
}
fn parse_errors(errors: Vec<graphql_client::Error>) -> Vec<String> {
errors
.into_iter()
.map(|e| {
let internal = e
.extensions
.as_ref()
.and_then(|ext| ext.get("internal"))
.and_then(|v| serde_json::from_value::<HasuraError>(v.clone()).ok())
.map(|x| x.error);
match internal {
Some(h_err) => {
format!("{}\n{:?}", e.message, h_err)
}
None => e.message,
}
})
.collect()
}
|
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn graphql_request<D: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
|
random_line_split
|
lib.rs
|
#[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn graphql_request<D: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
) -> Result<D, Vec<String>> {
let data = req.send().await.map_err(|e| vec![format!("{:?}", e)])?;
let decode: reqwest::Result<graphql_client::Response<D>> = data.json().await;
let body = decode.map_err(|e| vec![format!("{:?}", e)])?;
match body.data {
Some(d) => Ok(d),
None => Err(match body.errors {
Some(errors) => parse_errors(errors),
None => vec!["hasura missing data".to_string()],
}),
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn hasura_request<T: serde::Serialize, D: serde::de::DeserializeOwned>(
client: &reqwest::Client,
graphql_endpoint: &url::Url,
hasura_admin_secret: &str,
body: T,
) -> Result<D, Vec<String>> {
let req = client
.post(graphql_endpoint.as_str())
.header("x-hasura-admin-secret", hasura_admin_secret.as_bytes())
.json(&body);
graphql_request(req).await
}
fn parse_errors(errors: Vec<graphql_client::Error>) -> Vec<String> {
errors
.into_iter()
.map(|e| {
let internal = e
.extensions
.as_ref()
.and_then(|ext| ext.get("internal"))
.and_then(|v| serde_json::from_value::<HasuraError>(v.clone()).ok())
.map(|x| x.error);
match internal {
Some(h_err) =>
|
None => e.message,
}
})
.collect()
}
|
{
format!("{}\n{:?}", e.message, h_err)
}
|
conditional_block
|
lib.rs
|
#[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn graphql_request<D: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
) -> Result<D, Vec<String>> {
let data = req.send().await.map_err(|e| vec![format!("{:?}", e)])?;
let decode: reqwest::Result<graphql_client::Response<D>> = data.json().await;
let body = decode.map_err(|e| vec![format!("{:?}", e)])?;
match body.data {
Some(d) => Ok(d),
None => Err(match body.errors {
Some(errors) => parse_errors(errors),
None => vec!["hasura missing data".to_string()],
}),
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn hasura_request<T: serde::Serialize, D: serde::de::DeserializeOwned>(
client: &reqwest::Client,
graphql_endpoint: &url::Url,
hasura_admin_secret: &str,
body: T,
) -> Result<D, Vec<String>> {
let req = client
.post(graphql_endpoint.as_str())
.header("x-hasura-admin-secret", hasura_admin_secret.as_bytes())
.json(&body);
graphql_request(req).await
}
fn
|
(errors: Vec<graphql_client::Error>) -> Vec<String> {
errors
.into_iter()
.map(|e| {
let internal = e
.extensions
.as_ref()
.and_then(|ext| ext.get("internal"))
.and_then(|v| serde_json::from_value::<HasuraError>(v.clone()).ok())
.map(|x| x.error);
match internal {
Some(h_err) => {
format!("{}\n{:?}", e.message, h_err)
}
None => e.message,
}
})
.collect()
}
|
parse_errors
|
identifier_name
|
lib.rs
|
#[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn graphql_request<D: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
) -> Result<D, Vec<String>> {
let data = req.send().await.map_err(|e| vec![format!("{:?}", e)])?;
let decode: reqwest::Result<graphql_client::Response<D>> = data.json().await;
let body = decode.map_err(|e| vec![format!("{:?}", e)])?;
match body.data {
Some(d) => Ok(d),
None => Err(match body.errors {
Some(errors) => parse_errors(errors),
None => vec!["hasura missing data".to_string()],
}),
}
}
/// # Errors
///
/// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn hasura_request<T: serde::Serialize, D: serde::de::DeserializeOwned>(
client: &reqwest::Client,
graphql_endpoint: &url::Url,
hasura_admin_secret: &str,
body: T,
) -> Result<D, Vec<String>>
|
fn parse_errors(errors: Vec<graphql_client::Error>) -> Vec<String> {
errors
.into_iter()
.map(|e| {
let internal = e
.extensions
.as_ref()
.and_then(|ext| ext.get("internal"))
.and_then(|v| serde_json::from_value::<HasuraError>(v.clone()).ok())
.map(|x| x.error);
match internal {
Some(h_err) => {
format!("{}\n{:?}", e.message, h_err)
}
None => e.message,
}
})
.collect()
}
|
{
let req = client
.post(graphql_endpoint.as_str())
.header("x-hasura-admin-secret", hasura_admin_secret.as_bytes())
.json(&body);
graphql_request(req).await
}
|
identifier_body
|
object-one-type-two-traits.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.
// run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// Testing creating two vtables with the same self type, but different
// traits.
#![feature(box_syntax)]
use std::any::Any;
trait Wrap {
fn get(&self) -> isize;
fn wrap(self: Box<Self>) -> Box<Any+'static>;
}
|
self as Box<Any+'static>
}
}
fn is<T:Any>(x: &Any) -> bool {
x.is::<T>()
}
fn main() {
let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
}
|
impl Wrap for isize {
fn get(&self) -> isize {
*self
}
fn wrap(self: Box<isize>) -> Box<Any+'static> {
|
random_line_split
|
object-one-type-two-traits.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.
// run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// Testing creating two vtables with the same self type, but different
// traits.
#![feature(box_syntax)]
use std::any::Any;
trait Wrap {
fn get(&self) -> isize;
fn wrap(self: Box<Self>) -> Box<Any+'static>;
}
impl Wrap for isize {
fn get(&self) -> isize {
*self
}
fn wrap(self: Box<isize>) -> Box<Any+'static> {
self as Box<Any+'static>
}
}
fn is<T:Any>(x: &Any) -> bool {
x.is::<T>()
}
fn main()
|
{
let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
}
|
identifier_body
|
|
object-one-type-two-traits.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.
// run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// Testing creating two vtables with the same self type, but different
// traits.
#![feature(box_syntax)]
use std::any::Any;
trait Wrap {
fn get(&self) -> isize;
fn wrap(self: Box<Self>) -> Box<Any+'static>;
}
impl Wrap for isize {
fn get(&self) -> isize {
*self
}
fn wrap(self: Box<isize>) -> Box<Any+'static> {
self as Box<Any+'static>
}
}
fn
|
<T:Any>(x: &Any) -> bool {
x.is::<T>()
}
fn main() {
let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
}
|
is
|
identifier_name
|
enum_and_vtable_mangling.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub const match_: _bindgen_ty_1 = _bindgen_ty_1::match_;
pub const whatever_else: _bindgen_ty_1 = _bindgen_ty_1::whatever_else;
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_1 {
match_ = 0,
whatever_else = 1,
}
#[repr(C)]
pub struct C__bindgen_vtable(::std::os::raw::c_void);
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct C {
pub vtable_: *const C__bindgen_vtable,
pub i: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_C() {
assert_eq!(
::std::mem::size_of::<C>(),
16usize,
concat!("Size of: ", stringify!(C))
);
assert_eq!(
::std::mem::align_of::<C>(),
|
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<C>())).i as *const _ as usize },
8usize,
concat!("Offset of field: ", stringify!(C), "::", stringify!(i))
);
}
impl Default for C {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
extern "C" {
#[link_name = "\u{1}_ZN1C5matchEv"]
pub fn C_match(this: *mut ::std::os::raw::c_void);
}
|
8usize,
concat!("Alignment of ", stringify!(C))
|
random_line_split
|
enum_and_vtable_mangling.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub const match_: _bindgen_ty_1 = _bindgen_ty_1::match_;
pub const whatever_else: _bindgen_ty_1 = _bindgen_ty_1::whatever_else;
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_1 {
match_ = 0,
whatever_else = 1,
}
#[repr(C)]
pub struct C__bindgen_vtable(::std::os::raw::c_void);
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct C {
pub vtable_: *const C__bindgen_vtable,
pub i: ::std::os::raw::c_int,
}
#[test]
fn
|
() {
assert_eq!(
::std::mem::size_of::<C>(),
16usize,
concat!("Size of: ", stringify!(C))
);
assert_eq!(
::std::mem::align_of::<C>(),
8usize,
concat!("Alignment of ", stringify!(C))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<C>())).i as *const _ as usize },
8usize,
concat!("Offset of field: ", stringify!(C), "::", stringify!(i))
);
}
impl Default for C {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
extern "C" {
#[link_name = "\u{1}_ZN1C5matchEv"]
pub fn C_match(this: *mut ::std::os::raw::c_void);
}
|
bindgen_test_layout_C
|
identifier_name
|
mod.rs
|
/************************************************************************
* *
* Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
use config::Config;
use game::Info;
use std::cmp::max;
use std::sync::Arc;
use time::Duration;
use time::PreciseTime;
mod test;
#[derive(Clone)]
pub struct Timer {
byo_stones: i32,
byo_stones_left: i32,
byo_time: i64,
byo_time_left: i64,
config: Arc<Config>,
current_budget: Duration,
main_time_left: i64,
time_stamp: PreciseTime,
}
impl Timer {
pub fn new(config: Arc<Config>) -> Timer {
Timer {
byo_stones: 0,
byo_stones_left: 0,
byo_time: 0,
byo_time_left: 0,
config: config,
current_budget: Duration::milliseconds(0),
main_time_left: 0,
time_stamp: PreciseTime::now(),
}
}
pub fn setup(&mut self, main_in_s: i64, byo_in_s: i64, stones: i32) {
self.set_main_time(main_in_s * 1000);
self.set_byo_time(byo_in_s * 1000);
self.set_byo_stones(stones);
self.reset_time_stamp();
}
pub fn update(&mut self, time_in_s: i64, stones: i32) {
if stones == 0 {
self.main_time_left = time_in_s * 1000;
} else {
self.main_time_left = 0;
self.byo_time_left = time_in_s * 1000;
self.byo_stones_left = stones;
}
self.reset_time_stamp();
}
pub fn start<T: Info>(&mut self, game: &T) {
self.reset_time_stamp();
let budget = self.budget(game);
self.current_budget = budget;
let msg = format!(
"Thinking for {}ms ({}ms time left)",
budget.num_milliseconds(),
self.main_time_left());
self.config.log(msg);
}
pub fn ran_out_of_time(&self, win_ratio: f32) -> bool {
let fastplay_budget = (1.0 / self.config.time_control.fastplay_budget).floor() as i32;
let budget5 = self.current_budget / fastplay_budget;
let elapsed = self.elapsed();
if elapsed > budget5 && win_ratio > self.config.time_control.fastplay_threshold {
self.config.log(format!("Search stopped early. Fastplay rule triggered."));
true
} else {
elapsed > self.current_budget
}
}
pub fn stop(&mut self) {
self.adjust_time();
}
pub fn reset(&mut self) {
// Do nothing
}
pub fn byo_stones_left(&self) -> i32 {
self.byo_stones_left
}
pub fn byo_time
|
-> i64 {
self.byo_time_left
}
pub fn main_time_left(&self) -> i64 {
self.main_time_left
}
fn set_main_time(&mut self, time: i64) {
self.main_time_left = time;
}
fn set_byo_time(&mut self, time: i64) {
self.byo_time = time;
self.byo_time_left = time;
}
fn set_byo_stones(&mut self, stones: i32) {
self.byo_stones = stones;
self.byo_stones_left = stones;
}
fn elapsed(&self) -> Duration {
self.time_stamp.to(PreciseTime::now())
}
fn reset_time_stamp(&mut self) {
self.time_stamp = PreciseTime::now();
}
fn adjust_time(&mut self) {
let time_elapsed = self.elapsed().num_milliseconds();
if time_elapsed > self.main_time_left {
let overtime_spent = time_elapsed - self.main_time_left;
self.main_time_left = 0;
if overtime_spent > self.byo_time_left() {
self.byo_time_left = 0;
self.byo_stones_left = 0;
} else {
self.byo_time_left -= overtime_spent;
self.byo_stones_left -= 1;
if self.byo_stones_left() == 0 {
self.byo_time_left = self.byo_time;
self.byo_stones_left = self.byo_stones;
}
}
} else {
self.main_time_left -= time_elapsed;
}
}
fn c(&self) -> f32 {
self.config.time_control.c
}
fn budget<T: Info>(&self, game: &T) -> Duration {
// If there's still main time left
let ms = if self.main_time_left > 0 {
let min_stones = self.config.time_control.min_stones as u16;
let vacant = max(game.vacant_point_count(), min_stones) as f32;
(self.main_time_left as f32 / (self.c() * vacant)).floor() as i64
} else if self.byo_time_left() == 0 {
0
} else {
// Else use byoyomi time
(self.byo_time_left() as f32 / self.byo_stones_left() as f32).floor() as i64
};
Duration::milliseconds(ms)
}
}
|
_left(&self)
|
identifier_name
|
mod.rs
|
/************************************************************************
* *
* Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
use config::Config;
use game::Info;
use std::cmp::max;
use std::sync::Arc;
use time::Duration;
use time::PreciseTime;
mod test;
#[derive(Clone)]
pub struct Timer {
byo_stones: i32,
byo_stones_left: i32,
byo_time: i64,
byo_time_left: i64,
config: Arc<Config>,
current_budget: Duration,
main_time_left: i64,
time_stamp: PreciseTime,
}
impl Timer {
pub fn new(config: Arc<Config>) -> Timer {
Timer {
byo_stones: 0,
byo_stones_left: 0,
byo_time: 0,
byo_time_left: 0,
config: config,
current_budget: Duration::milliseconds(0),
main_time_left: 0,
time_stamp: PreciseTime::now(),
}
}
pub fn setup(&mut self, main_in_s: i64, byo_in_s: i64, stones: i32) {
self.set_main_time(main_in_s * 1000);
self.set_byo_time(byo_in_s * 1000);
self.set_byo_stones(stones);
self.reset_time_stamp();
}
pub fn update(&mut self, time_in_s: i64, stones: i32) {
if stones == 0 {
self.main_time_left = time_in_s * 1000;
} else {
self.main_time_left = 0;
self.byo_time_left = time_in_s * 1000;
self.byo_stones_left = stones;
}
self.reset_time_stamp();
}
pub fn start<T: Info>(&mut self, game: &T) {
self.reset_time_stamp();
let budget = self.budget(game);
self.current_budget = budget;
let msg = format!(
"Thinking for {}ms ({}ms time left)",
budget.num_milliseconds(),
self.main_time_left());
self.config.log(msg);
}
pub fn ran_out_of_time(&self, win_ratio: f32) -> bool {
let fastplay_budget = (1.0 / self.config.time_control.fastplay_budget).floor() as i32;
let budget5 = self.current_budget / fastplay_budget;
let elapsed = self.elapsed();
if elapsed > budget5 && win_ratio > self.config.time_control.fastplay_threshold {
self.config.log(format!("Search stopped early. Fastplay rule triggered."));
true
} else {
elapsed > self.current_budget
}
}
pub fn stop(&mut self) {
|
b fn reset(&mut self) {
// Do nothing
}
pub fn byo_stones_left(&self) -> i32 {
self.byo_stones_left
}
pub fn byo_time_left(&self) -> i64 {
self.byo_time_left
}
pub fn main_time_left(&self) -> i64 {
self.main_time_left
}
fn set_main_time(&mut self, time: i64) {
self.main_time_left = time;
}
fn set_byo_time(&mut self, time: i64) {
self.byo_time = time;
self.byo_time_left = time;
}
fn set_byo_stones(&mut self, stones: i32) {
self.byo_stones = stones;
self.byo_stones_left = stones;
}
fn elapsed(&self) -> Duration {
self.time_stamp.to(PreciseTime::now())
}
fn reset_time_stamp(&mut self) {
self.time_stamp = PreciseTime::now();
}
fn adjust_time(&mut self) {
let time_elapsed = self.elapsed().num_milliseconds();
if time_elapsed > self.main_time_left {
let overtime_spent = time_elapsed - self.main_time_left;
self.main_time_left = 0;
if overtime_spent > self.byo_time_left() {
self.byo_time_left = 0;
self.byo_stones_left = 0;
} else {
self.byo_time_left -= overtime_spent;
self.byo_stones_left -= 1;
if self.byo_stones_left() == 0 {
self.byo_time_left = self.byo_time;
self.byo_stones_left = self.byo_stones;
}
}
} else {
self.main_time_left -= time_elapsed;
}
}
fn c(&self) -> f32 {
self.config.time_control.c
}
fn budget<T: Info>(&self, game: &T) -> Duration {
// If there's still main time left
let ms = if self.main_time_left > 0 {
let min_stones = self.config.time_control.min_stones as u16;
let vacant = max(game.vacant_point_count(), min_stones) as f32;
(self.main_time_left as f32 / (self.c() * vacant)).floor() as i64
} else if self.byo_time_left() == 0 {
0
} else {
// Else use byoyomi time
(self.byo_time_left() as f32 / self.byo_stones_left() as f32).floor() as i64
};
Duration::milliseconds(ms)
}
}
|
self.adjust_time();
}
pu
|
identifier_body
|
mod.rs
|
/************************************************************************
* *
* Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
use config::Config;
use game::Info;
use std::cmp::max;
use std::sync::Arc;
use time::Duration;
use time::PreciseTime;
mod test;
#[derive(Clone)]
pub struct Timer {
byo_stones: i32,
byo_stones_left: i32,
byo_time: i64,
byo_time_left: i64,
config: Arc<Config>,
current_budget: Duration,
main_time_left: i64,
time_stamp: PreciseTime,
}
impl Timer {
pub fn new(config: Arc<Config>) -> Timer {
Timer {
|
byo_stones_left: 0,
byo_time: 0,
byo_time_left: 0,
config: config,
current_budget: Duration::milliseconds(0),
main_time_left: 0,
time_stamp: PreciseTime::now(),
}
}
pub fn setup(&mut self, main_in_s: i64, byo_in_s: i64, stones: i32) {
self.set_main_time(main_in_s * 1000);
self.set_byo_time(byo_in_s * 1000);
self.set_byo_stones(stones);
self.reset_time_stamp();
}
pub fn update(&mut self, time_in_s: i64, stones: i32) {
if stones == 0 {
self.main_time_left = time_in_s * 1000;
} else {
self.main_time_left = 0;
self.byo_time_left = time_in_s * 1000;
self.byo_stones_left = stones;
}
self.reset_time_stamp();
}
pub fn start<T: Info>(&mut self, game: &T) {
self.reset_time_stamp();
let budget = self.budget(game);
self.current_budget = budget;
let msg = format!(
"Thinking for {}ms ({}ms time left)",
budget.num_milliseconds(),
self.main_time_left());
self.config.log(msg);
}
pub fn ran_out_of_time(&self, win_ratio: f32) -> bool {
let fastplay_budget = (1.0 / self.config.time_control.fastplay_budget).floor() as i32;
let budget5 = self.current_budget / fastplay_budget;
let elapsed = self.elapsed();
if elapsed > budget5 && win_ratio > self.config.time_control.fastplay_threshold {
self.config.log(format!("Search stopped early. Fastplay rule triggered."));
true
} else {
elapsed > self.current_budget
}
}
pub fn stop(&mut self) {
self.adjust_time();
}
pub fn reset(&mut self) {
// Do nothing
}
pub fn byo_stones_left(&self) -> i32 {
self.byo_stones_left
}
pub fn byo_time_left(&self) -> i64 {
self.byo_time_left
}
pub fn main_time_left(&self) -> i64 {
self.main_time_left
}
fn set_main_time(&mut self, time: i64) {
self.main_time_left = time;
}
fn set_byo_time(&mut self, time: i64) {
self.byo_time = time;
self.byo_time_left = time;
}
fn set_byo_stones(&mut self, stones: i32) {
self.byo_stones = stones;
self.byo_stones_left = stones;
}
fn elapsed(&self) -> Duration {
self.time_stamp.to(PreciseTime::now())
}
fn reset_time_stamp(&mut self) {
self.time_stamp = PreciseTime::now();
}
fn adjust_time(&mut self) {
let time_elapsed = self.elapsed().num_milliseconds();
if time_elapsed > self.main_time_left {
let overtime_spent = time_elapsed - self.main_time_left;
self.main_time_left = 0;
if overtime_spent > self.byo_time_left() {
self.byo_time_left = 0;
self.byo_stones_left = 0;
} else {
self.byo_time_left -= overtime_spent;
self.byo_stones_left -= 1;
if self.byo_stones_left() == 0 {
self.byo_time_left = self.byo_time;
self.byo_stones_left = self.byo_stones;
}
}
} else {
self.main_time_left -= time_elapsed;
}
}
fn c(&self) -> f32 {
self.config.time_control.c
}
fn budget<T: Info>(&self, game: &T) -> Duration {
// If there's still main time left
let ms = if self.main_time_left > 0 {
let min_stones = self.config.time_control.min_stones as u16;
let vacant = max(game.vacant_point_count(), min_stones) as f32;
(self.main_time_left as f32 / (self.c() * vacant)).floor() as i64
} else if self.byo_time_left() == 0 {
0
} else {
// Else use byoyomi time
(self.byo_time_left() as f32 / self.byo_stones_left() as f32).floor() as i64
};
Duration::milliseconds(ms)
}
}
|
byo_stones: 0,
|
random_line_split
|
mod.rs
|
/************************************************************************
* *
* Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
use config::Config;
use game::Info;
use std::cmp::max;
use std::sync::Arc;
use time::Duration;
use time::PreciseTime;
mod test;
#[derive(Clone)]
pub struct Timer {
byo_stones: i32,
byo_stones_left: i32,
byo_time: i64,
byo_time_left: i64,
config: Arc<Config>,
current_budget: Duration,
main_time_left: i64,
time_stamp: PreciseTime,
}
impl Timer {
pub fn new(config: Arc<Config>) -> Timer {
Timer {
byo_stones: 0,
byo_stones_left: 0,
byo_time: 0,
byo_time_left: 0,
config: config,
current_budget: Duration::milliseconds(0),
main_time_left: 0,
time_stamp: PreciseTime::now(),
}
}
pub fn setup(&mut self, main_in_s: i64, byo_in_s: i64, stones: i32) {
self.set_main_time(main_in_s * 1000);
self.set_byo_time(byo_in_s * 1000);
self.set_byo_stones(stones);
self.reset_time_stamp();
}
pub fn update(&mut self, time_in_s: i64, stones: i32) {
if stones == 0 {
self.main_time_left = time_in_s * 1000;
} else {
self.main_time_left = 0;
self.byo_time_left = time_in_s * 1000;
self.byo_stones_left = stones;
}
self.reset_time_stamp();
}
pub fn start<T: Info>(&mut self, game: &T) {
self.reset_time_stamp();
let budget = self.budget(game);
self.current_budget = budget;
let msg = format!(
"Thinking for {}ms ({}ms time left)",
budget.num_milliseconds(),
self.main_time_left());
self.config.log(msg);
}
pub fn ran_out_of_time(&self, win_ratio: f32) -> bool {
let fastplay_budget = (1.0 / self.config.time_control.fastplay_budget).floor() as i32;
let budget5 = self.current_budget / fastplay_budget;
let elapsed = self.elapsed();
if elapsed > budget5 && win_ratio > self.config.time_control.fastplay_threshold {
|
elapsed > self.current_budget
}
}
pub fn stop(&mut self) {
self.adjust_time();
}
pub fn reset(&mut self) {
// Do nothing
}
pub fn byo_stones_left(&self) -> i32 {
self.byo_stones_left
}
pub fn byo_time_left(&self) -> i64 {
self.byo_time_left
}
pub fn main_time_left(&self) -> i64 {
self.main_time_left
}
fn set_main_time(&mut self, time: i64) {
self.main_time_left = time;
}
fn set_byo_time(&mut self, time: i64) {
self.byo_time = time;
self.byo_time_left = time;
}
fn set_byo_stones(&mut self, stones: i32) {
self.byo_stones = stones;
self.byo_stones_left = stones;
}
fn elapsed(&self) -> Duration {
self.time_stamp.to(PreciseTime::now())
}
fn reset_time_stamp(&mut self) {
self.time_stamp = PreciseTime::now();
}
fn adjust_time(&mut self) {
let time_elapsed = self.elapsed().num_milliseconds();
if time_elapsed > self.main_time_left {
let overtime_spent = time_elapsed - self.main_time_left;
self.main_time_left = 0;
if overtime_spent > self.byo_time_left() {
self.byo_time_left = 0;
self.byo_stones_left = 0;
} else {
self.byo_time_left -= overtime_spent;
self.byo_stones_left -= 1;
if self.byo_stones_left() == 0 {
self.byo_time_left = self.byo_time;
self.byo_stones_left = self.byo_stones;
}
}
} else {
self.main_time_left -= time_elapsed;
}
}
fn c(&self) -> f32 {
self.config.time_control.c
}
fn budget<T: Info>(&self, game: &T) -> Duration {
// If there's still main time left
let ms = if self.main_time_left > 0 {
let min_stones = self.config.time_control.min_stones as u16;
let vacant = max(game.vacant_point_count(), min_stones) as f32;
(self.main_time_left as f32 / (self.c() * vacant)).floor() as i64
} else if self.byo_time_left() == 0 {
0
} else {
// Else use byoyomi time
(self.byo_time_left() as f32 / self.byo_stones_left() as f32).floor() as i64
};
Duration::milliseconds(ms)
}
}
|
self.config.log(format!("Search stopped early. Fastplay rule triggered."));
true
} else {
|
conditional_block
|
dependency.rs
|
use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{SourceId, Summary, PackageId};
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoResult, CargoResultExt, CargoError};
/// Information about a dependency requested by a Cargo manifest.
/// Cheap to copy.
#[derive(PartialEq, Clone, Debug)]
pub struct Dependency {
inner: Rc<Inner>,
}
/// The data underlying a Dependency.
#[derive(PartialEq, Clone, Debug)]
struct Inner {
name: String,
source_id: SourceId,
req: VersionReq,
specified_req: bool,
kind: Kind,
only_match_name: bool,
optional: bool,
default_features: bool,
features: Vec<String>,
// This dependency should be used only for this platform.
// `None` means *all platforms*.
platform: Option<Platform>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Platform {
Name(String),
Cfg(CfgExpr),
}
#[derive(Serialize)]
struct SerializedDependency<'a> {
name: &'a str,
source: &'a SourceId,
req: String,
kind: Kind,
optional: bool,
uses_default_features: bool,
features: &'a [String],
target: Option<&'a Platform>,
}
impl ser::Serialize for Dependency {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer,
{
SerializedDependency {
name: self.name(),
source: &self.source_id(),
req: self.version_req().to_string(),
kind: self.kind(),
optional: self.is_optional(),
uses_default_features: self.uses_default_features(),
features: self.features(),
target: self.platform(),
}.serialize(s)
}
}
#[derive(PartialEq, Clone, Debug, Copy)]
pub enum Kind {
Normal,
Development,
Build,
}
fn parse_req_with_deprecated(req: &str,
extra: Option<(&PackageId, &Config)>)
-> CargoResult<VersionReq> {
match VersionReq::parse(req) {
Err(e) => {
let (inside, config) = match extra {
Some(pair) => pair,
None => return Err(e.into()),
};
match e {
ReqParseError::DeprecatedVersionRequirement(requirement) => {
let msg = format!("\
parsed version requirement `{}` is no longer valid
Previous versions of Cargo accepted this malformed requirement,
but it is being deprecated. This was found when parsing the manifest
of {} {}, and the correct version requirement is `{}`.
This will soon become a hard error, so it's either recommended to
update to a fixed version or contact the upstream maintainer about
this warning.
",
req, inside.name(), inside.version(), requirement);
config.shell().warn(&msg)?;
Ok(requirement)
}
e => Err(e.into()),
}
},
Ok(v) => Ok(v),
}
}
impl ser::Serialize for Kind {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer,
{
match *self {
Kind::Normal => None,
Kind::Development => Some("dev"),
Kind::Build => Some("build"),
}.serialize(s)
}
}
impl Dependency {
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse(name: &str,
version: Option<&str>,
source_id: &SourceId,
inside: &PackageId,
config: &Config) -> CargoResult<Dependency> {
let arg = Some((inside, config));
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, arg)?),
None => (false, VersionReq::any())
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse_no_deprecated(name: &str,
version: Option<&str>,
source_id: &SourceId) -> CargoResult<Dependency> {
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, None)?),
None => (false, VersionReq::any())
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
pub fn new_override(name: &str, source_id: &SourceId) -> Dependency {
Dependency {
inner: Rc::new(Inner {
name: name.to_string(),
source_id: source_id.clone(),
req: VersionReq::any(),
kind: Kind::Normal,
only_match_name: true,
optional: false,
features: Vec::new(),
default_features: true,
specified_req: false,
platform: None,
}),
}
}
pub fn version_req(&self) -> &VersionReq {
&self.inner.req
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn source_id(&self) -> &SourceId {
&self.inner.source_id
}
pub fn kind(&self) -> Kind {
self.inner.kind
}
pub fn specified_req(&self) -> bool {
self.inner.specified_req
}
/// If none, this dependencies must be built for all platforms.
/// If some, it must only be built for the specified platform.
pub fn platform(&self) -> Option<&Platform> {
self.inner.platform.as_ref()
}
pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
Rc::make_mut(&mut self.inner).kind = kind;
self
}
/// Sets the list of features requested for the package.
pub fn set_features(&mut self, features: Vec<String>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).features = features;
self
}
/// Sets whether the dependency requests default features of the package.
pub fn set_default_features(&mut self, default_features: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).default_features = default_features;
self
}
/// Sets whether the dependency is optional.
pub fn set_optional(&mut self, optional: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).optional = optional;
self
}
/// Set the source id for this dependency
pub fn
|
(&mut self, id: SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).source_id = id;
self
}
/// Set the version requirement for this dependency
pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency {
Rc::make_mut(&mut self.inner).req = req;
self
}
pub fn set_platform(&mut self, platform: Option<Platform>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).platform = platform;
self
}
/// Lock this dependency to depending on the specified package id
pub fn lock_to(&mut self, id: &PackageId) -> &mut Dependency {
assert_eq!(self.inner.source_id, *id.source_id());
assert!(self.inner.req.matches(id.version()));
self.set_version_req(VersionReq::exact(id.version()))
.set_source_id(id.source_id().clone())
}
/// Returns false if the dependency is only used to build the local package.
pub fn is_transitive(&self) -> bool {
match self.inner.kind {
Kind::Normal | Kind::Build => true,
Kind::Development => false,
}
}
pub fn is_build(&self) -> bool {
match self.inner.kind {
Kind::Build => true,
_ => false,
}
}
pub fn is_optional(&self) -> bool {
self.inner.optional
}
/// Returns true if the default features of the dependency are requested.
pub fn uses_default_features(&self) -> bool {
self.inner.default_features
}
/// Returns the list of features that are requested by the dependency.
pub fn features(&self) -> &[String] {
&self.inner.features
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches(&self, sum: &Summary) -> bool {
self.matches_id(sum.package_id())
}
/// Returns true if the package (`id`) can fulfill this dependency request.
pub fn matches_id(&self, id: &PackageId) -> bool {
self.inner.name == id.name() &&
(self.inner.only_match_name || (self.inner.req.matches(id.version()) &&
&self.inner.source_id == id.source_id()))
}
pub fn map_source(mut self, to_replace: &SourceId, replace_with: &SourceId)
-> Dependency {
if self.source_id()!= to_replace {
self
} else {
self.set_source_id(replace_with.clone());
self
}
}
}
impl Platform {
pub fn matches(&self, name: &str, cfg: Option<&[Cfg]>) -> bool {
match *self {
Platform::Name(ref p) => p == name,
Platform::Cfg(ref p) => {
match cfg {
Some(cfg) => p.matches(cfg),
None => false,
}
}
}
}
}
impl ser::Serialize for Platform {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer,
{
self.to_string().serialize(s)
}
}
impl FromStr for Platform {
type Err = CargoError;
fn from_str(s: &str) -> CargoResult<Platform> {
if s.starts_with("cfg(") && s.ends_with(")") {
let s = &s[4..s.len()-1];
s.parse().map(Platform::Cfg).chain_err(|| {
format!("failed to parse `{}` as a cfg expression", s)
})
} else {
Ok(Platform::Name(s.to_string()))
}
}
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Platform::Name(ref n) => n.fmt(f),
Platform::Cfg(ref e) => write!(f, "cfg({})", e),
}
}
}
|
set_source_id
|
identifier_name
|
dependency.rs
|
use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{SourceId, Summary, PackageId};
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoResult, CargoResultExt, CargoError};
/// Information about a dependency requested by a Cargo manifest.
/// Cheap to copy.
#[derive(PartialEq, Clone, Debug)]
pub struct Dependency {
inner: Rc<Inner>,
}
/// The data underlying a Dependency.
#[derive(PartialEq, Clone, Debug)]
struct Inner {
name: String,
source_id: SourceId,
req: VersionReq,
specified_req: bool,
kind: Kind,
only_match_name: bool,
optional: bool,
default_features: bool,
features: Vec<String>,
// This dependency should be used only for this platform.
// `None` means *all platforms*.
platform: Option<Platform>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Platform {
Name(String),
Cfg(CfgExpr),
}
#[derive(Serialize)]
struct SerializedDependency<'a> {
name: &'a str,
source: &'a SourceId,
req: String,
kind: Kind,
optional: bool,
uses_default_features: bool,
features: &'a [String],
target: Option<&'a Platform>,
}
impl ser::Serialize for Dependency {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer,
{
SerializedDependency {
name: self.name(),
source: &self.source_id(),
req: self.version_req().to_string(),
kind: self.kind(),
optional: self.is_optional(),
uses_default_features: self.uses_default_features(),
features: self.features(),
target: self.platform(),
}.serialize(s)
}
}
#[derive(PartialEq, Clone, Debug, Copy)]
pub enum Kind {
Normal,
Development,
Build,
}
fn parse_req_with_deprecated(req: &str,
extra: Option<(&PackageId, &Config)>)
-> CargoResult<VersionReq> {
match VersionReq::parse(req) {
Err(e) => {
let (inside, config) = match extra {
Some(pair) => pair,
None => return Err(e.into()),
};
match e {
ReqParseError::DeprecatedVersionRequirement(requirement) => {
let msg = format!("\
parsed version requirement `{}` is no longer valid
Previous versions of Cargo accepted this malformed requirement,
but it is being deprecated. This was found when parsing the manifest
of {} {}, and the correct version requirement is `{}`.
This will soon become a hard error, so it's either recommended to
update to a fixed version or contact the upstream maintainer about
this warning.
",
req, inside.name(), inside.version(), requirement);
config.shell().warn(&msg)?;
Ok(requirement)
|
}
},
Ok(v) => Ok(v),
}
}
impl ser::Serialize for Kind {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer,
{
match *self {
Kind::Normal => None,
Kind::Development => Some("dev"),
Kind::Build => Some("build"),
}.serialize(s)
}
}
impl Dependency {
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse(name: &str,
version: Option<&str>,
source_id: &SourceId,
inside: &PackageId,
config: &Config) -> CargoResult<Dependency> {
let arg = Some((inside, config));
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, arg)?),
None => (false, VersionReq::any())
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse_no_deprecated(name: &str,
version: Option<&str>,
source_id: &SourceId) -> CargoResult<Dependency> {
let (specified_req, version_req) = match version {
Some(v) => (true, parse_req_with_deprecated(v, None)?),
None => (false, VersionReq::any())
};
let mut ret = Dependency::new_override(name, source_id);
{
let ptr = Rc::make_mut(&mut ret.inner);
ptr.only_match_name = false;
ptr.req = version_req;
ptr.specified_req = specified_req;
}
Ok(ret)
}
pub fn new_override(name: &str, source_id: &SourceId) -> Dependency {
Dependency {
inner: Rc::new(Inner {
name: name.to_string(),
source_id: source_id.clone(),
req: VersionReq::any(),
kind: Kind::Normal,
only_match_name: true,
optional: false,
features: Vec::new(),
default_features: true,
specified_req: false,
platform: None,
}),
}
}
pub fn version_req(&self) -> &VersionReq {
&self.inner.req
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn source_id(&self) -> &SourceId {
&self.inner.source_id
}
pub fn kind(&self) -> Kind {
self.inner.kind
}
pub fn specified_req(&self) -> bool {
self.inner.specified_req
}
/// If none, this dependencies must be built for all platforms.
/// If some, it must only be built for the specified platform.
pub fn platform(&self) -> Option<&Platform> {
self.inner.platform.as_ref()
}
pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
Rc::make_mut(&mut self.inner).kind = kind;
self
}
/// Sets the list of features requested for the package.
pub fn set_features(&mut self, features: Vec<String>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).features = features;
self
}
/// Sets whether the dependency requests default features of the package.
pub fn set_default_features(&mut self, default_features: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).default_features = default_features;
self
}
/// Sets whether the dependency is optional.
pub fn set_optional(&mut self, optional: bool) -> &mut Dependency {
Rc::make_mut(&mut self.inner).optional = optional;
self
}
/// Set the source id for this dependency
pub fn set_source_id(&mut self, id: SourceId) -> &mut Dependency {
Rc::make_mut(&mut self.inner).source_id = id;
self
}
/// Set the version requirement for this dependency
pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency {
Rc::make_mut(&mut self.inner).req = req;
self
}
pub fn set_platform(&mut self, platform: Option<Platform>) -> &mut Dependency {
Rc::make_mut(&mut self.inner).platform = platform;
self
}
/// Lock this dependency to depending on the specified package id
pub fn lock_to(&mut self, id: &PackageId) -> &mut Dependency {
assert_eq!(self.inner.source_id, *id.source_id());
assert!(self.inner.req.matches(id.version()));
self.set_version_req(VersionReq::exact(id.version()))
.set_source_id(id.source_id().clone())
}
/// Returns false if the dependency is only used to build the local package.
pub fn is_transitive(&self) -> bool {
match self.inner.kind {
Kind::Normal | Kind::Build => true,
Kind::Development => false,
}
}
pub fn is_build(&self) -> bool {
match self.inner.kind {
Kind::Build => true,
_ => false,
}
}
pub fn is_optional(&self) -> bool {
self.inner.optional
}
/// Returns true if the default features of the dependency are requested.
pub fn uses_default_features(&self) -> bool {
self.inner.default_features
}
/// Returns the list of features that are requested by the dependency.
pub fn features(&self) -> &[String] {
&self.inner.features
}
/// Returns true if the package (`sum`) can fulfill this dependency request.
pub fn matches(&self, sum: &Summary) -> bool {
self.matches_id(sum.package_id())
}
/// Returns true if the package (`id`) can fulfill this dependency request.
pub fn matches_id(&self, id: &PackageId) -> bool {
self.inner.name == id.name() &&
(self.inner.only_match_name || (self.inner.req.matches(id.version()) &&
&self.inner.source_id == id.source_id()))
}
pub fn map_source(mut self, to_replace: &SourceId, replace_with: &SourceId)
-> Dependency {
if self.source_id()!= to_replace {
self
} else {
self.set_source_id(replace_with.clone());
self
}
}
}
impl Platform {
pub fn matches(&self, name: &str, cfg: Option<&[Cfg]>) -> bool {
match *self {
Platform::Name(ref p) => p == name,
Platform::Cfg(ref p) => {
match cfg {
Some(cfg) => p.matches(cfg),
None => false,
}
}
}
}
}
impl ser::Serialize for Platform {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer,
{
self.to_string().serialize(s)
}
}
impl FromStr for Platform {
type Err = CargoError;
fn from_str(s: &str) -> CargoResult<Platform> {
if s.starts_with("cfg(") && s.ends_with(")") {
let s = &s[4..s.len()-1];
s.parse().map(Platform::Cfg).chain_err(|| {
format!("failed to parse `{}` as a cfg expression", s)
})
} else {
Ok(Platform::Name(s.to_string()))
}
}
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Platform::Name(ref n) => n.fmt(f),
Platform::Cfg(ref e) => write!(f, "cfg({})", e),
}
}
}
|
}
e => Err(e.into()),
|
random_line_split
|
shared_memory.rs
|
//! TODO docs
use std::ffi::CString;
use std::slice;
use types;
pub struct Handle {
shm_fd: ::detail::FileHandle,
name: String,
access_mode: types::AccessMode,
}
impl Handle {
pub fn new(name: &str,
create_mode: types::CreateMode,
access_mode: types::AccessMode,
permissions: types::Permissions) -> Result<Handle, types::Error> {
let cstr = match CString::new(name) {
Err(_) => return Err(types::Error::ConvertString),
Ok(val) => val,
};
match ::detail::create_shm_handle(&cstr, &create_mode, &access_mode, &permissions) {
None => Err(types::Error::CreateFile),
Some(fd) => Ok(Handle {shm_fd: fd, name: String::from(name), access_mode: access_mode}),
}
}
pub fn remove(name: &str) -> Result<(), types::Error> {
let cstr = match CString::new(name) {
Err(_) => return Err(types::Error::ConvertString),
Ok(val) => val,
};
match ::detail::delete_file(&cstr) {
false => Err(types::Error::DeleteFile),
true => Ok(()),
}
}
pub fn native_handle(&self) -> ::detail::FileHandle {
self.shm_fd
}
pub fn name(&self) -> &String {
&self.name
}
pub fn access_mode(&self) -> types::AccessMode {
self.access_mode.clone()
}
}
impl Drop for Handle {
fn drop(&mut self) {
::detail::close_handle(self.shm_fd)
}
}
pub struct MappedRegion {
_handle: Handle,
ptr: *mut u8,
size: usize,
}
impl MappedRegion {
pub fn new(handle: Handle, size: usize) -> Result<MappedRegion, types::Error> {
if!::detail::truncate_file(handle.native_handle(), size) {
return Err(types::Error::ResizeFile);
}
match ::detail::map_memory(handle.native_handle(), size, handle.access_mode()) {
None => Err(types::Error::MapRegion),
Some(ptr) => Ok(MappedRegion {_handle: handle, ptr: ptr, size: size}),
}
}
pub fn memory(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.ptr, self.size) }
}
pub fn size(&self) -> usize {
self.size
}
}
#[cfg(test)]
mod tests {
#[test]
fn breath_test_handle() {
use super::*;
use types;
let name = "handleBreathTest";
{
let handle = Handle::new(name, types::CreateMode::CreateOnly, types::AccessMode::ReadWrite, types::Permissions::User).unwrap();
assert_eq!(handle.name(), name);
match handle.access_mode() {
types::AccessMode::ReadWrite => {},
_ => assert!(false, "wrong access mode"),
};
let _ = handle.native_handle();
}
match Handle::remove(name) {
Ok(_) => {},
Err(err) => assert!(false, "Can't remove file: {}", err),
}
}
#[test]
fn breath_test_mapped_region() {
use super::*;
use types;
let name = "mappedRegionBreathTest";
const SIZE: usize = 4096;
let data: &[u8] = b"Hello Memory Mapped Area!";
{
let _ = Handle::remove(name);
let handle = Handle::new(name, types::CreateMode::CreateOnly, types::AccessMode::ReadWrite, types::Permissions::User).unwrap();
let mut mapped_region = MappedRegion::new(handle, SIZE).unwrap();
assert_eq!(mapped_region.size(), SIZE);
assert_eq!(mapped_region.memory().len(), SIZE);
mapped_region.memory()[..data.len()].copy_from_slice(&data);
}
{
let handle = Handle::new(name, types::CreateMode::OpenOnly, types::AccessMode::ReadWrite, types::Permissions::User).unwrap();
let mut mapped_region = MappedRegion::new(handle, SIZE).unwrap();
let mut buffer = [0u8; SIZE];
buffer[..data.len()].copy_from_slice(&mapped_region.memory()[..data.len()]);
|
match Handle::remove(name) {
Ok(_) => {},
Err(err) => assert!(false, "Can't remove file: {}", err),
}
}
}
|
assert_eq!(data, &buffer[..data.len()]);
}
|
random_line_split
|
shared_memory.rs
|
//! TODO docs
use std::ffi::CString;
use std::slice;
use types;
pub struct Handle {
shm_fd: ::detail::FileHandle,
name: String,
access_mode: types::AccessMode,
}
impl Handle {
pub fn new(name: &str,
create_mode: types::CreateMode,
access_mode: types::AccessMode,
permissions: types::Permissions) -> Result<Handle, types::Error> {
let cstr = match CString::new(name) {
Err(_) => return Err(types::Error::ConvertString),
Ok(val) => val,
};
match ::detail::create_shm_handle(&cstr, &create_mode, &access_mode, &permissions) {
None => Err(types::Error::CreateFile),
Some(fd) => Ok(Handle {shm_fd: fd, name: String::from(name), access_mode: access_mode}),
}
}
pub fn remove(name: &str) -> Result<(), types::Error> {
let cstr = match CString::new(name) {
Err(_) => return Err(types::Error::ConvertString),
Ok(val) => val,
};
match ::detail::delete_file(&cstr) {
false => Err(types::Error::DeleteFile),
true => Ok(()),
}
}
pub fn native_handle(&self) -> ::detail::FileHandle {
self.shm_fd
}
pub fn
|
(&self) -> &String {
&self.name
}
pub fn access_mode(&self) -> types::AccessMode {
self.access_mode.clone()
}
}
impl Drop for Handle {
fn drop(&mut self) {
::detail::close_handle(self.shm_fd)
}
}
pub struct MappedRegion {
_handle: Handle,
ptr: *mut u8,
size: usize,
}
impl MappedRegion {
pub fn new(handle: Handle, size: usize) -> Result<MappedRegion, types::Error> {
if!::detail::truncate_file(handle.native_handle(), size) {
return Err(types::Error::ResizeFile);
}
match ::detail::map_memory(handle.native_handle(), size, handle.access_mode()) {
None => Err(types::Error::MapRegion),
Some(ptr) => Ok(MappedRegion {_handle: handle, ptr: ptr, size: size}),
}
}
pub fn memory(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.ptr, self.size) }
}
pub fn size(&self) -> usize {
self.size
}
}
#[cfg(test)]
mod tests {
#[test]
fn breath_test_handle() {
use super::*;
use types;
let name = "handleBreathTest";
{
let handle = Handle::new(name, types::CreateMode::CreateOnly, types::AccessMode::ReadWrite, types::Permissions::User).unwrap();
assert_eq!(handle.name(), name);
match handle.access_mode() {
types::AccessMode::ReadWrite => {},
_ => assert!(false, "wrong access mode"),
};
let _ = handle.native_handle();
}
match Handle::remove(name) {
Ok(_) => {},
Err(err) => assert!(false, "Can't remove file: {}", err),
}
}
#[test]
fn breath_test_mapped_region() {
use super::*;
use types;
let name = "mappedRegionBreathTest";
const SIZE: usize = 4096;
let data: &[u8] = b"Hello Memory Mapped Area!";
{
let _ = Handle::remove(name);
let handle = Handle::new(name, types::CreateMode::CreateOnly, types::AccessMode::ReadWrite, types::Permissions::User).unwrap();
let mut mapped_region = MappedRegion::new(handle, SIZE).unwrap();
assert_eq!(mapped_region.size(), SIZE);
assert_eq!(mapped_region.memory().len(), SIZE);
mapped_region.memory()[..data.len()].copy_from_slice(&data);
}
{
let handle = Handle::new(name, types::CreateMode::OpenOnly, types::AccessMode::ReadWrite, types::Permissions::User).unwrap();
let mut mapped_region = MappedRegion::new(handle, SIZE).unwrap();
let mut buffer = [0u8; SIZE];
buffer[..data.len()].copy_from_slice(&mapped_region.memory()[..data.len()]);
assert_eq!(data, &buffer[..data.len()]);
}
match Handle::remove(name) {
Ok(_) => {},
Err(err) => assert!(false, "Can't remove file: {}", err),
}
}
}
|
name
|
identifier_name
|
paths.rs
|
// Copyright 2017 Thorben Kroeger.
// Dual-licensed MIT and Apache 2.0 (see LICENSE files for details).
use std::path::{Path, PathBuf};
pub struct CommonPrefix {
pub prefix: PathBuf,
pub suffix1: PathBuf,
pub suffix2: PathBuf
}
pub fn common_prefix(path1: &Path, path2: &Path) -> CommonPrefix {
let mut a = path1.components().peekable();
let mut b = path2.components().peekable();
let mut common_prefix = vec![];
loop {
match (a.peek(), b.peek()) {
(Some(&e1), Some(&e2)) =>
|
_ => { break; }
}
}
let common_prefix = common_prefix.iter().map(|s| s.as_os_str()).collect::<PathBuf>();
let r1 = a.map(|s| s.as_os_str()).collect::<PathBuf>();
let r2 = b.map(|s| s.as_os_str()).collect::<PathBuf>();
CommonPrefix {
prefix: common_prefix,
suffix1: r1,
suffix2: r2
}
}
|
{
if e1 != e2 {
break;
}
common_prefix.push(e1);
a.next();
b.next();
continue;
}
|
conditional_block
|
paths.rs
|
// Copyright 2017 Thorben Kroeger.
// Dual-licensed MIT and Apache 2.0 (see LICENSE files for details).
use std::path::{Path, PathBuf};
pub struct CommonPrefix {
pub prefix: PathBuf,
pub suffix1: PathBuf,
pub suffix2: PathBuf
}
pub fn
|
(path1: &Path, path2: &Path) -> CommonPrefix {
let mut a = path1.components().peekable();
let mut b = path2.components().peekable();
let mut common_prefix = vec![];
loop {
match (a.peek(), b.peek()) {
(Some(&e1), Some(&e2)) => {
if e1!= e2 {
break;
}
common_prefix.push(e1);
a.next();
b.next();
continue;
}
_ => { break; }
}
}
let common_prefix = common_prefix.iter().map(|s| s.as_os_str()).collect::<PathBuf>();
let r1 = a.map(|s| s.as_os_str()).collect::<PathBuf>();
let r2 = b.map(|s| s.as_os_str()).collect::<PathBuf>();
CommonPrefix {
prefix: common_prefix,
suffix1: r1,
suffix2: r2
}
}
|
common_prefix
|
identifier_name
|
paths.rs
|
// Copyright 2017 Thorben Kroeger.
// Dual-licensed MIT and Apache 2.0 (see LICENSE files for details).
use std::path::{Path, PathBuf};
pub struct CommonPrefix {
pub prefix: PathBuf,
pub suffix1: PathBuf,
pub suffix2: PathBuf
}
pub fn common_prefix(path1: &Path, path2: &Path) -> CommonPrefix {
let mut a = path1.components().peekable();
let mut b = path2.components().peekable();
let mut common_prefix = vec![];
loop {
|
if e1!= e2 {
break;
}
common_prefix.push(e1);
a.next();
b.next();
continue;
}
_ => { break; }
}
}
let common_prefix = common_prefix.iter().map(|s| s.as_os_str()).collect::<PathBuf>();
let r1 = a.map(|s| s.as_os_str()).collect::<PathBuf>();
let r2 = b.map(|s| s.as_os_str()).collect::<PathBuf>();
CommonPrefix {
prefix: common_prefix,
suffix1: r1,
suffix2: r2
}
}
|
match (a.peek(), b.peek()) {
(Some(&e1), Some(&e2)) => {
|
random_line_split
|
paths.rs
|
// Copyright 2017 Thorben Kroeger.
// Dual-licensed MIT and Apache 2.0 (see LICENSE files for details).
use std::path::{Path, PathBuf};
pub struct CommonPrefix {
pub prefix: PathBuf,
pub suffix1: PathBuf,
pub suffix2: PathBuf
}
pub fn common_prefix(path1: &Path, path2: &Path) -> CommonPrefix
|
let r1 = a.map(|s| s.as_os_str()).collect::<PathBuf>();
let r2 = b.map(|s| s.as_os_str()).collect::<PathBuf>();
CommonPrefix {
prefix: common_prefix,
suffix1: r1,
suffix2: r2
}
}
|
{
let mut a = path1.components().peekable();
let mut b = path2.components().peekable();
let mut common_prefix = vec![];
loop {
match (a.peek(), b.peek()) {
(Some(&e1), Some(&e2)) => {
if e1 != e2 {
break;
}
common_prefix.push(e1);
a.next();
b.next();
continue;
}
_ => { break; }
}
}
let common_prefix = common_prefix.iter().map(|s| s.as_os_str()).collect::<PathBuf>();
|
identifier_body
|
trait-inheritance-num.rs
|
// xfail-fast
// 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.
extern mod extra;
use std::cmp::{Eq, Ord};
use std::num::NumCast;
pub trait NumExt: Num + NumCast + Eq + Ord {}
pub trait FloatExt: NumExt {}
fn
|
<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
pub fn main() {}
|
greater_than_one
|
identifier_name
|
trait-inheritance-num.rs
|
// xfail-fast
// 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.
extern mod extra;
use std::cmp::{Eq, Ord};
use std::num::NumCast;
pub trait NumExt: Num + NumCast + Eq + Ord {}
pub trait FloatExt: NumExt {}
fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
fn greater_than_one_float<T:FloatExt>(n: &T) -> bool
|
pub fn main() {}
|
{ *n > NumCast::from(1).unwrap() }
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.