Allow constant struct fields and tuple indexing

This commit is contained in:
Adolfo Ochagavía 2014-11-24 12:46:02 +01:00
parent c637cab853
commit fbde11297f

View File

@ -567,6 +567,34 @@ pub fn eval_const_expr_partial(tcx: &ty::ctxt, e: &Expr) -> Result<const_val, St
None => Ok(const_int(0i64))
}
}
ast::ExprTupField(ref base, index) => {
// Get the base tuple if it is constant
if let Some(&ast::ExprTup(ref fields)) = lookup_const(tcx, &**base).map(|s| &s.node) {
// Check that the given index is within bounds and evaluate its value
if fields.len() > index.node {
return eval_const_expr_partial(tcx, &*fields[index.node])
} else {
return Err("tuple index out of bounds".to_string())
}
}
Err("non-constant struct in constant expr".to_string())
}
ast::ExprField(ref base, field_name) => {
// Get the base expression if it is a struct and it is constant
if let Some(&ast::ExprStruct(_, ref fields, _)) = lookup_const(tcx, &**base)
.map(|s| &s.node) {
// Check that the given field exists and evaluate it
if let Some(f) = fields.iter().find(|f|
f.ident.node.as_str() == field_name.node.as_str()) {
return eval_const_expr_partial(tcx, &*f.expr)
} else {
return Err("nonexistent struct field".to_string())
}
}
Err("non-constant struct in constant expr".to_string())
}
_ => Err("unsupported constant expr".to_string())
}
}