From 32313ecece3cb76b2e7de7b49cc9c07553a23e9b Mon Sep 17 00:00:00 2001 From: Emilio Cobos Álvarez Date: Sat, 9 Jul 2016 13:02:56 -0700 Subject: hack: Use a local clone of refcell to not depend on borrow_state This is the same that we do in components/style in servo. --- src/gen.rs | 2 +- src/hacks/refcell.rs | 464 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 - src/parser.rs | 6 +- src/types.rs | 3 +- 5 files changed, 470 insertions(+), 6 deletions(-) create mode 100644 src/hacks/refcell.rs diff --git a/src/gen.rs b/src/gen.rs index d6b43ff9..4273e636 100644 --- a/src/gen.rs +++ b/src/gen.rs @@ -1,5 +1,5 @@ use std; -use std::cell::RefCell; +use hacks::refcell::RefCell; use std::vec::Vec; use std::rc::Rc; use std::collections::HashMap; diff --git a/src/hacks/refcell.rs b/src/hacks/refcell.rs new file mode 100644 index 00000000..408e95d4 --- /dev/null +++ b/src/hacks/refcell.rs @@ -0,0 +1,464 @@ +// Copyright 2012-2014 The Rust Project Developers. +// See http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A fork of std::cell::RefCell that makes `as_unsafe_cell` usable on stable Rust. +//! +//! FIXME(https://github.com/rust-lang/rust/issues/27708): Remove this +//! (revert commit f7f81e0ed0b62402db291e28a9bb16f7194ebf78 / PR #11835) +//! when `std::cell::RefCell::as_unsafe_cell` is in Rust’s stable channel. + +#![allow(unsafe_code, dead_code)] + +use std::cell::{UnsafeCell, Cell}; +use std::cmp::Ordering; +use std::ops::{Deref, DerefMut}; + +/// A fork of std::cell::RefCell that makes `as_unsafe_cell` usable on stable Rust. +/// +/// FIXME(https://github.com/rust-lang/rust/issues/27708): Remove this +/// (revert commit f7f81e0ed0b62402db291e28a9bb16f7194ebf78 / PR #11835) +/// when `std::cell::RefCell::as_unsafe_cell` is in Rust’s stable channel. +#[derive(Debug)] +pub struct RefCell { + borrow: Cell, + value: UnsafeCell, +} +type BorrowFlag = usize; + +/// An enumeration of values returned from the `state` method on a `RefCell`. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum BorrowState { + /// The cell is currently being read, there is at least one active `borrow`. + Reading, + /// The cell is currently being written to, there is an active `borrow_mut`. + Writing, + /// There are no outstanding borrows on this cell. + Unused, +} + +// Values [1, MAX-1] represent the number of `Ref` active +// (will not outgrow its range since `usize` is the size of the address space) +const UNUSED: BorrowFlag = 0; +const WRITING: BorrowFlag = !0; + +impl RefCell { + /// Creates a new `RefCell` containing `value`. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// ``` + #[inline] + pub fn new(value: T) -> RefCell { + RefCell { + value: UnsafeCell::new(value), + borrow: Cell::new(UNUSED), + } + } + + /// Consumes the `RefCell`, returning the wrapped value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// + /// let five = c.into_inner(); + /// ``` + #[inline] + pub fn into_inner(self) -> T { + // Since this function takes `self` (the `RefCell`) by value, the + // compiler statically verifies that it is not currently borrowed. + // Therefore the following assertion is just a `debug_assert!`. + debug_assert!(self.borrow.get() == UNUSED); + unsafe { self.value.into_inner() } + } +} + +impl RefCell { + /// Query the current state of this `RefCell` + /// + /// The returned value can be dispatched on to determine if a call to + /// `borrow` or `borrow_mut` would succeed. + #[inline] + pub fn borrow_state(&self) -> BorrowState { + match self.borrow.get() { + WRITING => BorrowState::Writing, + UNUSED => BorrowState::Unused, + _ => BorrowState::Reading, + } + } + + /// Immutably borrows the wrapped value. + /// + /// The borrow lasts until the returned `Ref` exits scope. Multiple + /// immutable borrows can be taken out at the same time. + /// + /// # Panics + /// + /// Panics if the value is currently mutably borrowed. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// + /// let borrowed_five = c.borrow(); + /// let borrowed_five2 = c.borrow(); + /// ``` + /// + /// An example of panic: + /// + /// ``` + /// use std::cell::RefCell; + /// use std::thread; + /// + /// let result = thread::spawn(move || { + /// let c = RefCell::new(5); + /// let m = c.borrow_mut(); + /// + /// let b = c.borrow(); // this causes a panic + /// }).join(); + /// + /// assert!(result.is_err()); + /// ``` + #[inline] + pub fn borrow(&self) -> Ref { + match BorrowRef::new(&self.borrow) { + Some(b) => Ref { + value: unsafe { &*self.value.get() }, + borrow: b, + }, + None => panic!("RefCell already mutably borrowed"), + } + } + + /// Mutably borrows the wrapped value. + /// + /// The borrow lasts until the returned `RefMut` exits scope. The value + /// cannot be borrowed while this borrow is active. + /// + /// # Panics + /// + /// Panics if the value is currently borrowed. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// + /// *c.borrow_mut() = 7; + /// + /// assert_eq!(*c.borrow(), 7); + /// ``` + /// + /// An example of panic: + /// + /// ``` + /// use std::cell::RefCell; + /// use std::thread; + /// + /// let result = thread::spawn(move || { + /// let c = RefCell::new(5); + /// let m = c.borrow(); + /// + /// let b = c.borrow_mut(); // this causes a panic + /// }).join(); + /// + /// assert!(result.is_err()); + /// ``` + #[inline] + pub fn borrow_mut(&self) -> RefMut { + match BorrowRefMut::new(&self.borrow) { + Some(b) => RefMut { + value: unsafe { &mut *self.value.get() }, + borrow: b, + }, + None => panic!("RefCell already borrowed"), + } + } + + /// Returns a reference to the underlying `UnsafeCell`. + /// + /// This can be used to circumvent `RefCell`'s safety checks. + /// + /// This function is `unsafe` because `UnsafeCell`'s field is public. + #[inline] + pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell { + &self.value + } + + /// Returns a mutable reference to the underlying data. + /// + /// This call borrows `RefCell` mutably (at compile-time) so there is no + /// need for dynamic checks. + #[inline] + pub fn get_mut(&mut self) -> &mut T { + unsafe { + &mut *self.value.get() + } + } +} + +unsafe impl Send for RefCell where T: Send {} + +impl Clone for RefCell { + #[inline] + fn clone(&self) -> RefCell { + RefCell::new(self.borrow().clone()) + } +} + +impl Default for RefCell { + #[inline] + fn default() -> RefCell { + RefCell::new(Default::default()) + } +} + +impl PartialEq for RefCell { + #[inline] + fn eq(&self, other: &RefCell) -> bool { + *self.borrow() == *other.borrow() + } +} + +impl Eq for RefCell {} + +impl PartialOrd for RefCell { + #[inline] + fn partial_cmp(&self, other: &RefCell) -> Option { + self.borrow().partial_cmp(&*other.borrow()) + } + + #[inline] + fn lt(&self, other: &RefCell) -> bool { + *self.borrow() < *other.borrow() + } + + #[inline] + fn le(&self, other: &RefCell) -> bool { + *self.borrow() <= *other.borrow() + } + + #[inline] + fn gt(&self, other: &RefCell) -> bool { + *self.borrow() > *other.borrow() + } + + #[inline] + fn ge(&self, other: &RefCell) -> bool { + *self.borrow() >= *other.borrow() + } +} + +impl Ord for RefCell { + #[inline] + fn cmp(&self, other: &RefCell) -> Ordering { + self.borrow().cmp(&*other.borrow()) + } +} + +struct BorrowRef<'b> { + borrow: &'b Cell, +} + +impl<'b> BorrowRef<'b> { + #[inline] + fn new(borrow: &'b Cell) -> Option> { + match borrow.get() { + WRITING => None, + b => { + borrow.set(b + 1); + Some(BorrowRef { borrow: borrow }) + }, + } + } +} + +impl<'b> Drop for BorrowRef<'b> { + #[inline] + fn drop(&mut self) { + let borrow = self.borrow.get(); + debug_assert!(borrow != WRITING && borrow != UNUSED); + self.borrow.set(borrow - 1); + } +} + +impl<'b> Clone for BorrowRef<'b> { + #[inline] + fn clone(&self) -> BorrowRef<'b> { + // Since this Ref exists, we know the borrow flag + // is not set to WRITING. + let borrow = self.borrow.get(); + debug_assert!(borrow != UNUSED); + // Prevent the borrow counter from overflowing. + assert!(borrow != WRITING); + self.borrow.set(borrow + 1); + BorrowRef { borrow: self.borrow } + } +} + +/// Wraps a borrowed reference to a value in a `RefCell` box. +/// A wrapper type for an immutably borrowed value from a `RefCell`. +/// +/// See the [module-level documentation](index.html) for more. +pub struct Ref<'b, T: ?Sized + 'b> { + value: &'b T, + borrow: BorrowRef<'b>, +} + +impl<'b, T: ?Sized> Deref for Ref<'b, T> { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + self.value + } +} + +impl<'b, T: ?Sized> Ref<'b, T> { + /// Copies a `Ref`. + /// + /// The `RefCell` is already immutably borrowed, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere + /// with the widespread use of `r.borrow().clone()` to clone the contents of + /// a `RefCell`. + #[inline] + pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> { + Ref { + value: orig.value, + borrow: orig.borrow.clone(), + } + } + + /// Make a new `Ref` for a component of the borrowed data. + /// + /// The `RefCell` is already immutably borrowed, so this cannot fail. + /// + /// This is an associated function that needs to be used as `Ref::map(...)`. + /// A method would interfere with methods of the same name on the contents + /// of a `RefCell` used through `Deref`. + /// + /// # Example + /// + /// ``` + /// use std::cell::{RefCell, Ref}; + /// + /// let c = RefCell::new((5, 'b')); + /// let b1: Ref<(u32, char)> = c.borrow(); + /// let b2: Ref = Ref::map(b1, |t| &t.0); + /// assert_eq!(*b2, 5) + /// ``` + #[inline] + pub fn map(orig: Ref<'b, T>, f: F) -> Ref<'b, U> + where F: FnOnce(&T) -> &U + { + Ref { + value: f(orig.value), + borrow: orig.borrow, + } + } +} + +impl<'b, T: ?Sized> RefMut<'b, T> { + /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum + /// variant. + /// + /// The `RefCell` is already mutably borrowed, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `RefMut::map(...)`. A method would interfere with methods of the same + /// name on the contents of a `RefCell` used through `Deref`. + /// + /// # Example + /// + /// ``` + /// use std::cell::{RefCell, RefMut}; + /// + /// let c = RefCell::new((5, 'b')); + /// { + /// let b1: RefMut<(u32, char)> = c.borrow_mut(); + /// let mut b2: RefMut = RefMut::map(b1, |t| &mut t.0); + /// assert_eq!(*b2, 5); + /// *b2 = 42; + /// } + /// assert_eq!(*c.borrow(), (42, 'b')); + /// ``` + #[inline] + pub fn map(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U> + where F: FnOnce(&mut T) -> &mut U + { + RefMut { + value: f(orig.value), + borrow: orig.borrow, + } + } +} + +struct BorrowRefMut<'b> { + borrow: &'b Cell, +} + +impl<'b> Drop for BorrowRefMut<'b> { + #[inline] + fn drop(&mut self) { + let borrow = self.borrow.get(); + debug_assert!(borrow == WRITING); + self.borrow.set(UNUSED); + } +} + +impl<'b> BorrowRefMut<'b> { + #[inline] + fn new(borrow: &'b Cell) -> Option> { + match borrow.get() { + UNUSED => { + borrow.set(WRITING); + Some(BorrowRefMut { borrow: borrow }) + }, + _ => None, + } + } +} + +/// A wrapper type for a mutably borrowed value from a `RefCell`. +/// +/// See the [module-level documentation](index.html) for more. +pub struct RefMut<'b, T: ?Sized + 'b> { + value: &'b mut T, + borrow: BorrowRefMut<'b>, +} + +impl<'b, T: ?Sized> Deref for RefMut<'b, T> { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + self.value + } +} + +impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> { + #[inline] + fn deref_mut(&mut self) -> &mut T { + self.value + } +} diff --git a/src/lib.rs b/src/lib.rs index be43ca58..d2d36307 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,6 @@ #![crate_name = "bindgen"] #![crate_type = "dylib"] #![feature(quote)] -#![feature(borrow_state)] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] diff --git a/src/parser.rs b/src/parser.rs index 3004eb40..12047213 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,7 +1,7 @@ #![allow(non_upper_case_globals)] use std::collections::{HashMap, HashSet}; -use std::cell::RefCell; +use hacks::refcell::RefCell; use std::rc::Rc; use std::path::Path; use std::cmp; @@ -393,7 +393,7 @@ fn conv_decl_ty_resolving_typedefs(ctx: &mut ClangParserCtx, // We might incur in double borrows here. If that's the case, we're // already scanning the compinfo, and we'd get the args from the // ast. - use std::cell::BorrowState; + use hacks::refcell::BorrowState; if !args.is_empty() && ci.borrow_state() == BorrowState::Unused { ci.borrow_mut().args = args; @@ -607,7 +607,7 @@ fn visit_composite(cursor: &Cursor, parent: &Cursor, is_class_typedef); - use std::cell::BorrowState; + use hacks::refcell::BorrowState; if let Some(child_ci) = ty.get_outermost_composite() { if let BorrowState::Unused = child_ci.borrow_state() { let mut child_ci = child_ci.borrow_mut(); diff --git a/src/types.rs b/src/types.rs index 4527d710..a1d574f2 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,4 +1,5 @@ -use std::cell::{Cell, RefCell}; +use std::cell::Cell; +use hacks::refcell::RefCell; use std::fmt; use std::rc::Rc; use std::collections::HashMap; -- cgit v1.2.3