Skip to content

Commit

Permalink
Auto merge of #30184 - petrochenkov:ascr, r=nikomatsakis
Browse files Browse the repository at this point in the history
This PR is a rebase of the original PR by @eddyb #21836 with some unrebasable parts manually reapplied, feature gate added + type equality restriction added as described below.

This implementation is partial because the type equality restriction is applied to all type ascription expressions and not only those in lvalue contexts. Thus, all difficulties with detection of these contexts and translation of coercions having effect in runtime are avoided.
So, you can't write things with coercions like `let slice = &[1, 2, 3]: &[u8];`. It obviously makes type ascription less useful than it should be, but it's still much more useful than not having type ascription at all.
In particular, things like `let v = something.iter().collect(): Vec<_>;` and `let u = t.into(): U;` work as expected and I'm pretty happy with these improvements alone.

Part of #23416
  • Loading branch information
bors committed Dec 19, 2015
2 parents 8ad12c3 + 95fdaf2 commit 440ef8b
Show file tree
Hide file tree
Showing 36 changed files with 321 additions and 24 deletions.
2 changes: 2 additions & 0 deletions src/doc/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -2388,6 +2388,8 @@ The currently implemented features of the reference compiler are:

* - `deprecated` - Allows using the `#[deprecated]` attribute.

* - `type_ascription` - Allows type ascription expressions `expr: Type`.

