Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement automatic overloaded deref. #12610

Merged
merged 7 commits into from
Mar 13, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -1687,7 +1687,7 @@ let x = Rc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let y = x.clone(); // a new owner
let z = x; // this moves `x` into `z`, rather than creating a new owner

assert!(*z.borrow() == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

// the variable is mutable, but not the contents of the box
let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
Expand Down
4 changes: 2 additions & 2 deletions src/libarena/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ struct Chunk {
}
impl Chunk {
fn capacity(&self) -> uint {
self.data.borrow().borrow().get().capacity()
self.data.deref().borrow().get().capacity()
}

unsafe fn as_ptr(&self) -> *u8 {
self.data.borrow().borrow().get().as_ptr()
self.data.deref().borrow().get().as_ptr()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/libnum/complex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl<T: Clone + Float> Cmplx<T> {
/// Convert a polar representation into a complex number.
#[inline]
pub fn from_polar(r: &T, theta: &T) -> Cmplx<T> {
Cmplx::new(r * theta.cos(), r * theta.sin())
Cmplx::new(*r * theta.cos(), *r * theta.sin())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this mean the &1 + 2 bug is fixed?

(If so, needstest)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've only changed x OP y with x &T instead of T where T is a generic type param with the operator overload in its trait bounds, and it wasn't to fix that bug, but prevent nasty recursion in autoderef.

I guess I should fiddle with the lookup code some more to deny more forms, as this is likely to also affect autoderef.

}
}

Expand Down
3 changes: 2 additions & 1 deletion src/librustc/driver/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,7 +1020,8 @@ pub fn build_session_(sopts: @session::Options,
lints: RefCell::new(HashMap::new()),
node_id: Cell::new(1),
crate_types: @RefCell::new(Vec::new()),
features: front::feature_gate::Features::new()
features: front::feature_gate::Features::new(),
recursion_limit: Cell::new(64),
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/librustc/driver/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@ pub struct Session_ {
Vec<(lint::Lint, codemap::Span, ~str)> >>,
node_id: Cell<ast::NodeId>,
crate_types: @RefCell<Vec<CrateType> >,
features: front::feature_gate::Features
features: front::feature_gate::Features,

/// The maximum recursion limit for potentially infinitely recursive
/// operations such as auto-dereference and monomorphization.
recursion_limit: Cell<uint>,
}

pub type Session = @Session_;
Expand Down
10 changes: 6 additions & 4 deletions src/librustc/middle/astencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use metadata::tydecode;
use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter,
RegionParameter};
use metadata::tyencode;
use middle::typeck::{MethodCallee, MethodOrigin};
use middle::typeck::{MethodCall, MethodCallee, MethodOrigin};
use middle::{ty, typeck, moves};
use middle;
use util::ppaux::ty_to_str;
Expand Down Expand Up @@ -1039,7 +1039,8 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
}
}

for &method in maps.method_map.borrow().get().find(&id).iter() {
let method_call = MethodCall::expr(id);
for &method in maps.method_map.borrow().get().find(&method_call).iter() {
ebml_w.tag(c::tag_table_method_map, |ebml_w| {
ebml_w.id(id);
ebml_w.tag(c::tag_table_val, |ebml_w| {
Expand Down Expand Up @@ -1081,7 +1082,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
ebml_w.tag(c::tag_table_capture_map, |ebml_w| {
ebml_w.id(id);
ebml_w.tag(c::tag_table_val, |ebml_w| {
ebml_w.emit_from_vec(cap_vars.borrow().as_slice(),
ebml_w.emit_from_vec(cap_vars.deref().as_slice(),
|ebml_w, cap_var| {
cap_var.encode(ebml_w);
})
Expand Down Expand Up @@ -1385,7 +1386,8 @@ fn decode_side_tables(xcx: @ExtendedDecodeContext,
}
c::tag_table_method_map => {
let method = val_dsr.read_method_callee(xcx);
dcx.maps.method_map.borrow_mut().get().insert(id, method);
let method_call = MethodCall::expr(id);
dcx.maps.method_map.borrow_mut().get().insert(method_call, method);
}
c::tag_table_vtable_map => {
let vtable_res =
Expand Down
7 changes: 4 additions & 3 deletions src/librustc/middle/borrowck/check_loans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use mc = middle::mem_categorization;
use middle::borrowck::*;
use middle::moves;
use middle::ty;
use middle::typeck::MethodCall;
use std::vec_ng::Vec;
use syntax::ast;
use syntax::ast_util;
Expand Down Expand Up @@ -716,7 +717,7 @@ impl<'a> CheckLoanCtxt<'a> {
span: Span) {
let capture_map = self.bccx.capture_map.borrow();
let cap_vars = capture_map.get().get(&closure_id);
for cap_var in cap_vars.borrow().iter() {
for cap_var in cap_vars.deref().iter() {
let var_id = ast_util::def_id_of_def(cap_var.def).node;
let var_path = @LpVar(var_id);
self.check_if_path_is_moved(closure_id, span,
Expand Down Expand Up @@ -838,11 +839,11 @@ fn check_loans_in_expr<'a>(this: &mut CheckLoanCtxt<'a>,
this.check_call(expr, None, expr.span, args.as_slice());
}
ast::ExprIndex(_, rval) | ast::ExprBinary(_, _, rval)
if method_map.get().contains_key(&expr.id) => {
if method_map.get().contains_key(&MethodCall::expr(expr.id)) => {
this.check_call(expr, None, expr.span, [rval]);
}
ast::ExprUnary(_, _) | ast::ExprIndex(_, _)
if method_map.get().contains_key(&expr.id) => {
if method_map.get().contains_key(&MethodCall::expr(expr.id)) => {
this.check_call(expr, None, expr.span, []);
}
ast::ExprInlineAsm(ref ia) => {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/borrowck/gather_loans/gather_moves.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn gather_captures(bccx: &BorrowckCtxt,
closure_expr: &ast::Expr) {
let capture_map = bccx.capture_map.borrow();
let captured_vars = capture_map.get().get(&closure_expr.id);
for captured_var in captured_vars.borrow().iter() {
for captured_var in captured_vars.deref().iter() {
match captured_var.mode {
moves::CapMove => {
let cmt = bccx.cat_captured_var(closure_expr.id,
Expand Down
44 changes: 40 additions & 4 deletions src/librustc/middle/borrowck/gather_loans/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use middle::moves;
use middle::pat_util;
use middle::ty::{ty_region};
use middle::ty;
use middle::typeck::MethodCall;
use util::common::indenter;
use util::ppaux::{Repr};

Expand Down Expand Up @@ -242,7 +243,7 @@ fn gather_loans_in_expr(this: &mut GatherLoanCtxt,

ast::ExprIndex(_, arg) |
ast::ExprBinary(_, _, arg)
if method_map.get().contains_key(&ex.id) => {
if method_map.get().contains_key(&MethodCall::expr(ex.id)) => {
// Arguments in method calls are always passed by ref.
//
// Currently these do not use adjustments, so we have to
Expand Down Expand Up @@ -325,6 +326,39 @@ impl<'a> GatherLoanCtxt<'a> {
assert_eq!(id, popped);
}

pub fn guarantee_autoderefs(&mut self,
expr: &ast::Expr,
autoderefs: uint) {
let method_map = self.bccx.method_map.borrow();
for i in range(0, autoderefs) {
match method_map.get().find(&MethodCall::autoderef(expr.id, i as u32)) {
Some(method) => {
// Treat overloaded autoderefs as if an AutoRef adjustment
// was applied on the base type, as that is always the case.
let mut mc = self.bccx.mc();
let cmt = match mc.cat_expr_autoderefd(expr, i) {
Ok(v) => v,
Err(()) => self.tcx().sess.span_bug(expr.span, "Err from mc")
};
let self_ty = *ty::ty_fn_args(method.ty).get(0);
let (m, r) = match ty::get(self_ty).sty {
ty::ty_rptr(r, ref m) => (m.mutbl, r),
_ => self.tcx().sess.span_bug(expr.span,
format!("bad overloaded deref type {}",
method.ty.repr(self.tcx())))
};
self.guarantee_valid(expr.id,
expr.span,
cmt,
m,
r,
AutoRef);
}
None => {}
}
}
}

pub fn guarantee_adjustments(&mut self,
expr: &ast::Expr,
adjustment: &ty::AutoAdjustment) {
Expand All @@ -340,15 +374,17 @@ impl<'a> GatherLoanCtxt<'a> {

ty::AutoDerefRef(
ty::AutoDerefRef {
autoref: None, .. }) => {
autoref: None, autoderefs }) => {
debug!("no autoref");
self.guarantee_autoderefs(expr, autoderefs);
return;
}

ty::AutoDerefRef(
ty::AutoDerefRef {
autoref: Some(ref autoref),
autoderefs: autoderefs}) => {
autoderefs}) => {
self.guarantee_autoderefs(expr, autoderefs);
let mut mc = self.bccx.mc();
let cmt = match mc.cat_expr_autoderefd(expr, autoderefs) {
Ok(v) => v,
Expand Down Expand Up @@ -406,7 +442,7 @@ impl<'a> GatherLoanCtxt<'a> {
closure_expr: &ast::Expr) {
let capture_map = self.bccx.capture_map.borrow();
let captured_vars = capture_map.get().get(&closure_expr.id);
for captured_var in captured_vars.borrow().iter() {
for captured_var in captured_vars.deref().iter() {
match captured_var.mode {
moves::CapCopy | moves::CapMove => { continue; }
moves::CapRef => { }
Expand Down
12 changes: 7 additions & 5 deletions src/librustc/middle/borrowck/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,8 @@ impl BorrowckCtxt {
move_data::MoveExpr => {
let (expr_ty, expr_span) = match self.tcx.map.find(move.id) {
Some(ast_map::NodeExpr(expr)) => {
(ty::expr_ty_adjusted(self.tcx, expr), expr.span)
(ty::expr_ty_adjusted(self.tcx, expr,
self.method_map.borrow().get()), expr.span)
}
r => self.tcx.sess.bug(format!("MoveExpr({:?}) maps to {:?}, not Expr",
move.id, r))
Expand All @@ -582,7 +583,8 @@ impl BorrowckCtxt {
move_data::Captured => {
let (expr_ty, expr_span) = match self.tcx.map.find(move.id) {
Some(ast_map::NodeExpr(expr)) => {
(ty::expr_ty_adjusted(self.tcx, expr), expr.span)
(ty::expr_ty_adjusted(self.tcx, expr,
self.method_map.borrow().get()), expr.span)
}
r => self.tcx.sess.bug(format!("Captured({:?}) maps to {:?}, not Expr",
move.id, r))
Expand Down Expand Up @@ -922,8 +924,8 @@ impl mc::Typer for TcxTyper {
Ok(ty::node_id_to_type(self.tcx, id))
}

fn node_method_ty(&mut self, id: ast::NodeId) -> Option<ty::t> {
self.method_map.borrow().get().find(&id).map(|method| method.ty)
fn node_method_ty(&mut self, method_call: typeck::MethodCall) -> Option<ty::t> {
self.method_map.borrow().get().find(&method_call).map(|method| method.ty)
}

fn adjustment(&mut self, id: ast::NodeId) -> Option<@ty::AutoAdjustment> {
Expand All @@ -932,7 +934,7 @@ impl mc::Typer for TcxTyper {
}

fn is_method_call(&mut self, id: ast::NodeId) -> bool {
self.method_map.borrow().get().contains_key(&id)
self.method_map.borrow().get().contains_key(&typeck::MethodCall::expr(id))
}

fn temporary_scope(&mut self, id: ast::NodeId) -> Option<ast::NodeId> {
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/cfg/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ impl CFGBuilder {
}

fn is_method_call(&self, expr: &ast::Expr) -> bool {
let method_map = self.method_map.borrow();
method_map.get().contains_key(&expr.id)
let method_call = typeck::MethodCall::expr(expr.id);
self.method_map.borrow().get().contains_key(&method_call)
}
}
4 changes: 2 additions & 2 deletions src/librustc/middle/check_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ pub fn check_expr(v: &mut CheckCrateVisitor,
}
ExprLit(lit) if ast_util::lit_is_str(lit) => {}
ExprBinary(..) | ExprUnary(..) => {
let method_map = method_map.borrow();
if method_map.get().contains_key(&e.id) {
let method_call = typeck::MethodCall::expr(e.id);
if method_map.borrow().get().contains_key(&method_call) {
sess.span_err(e.span, "user-defined operators are not \
allowed in constant expressions");
}
Expand Down
8 changes: 4 additions & 4 deletions src/librustc/middle/const_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use middle::astencode;
use middle::ty;
use middle::typeck::astconv;
use middle;
use util::nodemap::{DefIdMap, NodeMap};
use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};

use syntax::ast::*;
use syntax::parse::token::InternedString;
Expand Down Expand Up @@ -136,7 +136,7 @@ pub fn lookup_variant_by_id(tcx: ty::ctxt,
}
let maps = astencode::Maps {
root_map: @RefCell::new(HashMap::new()),
method_map: @RefCell::new(NodeMap::new()),
method_map: @RefCell::new(FnvHashMap::new()),
vtable_map: @RefCell::new(NodeMap::new()),
capture_map: @RefCell::new(NodeMap::new())
};
Expand Down Expand Up @@ -186,7 +186,7 @@ pub fn lookup_const_by_id(tcx: ty::ctxt, def_id: ast::DefId)
}
let maps = astencode::Maps {
root_map: @RefCell::new(HashMap::new()),
method_map: @RefCell::new(NodeMap::new()),
method_map: @RefCell::new(FnvHashMap::new()),
vtable_map: @RefCell::new(NodeMap::new()),
capture_map: @RefCell::new(NodeMap::new())
};
Expand Down Expand Up @@ -512,7 +512,7 @@ pub fn lit_to_const(lit: &Lit) -> const_val {
match lit.node {
LitStr(ref s, _) => const_str((*s).clone()),
LitBinary(ref data) => {
const_binary(Rc::new(data.borrow().iter().map(|x| *x).collect()))
const_binary(Rc::new(data.deref().iter().map(|x| *x).collect()))
}
LitChar(n) => const_uint(n as u64),
LitInt(n, _) => const_int(n),
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/dataflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -810,8 +810,8 @@ impl<'a, O:DataFlowOperator> PropagationContext<'a, O> {
}

fn is_method_call(&self, expr: &ast::Expr) -> bool {
let method_map = self.dfcx.method_map.borrow();
method_map.get().contains_key(&expr.id)
let method_call = typeck::MethodCall::expr(expr.id);
self.dfcx.method_map.borrow().get().contains_key(&method_call)
}

fn reset(&mut self, bits: &mut [uint]) {
Expand Down
7 changes: 4 additions & 3 deletions src/librustc/middle/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,10 @@ impl MarkSymbolVisitor {
}
}

fn lookup_and_handle_method(&mut self, id: &ast::NodeId,
fn lookup_and_handle_method(&mut self, id: ast::NodeId,
span: codemap::Span) {
match self.method_map.borrow().get().find(id) {
let method_call = typeck::MethodCall::expr(id);
match self.method_map.borrow().get().find(&method_call) {
Some(method) => {
match method.origin {
typeck::MethodStatic(def_id) => {
Expand Down Expand Up @@ -179,7 +180,7 @@ impl Visitor<()> for MarkSymbolVisitor {
fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
match expr.node {
ast::ExprMethodCall(..) => {
self.lookup_and_handle_method(&expr.id, expr.span);
self.lookup_and_handle_method(expr.id, expr.span);
}
_ => ()
}
Expand Down
5 changes: 3 additions & 2 deletions src/librustc/middle/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
/// `unsafe`.

use middle::ty;
use middle::typeck::MethodMap;
use middle::typeck::{MethodCall, MethodMap};
use util::ppaux;

use syntax::ast;
Expand Down Expand Up @@ -138,7 +138,8 @@ impl Visitor<()> for EffectCheckVisitor {
fn visit_expr(&mut self, expr: &ast::Expr, _:()) {
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let base_type = self.method_map.borrow().get().get(&expr.id).ty;
let method_call = MethodCall::expr(expr.id);
let base_type = self.method_map.borrow().get().get(&method_call).ty;
debug!("effect: method call case, base type is {}",
ppaux::ty_to_str(self.tcx, base_type));
if type_is_unsafe_function(base_type) {
Expand Down
7 changes: 4 additions & 3 deletions src/librustc/middle/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ pub fn check_expr(cx: &mut Context, e: &Expr) {
// Handle any kind bounds on type parameters
{
let method_map = cx.method_map.borrow();
let method = method_map.get().find(&e.id);
let method = method_map.get().find(&typeck::MethodCall::expr(e.id));
let node_type_substs = cx.tcx.node_type_substs.borrow();
let r = match method {
Some(method) => Some(&method.substs.tps),
Expand Down Expand Up @@ -298,7 +298,7 @@ pub fn check_expr(cx: &mut Context, e: &Expr) {
}
}
};
let type_param_defs = type_param_defs.borrow();
let type_param_defs = type_param_defs.deref();
if ts.len() != type_param_defs.len() {
// Fail earlier to make debugging easier
fail!("internal error: in kind::check_expr, length \
Expand Down Expand Up @@ -341,7 +341,8 @@ pub fn check_expr(cx: &mut Context, e: &Expr) {
match **adjustment {
ty::AutoObject(..) => {
let source_ty = ty::expr_ty(cx.tcx, e);
let target_ty = ty::expr_ty_adjusted(cx.tcx, e);
let target_ty = ty::expr_ty_adjusted(cx.tcx, e,
cx.method_map.borrow().get());
check_trait_cast(cx, source_ty, target_ty, e.span);
}
ty::AutoAddEnv(..) |
Expand Down
Loading