If a feature is promoted to a language feature, then all existing programs will
start to receive compilation warnings about `#![feature]` directives which enabled
the new feature (because the directive is no longer necessary). However, if a
Expand Down
1 change: 1 addition & 0 deletions src/librustc/middle/cfg/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
hir::ExprBox(ref e) |
hir::ExprAddrOf(_, ref e) |
hir::ExprCast(ref e, _) |
hir::ExprType(ref e, _) |
hir::ExprUnary(_, ref e) |
hir::ExprField(ref e, _) |
hir::ExprTupField(ref e, _) => {
Expand Down
1 change: 1 addition & 0 deletions src/librustc/middle/check_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,7 @@ fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>,
hir::ExprField(..) |
hir::ExprTupField(..) |
hir::ExprVec(_) |
hir::ExprType(..) |
hir::ExprTup(..) => {}

// Conditional control flow (possible to implement).
Expand Down
1 change: 1 addition & 0 deletions src/librustc/middle/const_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,7 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &ty::ctxt<'tcx>,
None => unreachable!(),
}
}
hir::ExprType(ref e, _) => try!(eval_const_expr_partial(tcx, &**e, ty_hint, fn_args)),
hir::ExprTup(_) => Tuple(e.id),
hir::ExprStruct(..) => Struct(e.id),
hir::ExprIndex(ref arr, ref idx) => {
Expand Down
4 changes: 4 additions & 0 deletions src/librustc/middle/expr_use_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,10 @@ impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
match expr.node {
hir::ExprPath(..) => { }

hir::ExprType(ref subexpr, _) => {
self.walk_expr(&**subexpr)
}

hir::ExprUnary(hir::UnDeref, ref base) => { // *base
if !self.walk_overloaded_operator(expr, &**base, Vec::new(), PassArgs::ByRef) {
self.select_from_expr(&**base);
Expand Down
5 changes: 3 additions & 2 deletions src/librustc/middle/liveness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
hir::ExprBlock(..) | hir::ExprAssign(..) | hir::ExprAssignOp(..) |
hir::ExprStruct(..) | hir::ExprRepeat(..) |
hir::ExprInlineAsm(..) | hir::ExprBox(..) |
hir::ExprRange(..) => {
hir::ExprRange(..) | hir::ExprType(..) => {
intravisit::walk_expr(ir, expr);
}
}
Expand Down Expand Up @@ -1160,6 +1160,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
hir::ExprBox(ref e) |
hir::ExprAddrOf(_, ref e) |
hir::ExprCast(ref e, _) |
hir::ExprType(ref e, _) |
hir::ExprUnary(_, ref e) => {
self.propagate_through_expr(&**e, succ)
}
Expand Down Expand Up @@ -1443,7 +1444,7 @@ fn check_expr(this: &mut Liveness, expr: &Expr) {
hir::ExprBlock(..) | hir::ExprAddrOf(..) |
hir::ExprStruct(..) | hir::ExprRepeat(..) |
hir::ExprClosure(..) | hir::ExprPath(..) | hir::ExprBox(..) |
hir::ExprRange(..) => {
hir::ExprRange(..) | hir::ExprType(..) => {
intravisit::walk_expr(this, expr);
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/librustc/middle/mem_categorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,10 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
self.cat_def(expr.id, expr.span, expr_ty, def)
}

hir::ExprType(ref e, _) => {
self.cat_expr(&**e)
}

hir::ExprAddrOf(..) | hir::ExprCall(..) |
hir::ExprAssign(..) | hir::ExprAssignOp(..) |
hir::ExprClosure(..) | hir::ExprRet(..) |
Expand Down
4 changes: 4 additions & 0 deletions src/librustc/middle/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2114,6 +2114,10 @@ impl<'tcx> ctxt<'tcx> {
}
}

hir::ExprType(ref e, _) => {
self.expr_is_lval(e)
}

hir::ExprUnary(hir::UnDeref, _) |
hir::ExprField(..) |
hir::ExprTupField(..) |
Expand Down
2 changes: 2 additions & 0 deletions src/librustc_back/svh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ mod svh_visitor {
SawExprUnary(hir::UnOp),
SawExprLit(ast::Lit_),
SawExprCast,
SawExprType,
SawExprIf,
SawExprWhile,
SawExprMatch,
Expand Down Expand Up @@ -262,6 +263,7 @@ mod svh_visitor {
ExprUnary(op, _) => SawExprUnary(op),
ExprLit(ref lit) => SawExprLit(lit.node.clone()),
ExprCast(..) => SawExprCast,
ExprType(..) => SawExprType,
ExprIf(..) => SawExprIf,
ExprWhile(..) => SawExprWhile,
ExprLoop(_, id) => SawExprLoop(id.map(|id| id.name.as_str())),
Expand Down
3 changes: 3 additions & 0 deletions src/librustc_front/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,9 @@ pub fn noop_fold_expr<T: Folder>(Expr { id, node, span, attrs }: Expr, folder: &
ExprCast(expr, ty) => {
ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprType(expr, ty) => {
ExprType(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
ExprIf(cond, tr, fl) => {
ExprIf(folder.fold_expr(cond),
Expand Down
1 change: 1 addition & 0 deletions src/librustc_front/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,7 @@ pub enum Expr_ {
ExprLit(P<Lit>),
/// A cast (`foo as f64`)
ExprCast(P<Expr>, P<Ty>),
ExprType(P<Expr>, P<Ty>),
/// An `if` block, with an optional else block
///
/// `if expr { block } else { expr }`
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_front/intravisit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
visitor.visit_expr(subexpression)
}
ExprLit(_) => {}
ExprCast(ref subexpression, ref typ) => {
ExprCast(ref subexpression, ref typ) | ExprType(ref subexpression, ref typ) => {
visitor.visit_expr(subexpression);
visitor.visit_ty(typ)
}
Expand Down
4 changes: 4 additions & 0 deletions src/librustc_front/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,10 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
let expr = lower_expr(lctx, expr);
hir::ExprCast(expr, lower_ty(lctx, ty))
}
ExprType(ref expr, ref ty) => {
let expr = lower_expr(lctx, expr);
hir::ExprType(expr, lower_ty(lctx, ty))
}
ExprAddrOf(m, ref ohs) => {
let m = lower_mutability(lctx, m);
let ohs = lower_expr(lctx, ohs);
Expand Down
8 changes: 7 additions & 1 deletion src/librustc_front/print/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,8 @@ fn needs_parentheses(expr: &hir::Expr) -> bool {
hir::ExprBinary(..) |
hir::ExprClosure(..) |
hir::ExprAssignOp(..) |
hir::ExprCast(..) => true,
hir::ExprCast(..) |
hir::ExprType(..) => true,
_ => false,
}
}
Expand Down Expand Up @@ -1353,6 +1354,11 @@ impl<'a> State<'a> {
try!(self.word_space("as"));
try!(self.print_type(&**ty));
}
hir::ExprType(ref expr, ref ty) => {
try!(self.print_expr(&**expr));
try!(self.word_space(":"));
try!(self.print_type(&**ty));
}
hir::ExprIf(ref test, ref blk, ref elseopt) => {
try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
}
Expand Down
1 change: 1 addition & 0 deletions src/librustc_lint/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ impl UnusedParens {
}
ast::ExprUnary(_, ref x) |
ast::ExprCast(ref x, _) |
ast::ExprType(ref x, _) |
ast::ExprField(ref x, _) |
ast::ExprTupField(ref x, _) |
ast::ExprIndex(ref x, _) => {
Expand Down
2 changes: 2 additions & 0 deletions src/librustc_mir/hair/cx/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,8 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr {
name: Field::new(index.node as usize) },
hir::ExprCast(ref source, _) =>
ExprKind::Cast { source: source.to_ref() },
hir::ExprType(ref source, _) =>
return source.make_mirror(cx),
hir::ExprBox(ref value) =>
ExprKind::Box { value: value.to_ref() },
hir::ExprVec(ref fields) =>
Expand Down
1 change: 1 addition & 0 deletions src/librustc_trans/trans/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1003,6 +1003,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
try!(const_fn_call(cx, MethodCallKey(method_call),
method_did, &arg_vals, param_substs, trueconst))
},
hir::ExprType(ref e, _) => try!(const_expr(cx, &**e, param_substs, fn_args, trueconst)).0,
hir::ExprBlock(ref block) => {
match block.expr {
Some(ref expr) => try!(const_expr(
Expand Down
1 change: 1 addition & 0 deletions src/librustc_trans/trans/debuginfo/create_scope_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ fn walk_expr(cx: &CrateContext,
hir::ExprPath(..) => {}

hir::ExprCast(ref sub_exp, _) |
hir::ExprType(ref sub_exp, _) |
hir::ExprAddrOf(_, ref sub_exp) |
hir::ExprField(ref sub_exp, _) |
hir::ExprTupField(ref sub_exp, _) =>
Expand Down
13 changes: 13 additions & 0 deletions src/librustc_trans/trans/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,9 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
let _icx = push_ctxt("trans_datum_unadjusted");

match expr.node {
hir::ExprType(ref e, _) => {
trans(bcx, &**e)
}
hir::ExprPath(..) => {
trans_def(bcx, expr, bcx.def(expr.id))
}
Expand Down Expand Up @@ -941,6 +944,9 @@ fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
hir::ExprBreak(label_opt) => {
controlflow::trans_break(bcx, expr, label_opt.map(|l| l.node.name))
}
hir::ExprType(ref e, _) => {
trans_into(bcx, &**e, Ignore)
}
hir::ExprAgain(label_opt) => {
controlflow::trans_cont(bcx, expr, label_opt.map(|l| l.node.name))
}
Expand Down Expand Up @@ -1064,6 +1070,9 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);

match expr.node {
hir::ExprType(ref e, _) => {
trans_into(bcx, &**e, dest)
}
hir::ExprPath(..) => {
trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
}
Expand Down Expand Up @@ -2601,6 +2610,10 @@ fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind {
}
}

hir::ExprType(ref expr, _) => {
expr_kind(tcx, expr)
}

hir::ExprUnary(hir::UnDeref, _) |
hir::ExprField(..) |
hir::ExprTupField(..) |
Expand Down
13 changes: 13 additions & 0 deletions src/librustc_typeck/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2648,6 +2648,14 @@ fn check_lit<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
}
}

fn check_expr_eq_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx hir::Expr,
expected: Ty<'tcx>) {
check_expr_with_unifier(
fcx, expr, ExpectHasType(expected), NoPreference,
|| demand::eqtype(fcx, expr.span, expected, fcx.expr_ty(expr)));
}

pub fn check_expr_has_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx hir::Expr,
expected: Ty<'tcx>) {
Expand Down Expand Up @@ -3510,6 +3518,11 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
deferred_cast_checks.push(cast_check);
}
}
hir::ExprType(ref e, ref t) => {
let typ = fcx.to_ty(&**t);
check_expr_eq_type(fcx, &**e, typ);
fcx.write_ty(id, typ);
}
hir::ExprVec(ref args) => {
let uty = expected.to_option(fcx).and_then(|uty| {
match uty.sty {
Expand Down
1 change: 1 addition & 0 deletions src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -942,6 +942,7 @@ pub enum Expr_ {
ExprLit(P<Lit>),
/// A cast (`foo as f64`)
ExprCast(P<Expr>, P<Ty>),
ExprType(P<Expr>, P<Ty>),
/// An `if` block, with an optional else block
///
/// `if expr { block } else { expr }`
Expand Down
7 changes: 7 additions & 0 deletions src/libsyntax/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ const KNOWN_FEATURES: &'static [(&'static str, &'static str, Option<u32>, Status

// Allows `#[deprecated]` attribute
("deprecated", "1.6.0", Some(29935), Active),

// allow using type ascription in expressions
("type_ascription", "1.6.0", Some(23416), Active),
];
// (changing above list without updating src/doc/reference.md makes @cmr sad)

Expand Down Expand Up @@ -958,6 +961,10 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
"box expression syntax is experimental; \
you can call `Box::new` instead.");
}
ast::ExprType(..) => {
self.gate_feature("type_ascription", e.span,
"type ascription is experimental");
}
_ => {}
}
visit::walk_expr(self, e);
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,9 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
ExprCast(expr, ty) => {
ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprType(expr, ty) => {
ExprType(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
ExprIf(cond, tr, fl) => {
ExprIf(folder.fold_expr(cond),
Expand Down
12 changes: 9 additions & 3 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use ast::{ExprBreak, ExprCall, ExprCast, ExprInPlace};
use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
use ast::{ExprMethodCall, ExprParen, ExprPath};
use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprType, ExprUnary};
use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, FunctionRetTy};
use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
Expand Down Expand Up @@ -2787,6 +2787,11 @@ impl<'a> Parser<'a> {
lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
ExprCast(lhs, rhs), None);
continue
} else if op == AssocOp::Colon {
let rhs = try!(self.parse_ty());
lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
ExprType(lhs, rhs), None);
continue
} else if op == AssocOp::DotDot {
// If we didn’t have to handle `x..`, it would be pretty easy to generalise
// it to the Fixity::None code.
Expand All @@ -2809,7 +2814,6 @@ impl<'a> Parser<'a> {
break
}


let rhs = try!(match op.fixity() {
Fixity::Right => self.with_res(restrictions, |this|{
this.parse_assoc_expr_with(op.precedence(), LhsExpr::NotYetParsed)
Expand Down Expand Up @@ -2856,7 +2860,9 @@ impl<'a> Parser<'a> {
let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
}
AssocOp::As | AssocOp::DotDot => self.bug("As or DotDot branch reached")
AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
self.bug("As, Colon or DotDot branch reached")
}
};

if op.fixity() == Fixity::None { break }
Expand Down
7 changes: 6 additions & 1 deletion src/libsyntax/print/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ fn needs_parentheses(expr: &ast::Expr) -> bool {
ast::ExprAssign(..) | ast::ExprBinary(..) |
ast::ExprClosure(..) |
ast::ExprAssignOp(..) | ast::ExprCast(..) |
ast::ExprInPlace(..) => true,
ast::ExprInPlace(..) | ast::ExprType(..) => true,
_ => false,
}
}
Expand Down Expand Up @@ -2035,6 +2035,11 @@ impl<'a> State<'a> {
try!(self.word_space("as"));
try!(self.print_type(&**ty));
}
ast::ExprType(ref expr, ref ty) => {
try!(self.print_expr(&**expr));
try!(self.word_space(":"));
try!(self.print_type(&**ty));
}
ast::ExprIf(ref test, ref blk, ref elseopt) => {
try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
}
Expand Down
Loading

0 comments on commit 440ef8b

Please sign in to comment.