# impl Shape for int { }
# let mycircle = 0;
-let myshape: @Shape = @mycircle as @Shape;
+let myshape: ~Shape = ~mycircle as ~Shape;
~~~~
The resulting value is a managed box containing the value that was cast,
# impl Circle for int { fn radius(&self) -> f64 { 0.0 } }
# let mycircle = 0;
-let mycircle: Circle = @mycircle as @Circle;
+let mycircle: Circle = ~mycircle as ~Circle;
let nonsense = mycircle.radius() * mycircle.area();
~~~~
a call to a method on an object type is only resolved to a vtable entry at compile time.
The actual implementation for each vtable entry can vary on an object-by-object basis.
-Given a pointer-typed expression `E` of type `&T`, `~T` or `@T`, where `T` implements trait `R`,
-casting `E` to the corresponding pointer type `&R`, `~R` or `@R` results in a value of the _object type_ `R`.
+Given a pointer-typed expression `E` of type `&T` or `~T`, where `T` implements trait `R`,
+casting `E` to the corresponding pointer type `&R` or `~R` results in a value of the _object type_ `R`.
This result is represented as a pair of pointers:
the vtable pointer for the `T` implementation of `R`, and the pointer value of `E`.
fn to_string(&self) -> ~str { self.to_str() }
}
-fn print(a: @Printable) {
+fn print(a: ~Printable) {
println!("{}", a.to_string());
}
fn main() {
- print(@10 as @Printable);
+ print(~10 as ~Printable);
}
~~~~
The type of `self` is the type on which the method is implemented,
or a pointer thereof. As an argument it is written either `self`,
-`&self`, `@self`, or `~self`.
+`&self`, or `~self`.
A caller must in turn have a compatible pointer type to call the method.
~~~
# }
impl Shape {
fn draw_reference(&self) { ... }
- fn draw_managed(@self) { ... }
fn draw_owned(~self) { ... }
fn draw_value(self) { ... }
}
let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
-(@s).draw_managed();
(~s).draw_owned();
(&s).draw_reference();
s.draw_value();
# }
# impl Shape {
# fn draw_reference(&self) { ... }
-# fn draw_managed(@self) { ... }
# fn draw_owned(~self) { ... }
# fn draw_value(self) { ... }
# }
~~~~
# trait Drawable { fn draw(&self); }
-fn draw_all(shapes: &[@Drawable]) {
+fn draw_all(shapes: &[~Drawable]) {
for shape in shapes.iter() { shape.draw(); }
}
~~~~
-In this example, there is no type parameter. Instead, the `@Drawable`
-type denotes any managed box value that implements the `Drawable`
-trait. To construct such a value, you use the `as` operator to cast a
-value to an object:
+In this example, there is no type parameter. Instead, the `~Drawable`
+type denotes any owned box value that implements the `Drawable` trait.
+To construct such a value, you use the `as` operator to cast a value
+to an object:
~~~~
# type Circle = int; type Rectangle = bool;
# trait Drawable { fn draw(&self); }
# fn new_circle() -> Circle { 1 }
# fn new_rectangle() -> Rectangle { true }
-# fn draw_all(shapes: &[@Drawable]) {}
+# fn draw_all(shapes: &[~Drawable]) {}
impl Drawable for Circle { fn draw(&self) { ... } }
impl Drawable for Rectangle { fn draw(&self) { ... } }
-let c: @Circle = @new_circle();
-let r: @Rectangle = @new_rectangle();
-draw_all([c as @Drawable, r as @Drawable]);
+let c: ~Circle = ~new_circle();
+let r: ~Rectangle = ~new_rectangle();
+draw_all([c as ~Drawable, r as ~Drawable]);
~~~~
We omit the code for `new_circle` and `new_rectangle`; imagine that
# impl Drawable for int { fn draw(&self) {} }
# fn new_circle() -> int { 1 }
# fn new_rectangle() -> int { 2 }
-// A managed object
-let boxy: @Drawable = @new_circle() as @Drawable;
// An owned object
let owny: ~Drawable = ~new_circle() as ~Drawable;
// A borrowed object
order to be packaged up in a trait object of that storage class.
* The contents of owned traits (`~Trait`) must fulfill the `Send` bound.
-* The contents of managed traits (`@Trait`) must fulfill the `'static` bound.
* The contents of reference traits (`&Trait`) are not constrained by any bound.
Consequently, the trait objects themselves automatically fulfill their
the trait itself fulfills `Freeze`.
* `~Trait:Send` is equivalent to `~Trait`.
-* `@Trait:'static` is equivalent to `@Trait`.
* `&Trait:` is equivalent to `&Trait`.
Builtin kind bounds can also be specified on closure types in the same way (for
use syntax::attr::{AttrMetaMethods};
use syntax::codemap;
use syntax::diagnostic;
+use syntax::diagnostic::Emitter;
use syntax::ext::base::CrateLoader;
use syntax::parse;
use syntax::parse::token::InternedString;
}
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
-fn parse_cfgspecs(cfgspecs: ~[~str], demitter: @diagnostic::Emitter)
+fn parse_cfgspecs(cfgspecs: ~[~str])
-> ast::CrateConfig {
cfgspecs.move_iter().map(|s| {
- let sess = parse::new_parse_sess(Some(demitter));
+ let sess = parse::new_parse_sess();
parse::parse_meta_from_source_str("cfgspec".to_str(), s, ~[], sess)
}).collect::<ast::CrateConfig>()
}
phase_6_link_output(sess, &trans, &outputs);
}
-struct IdentifiedAnnotation {
- contents: (),
-}
+struct IdentifiedAnnotation;
impl pprust::PpAnn for IdentifiedAnnotation {
fn pre(&self, node: pprust::AnnNode) -> io::IoResult<()> {
let annotation = match ppm {
PpmIdentified | PpmExpandedIdentified => {
- @IdentifiedAnnotation {
- contents: (),
- } as @pprust::PpAnn
+ ~IdentifiedAnnotation as ~pprust::PpAnn
}
PpmTyped => {
let ast_map = ast_map.expect("--pretty=typed missing ast_map");
let analysis = phase_3_run_analysis_passes(sess, &crate, ast_map);
- @TypedAnnotation {
+ ~TypedAnnotation {
analysis: analysis
- } as @pprust::PpAnn
+ } as ~pprust::PpAnn:
}
- _ => @pprust::NoAnn as @pprust::PpAnn,
+ _ => ~pprust::NoAnn as ~pprust::PpAnn:,
};
let src = &sess.codemap.get_filemap(source_name(input)).src;
("mips", abi::Mips)];
-pub fn build_target_config(sopts: @session::Options,
- demitter: @diagnostic::Emitter)
+pub fn build_target_config(sopts: @session::Options)
-> @session::Config {
let os = match get_os(sopts.target_triple) {
Some(os) => os,
- None => early_error(demitter, "unknown operating system")
+ None => early_error("unknown operating system")
};
let arch = match get_arch(sopts.target_triple) {
Some(arch) => arch,
- None => early_error(demitter,
- "unknown architecture: " + sopts.target_triple)
+ None => early_error("unknown architecture: " + sopts.target_triple)
};
let (int_type, uint_type) = match arch {
abi::X86 => (ast::TyI32, ast::TyU32),
}
pub fn build_session_options(binary: ~str,
- matches: &getopts::Matches,
- demitter: @diagnostic::Emitter)
+ matches: &getopts::Matches)
-> @session::Options {
let crate_types = matches.opt_strs("crate-type").flat_map(|s| {
s.split(',').map(|part| {
"staticlib" => session::CrateTypeStaticlib,
"dylib" => session::CrateTypeDylib,
"bin" => session::CrateTypeExecutable,
- _ => early_error(demitter,
- format!("unknown crate type: `{}`", part))
+ _ => early_error(format!("unknown crate type: `{}`", part))
}
}).collect()
});
let lint_name = lint_name.replace("-", "_");
match lint_dict.find_equiv(&lint_name) {
None => {
- early_error(demitter, format!("unknown {} flag: {}",
- level_name, lint_name));
+ early_error(format!("unknown {} flag: {}",
+ level_name, lint_name));
}
Some(lint) => {
lint_opts.push((lint.lint, *level));
if *name == *debug_flag { this_bit = bit; break; }
}
if this_bit == 0 {
- early_error(demitter, format!("unknown debug flag: {}", *debug_flag))
+ early_error(format!("unknown debug flag: {}", *debug_flag))
}
debugging_opts |= this_bit;
}
"bc" => link::OutputTypeBitcode,
"obj" => link::OutputTypeObject,
"link" => link::OutputTypeExe,
- _ => early_error(demitter,
- format!("unknown emission type: `{}`",
- part))
+ _ => early_error(format!("unknown emission type: `{}`", part))
}
}).collect()
})
No
} else if matches.opt_present("O") {
if matches.opt_present("opt-level") {
- early_error(demitter, "-O and --opt-level both provided");
+ early_error("-O and --opt-level both provided");
}
Default
} else if matches.opt_present("opt-level") {
~"2" => Default,
~"3" => Aggressive,
_ => {
- early_error(demitter, "optimization level needs to be between 0-3")
+ early_error("optimization level needs to be between 0-3")
}
}
} else { No }
}).collect()
});
- let cfg = parse_cfgspecs(matches.opt_strs("cfg"), demitter);
+ let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
let test = matches.opt_present("test");
let android_cross_path = matches.opt_str("android-cross-path");
let write_dependency_info = (matches.opt_present("dep-info"),
}
pub fn build_session(sopts: @session::Options,
- local_crate_source_file: Option<Path>,
- demitter: @diagnostic::Emitter)
+ local_crate_source_file: Option<Path>)
-> Session {
let codemap = @codemap::CodeMap::new();
let diagnostic_handler =
- diagnostic::mk_handler(Some(demitter));
+ diagnostic::mk_handler();
let span_diagnostic_handler =
diagnostic::mk_span_handler(diagnostic_handler, codemap);
- build_session_(sopts, local_crate_source_file, codemap, demitter, span_diagnostic_handler)
+ build_session_(sopts, local_crate_source_file, codemap, span_diagnostic_handler)
}
pub fn build_session_(sopts: @session::Options,
local_crate_source_file: Option<Path>,
codemap: @codemap::CodeMap,
- demitter: @diagnostic::Emitter,
span_diagnostic_handler: @diagnostic::SpanHandler)
-> Session {
- let target_cfg = build_target_config(sopts, demitter);
+ let target_cfg = build_target_config(sopts);
let p_s = parse::new_parse_sess_special_handler(span_diagnostic_handler, codemap);
let cstore = @CStore::new(token::get_ident_interner());
let filesearch = @filesearch::FileSearch::new(
}
}
-pub fn early_error(emitter: &diagnostic::Emitter, msg: &str) -> ! {
- emitter.emit(None, msg, diagnostic::Fatal);
+pub fn early_error(msg: &str) -> ! {
+ diagnostic::DefaultEmitter.emit(None, msg, diagnostic::Fatal);
fail!(diagnostic::FatalError);
}
Ok(m) => m,
Err(f) => fail!("test_switch_implies_cfg_test: {}", f.to_err_msg())
};
- let sessopts = build_session_options(~"rustc", matches, @diagnostic::DefaultEmitter);
- let sess = build_session(sessopts, None, @diagnostic::DefaultEmitter);
+ let sessopts = build_session_options(~"rustc", matches);
+ let sess = build_session(sessopts, None);
let cfg = build_configuration(sess);
assert!((attr::contains_name(cfg, "test")));
}
f.to_err_msg());
}
};
- let sessopts = build_session_options(~"rustc", matches, @diagnostic::DefaultEmitter);
- let sess = build_session(sessopts, None, @diagnostic::DefaultEmitter);
+ let sessopts = build_session_options(~"rustc", matches);
+ let sess = build_session(sessopts, None);
let cfg = build_configuration(sess);
let mut test_items = cfg.iter().filter(|m| m.name().equiv(&("test")));
assert!(test_items.next().is_some());
}
}
-pub fn run_compiler(args: &[~str], demitter: @diagnostic::Emitter) {
+pub fn run_compiler(args: &[~str]) {
let mut args = args.to_owned();
let binary = args.shift().unwrap();
&match getopts::getopts(args, d::optgroups()) {
Ok(m) => m,
Err(f) => {
- d::early_error(demitter, f.to_err_msg());
+ d::early_error(f.to_err_msg());
}
};
return;
}
let (input, input_file_path) = match matches.free.len() {
- 0u => d::early_error(demitter, "no input filename given"),
+ 0u => d::early_error("no input filename given"),
1u => {
let ifile = matches.free[0].as_slice();
if ifile == "-" {
(d::FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
- _ => d::early_error(demitter, "multiple input filenames provided")
+ _ => d::early_error("multiple input filenames provided")
};
- let sopts = d::build_session_options(binary, matches, demitter);
- let sess = d::build_session(sopts, input_file_path, demitter);
+ let sopts = d::build_session_options(binary, matches);
+ let sess = d::build_session(sopts, input_file_path);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let cfg = d::build_configuration(sess);
&mut stdout as &mut io::Writer).unwrap();
}
d::StrInput(_) => {
- d::early_error(demitter, "can not list metadata for stdin");
+ d::early_error("can not list metadata for stdin");
}
}
return;
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
-pub fn monitor(f: proc(@diagnostic::Emitter)) {
+pub fn monitor(f: proc()) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
match task_builder.try(proc() {
io::stdio::set_stderr(~w as ~io::Writer);
- f(@diagnostic::DefaultEmitter)
+ f()
}) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
pub fn main_args(args: &[~str]) -> int {
let owned_args = args.to_owned();
- monitor(proc(demitter) run_compiler(owned_args, demitter));
+ monitor(proc() run_compiler(owned_args));
0
}
match explicit_self_kind as char {
's' => ast::SelfStatic,
'v' => ast::SelfValue,
- '@' => ast::SelfBox,
'~' => ast::SelfUniq,
// FIXME(#4846) expl. region
'&' => ast::SelfRegion(None, get_mutability(string[1])),
match explicit_self {
SelfStatic => { ebml_w.writer.write(&[ 's' as u8 ]); }
SelfValue => { ebml_w.writer.write(&[ 'v' as u8 ]); }
- SelfBox => { ebml_w.writer.write(&[ '@' as u8 ]); }
SelfUniq => { ebml_w.writer.write(&[ '~' as u8 ]); }
SelfRegion(_, m) => {
// FIXME(#4846) encode custom lifetime
fn parse_trait_store(st: &mut PState, conv: conv_did) -> ty::TraitStore {
match next(st) {
'~' => ty::UniqTraitStore,
- '@' => ty::BoxTraitStore,
'&' => ty::RegionTraitStore(parse_region(st, conv)),
c => st.tcx.sess.bug(format!("parse_trait_store(): bad input '{}'", c))
}
pub fn enc_trait_store(w: &mut MemWriter, cx: @ctxt, s: ty::TraitStore) {
match s {
ty::UniqTraitStore => mywrite!(w, "~"),
- ty::BoxTraitStore => mywrite!(w, "@"),
ty::RegionTraitStore(re) => {
mywrite!(w, "&");
enc_region(w, cx, re);
}
#[cfg(test)]
-type fake_session = @parse::ParseSess;
-
-#[cfg(test)]
-impl fake_ext_ctxt for fake_session {
+impl fake_ext_ctxt for @parse::ParseSess {
fn cfg(&self) -> ast::CrateConfig { ~[] }
fn parse_sess(&self) -> @parse::ParseSess { *self }
fn call_site(&self) -> Span {
}
#[cfg(test)]
-fn mk_ctxt() -> @fake_ext_ctxt {
- @parse::new_parse_sess(None) as @fake_ext_ctxt
+fn mk_ctxt() -> @parse::ParseSess {
+ parse::new_parse_sess()
}
#[cfg(test)]
}
ty::AutoObject(..) => {
- // FIXME: Handle @Trait to &Trait casts here?
+ // FIXME: Handle ~Trait to &Trait casts here?
}
}
}
debug!("Dataflow result:");
debug!("{}", {
- let this = @(*self).clone();
- this.pretty_print_to(~io::stderr() as ~io::Writer, blk).unwrap();
+ self.pretty_print_to(~io::stderr(), blk).unwrap();
""
});
}
- fn pretty_print_to(@self, wr: ~io::Writer,
+ fn pretty_print_to(&self, wr: ~io::Writer,
blk: &ast::Block) -> io::IoResult<()> {
let mut ps = pprust::rust_printer_annotated(wr, self.tcx.sess.intr(),
- self as @pprust::PpAnn);
+ self as &pprust::PpAnn);
if_ok!(pprust::cbox(&mut ps, pprust::indent_unit));
if_ok!(pprust::ibox(&mut ps, 0u));
if_ok!(pprust::print_block(&mut ps, blk));
}
fn ty_infer(&self, _span: Span) -> ty::t {
- let infcx: @infer::InferCtxt = infer::new_infer_ctxt(self.tcx);
- infcx.next_ty_var()
+ infer::new_infer_ctxt(self.tcx).next_ty_var()
}
}
fn check_unused_casts(cx: &Context, e: &ast::Expr) {
return match e.node {
ast::ExprCast(expr, ty) => {
- let infcx: @infer::InferCtxt = infer::new_infer_ctxt(cx.tcx);
- let t_t = ast_ty_to_ty(cx, &infcx, ty);
+ let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), ty);
if ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty {
cx.span_lint(UnnecessaryTypecast, ty.span,
"unnecessary type cast");
let mut n_uniq = 0;
ty::fold_ty(cx.tcx, ty, |t| {
match ty::get(t).sty {
- ty::ty_box(_) |
- ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
+ ty::ty_box(_) => {
n_box += 1;
}
ty::ty_uniq(_) | ty::ty_str(ty::vstore_uniq) |
Some(deref_ptr(region_ptr(ast::MutImmutable, r)))
}
- ty::ty_box(_) |
- ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
+ ty::ty_box(_) => {
Some(deref_ptr(gc_ptr))
}
}
impl cmt_ {
- pub fn guarantor(@self) -> cmt {
+ pub fn guarantor(self) -> cmt {
//! Returns `self` after stripping away any owned pointer derefs or
//! interior content. The return value is basically the `cmt` which
//! determines how long the value in `self` remains live.
cat_deref(_, _, unsafe_ptr(..)) |
cat_deref(_, _, gc_ptr) |
cat_deref(_, _, region_ptr(..)) => {
- self
+ @self
}
cat_downcast(b) |
cat_stack_upvar(b) |
}
}
-pub fn B(cx: &Block) -> Builder {
+pub fn B<'a>(cx: &'a Block) -> Builder<'a> {
let b = cx.fcx.ccx.builder();
b.position_at_end(cx.llbb);
b
use syntax::codemap::Span;
use std::ptr::is_not_null;
-pub struct Builder {
+pub struct Builder<'a> {
llbuilder: BuilderRef,
- ccx: @CrateContext,
+ ccx: &'a CrateContext,
}
// This is a really awful way to get a zero-length c-string, but better (and a
}
}
-impl Builder {
- pub fn new(ccx: @CrateContext) -> Builder {
+impl<'a> Builder<'a> {
+ pub fn new(ccx: &'a CrateContext) -> Builder<'a> {
Builder {
llbuilder: ccx.builder.B,
ccx: ccx,
}
}
- pub fn builder(@self) -> Builder {
+ pub fn builder<'a>(&'a self) -> Builder<'a> {
Builder::new(self)
}
return ptr_metadata;
}
-trait MemberDescriptionFactory {
+enum MemberDescriptionFactory {
+ StructMD(StructMemberDescriptionFactory),
+ TupleMD(TupleMemberDescriptionFactory),
+ GeneralMD(GeneralMemberDescriptionFactory),
+ EnumVariantMD(EnumVariantMemberDescriptionFactory)
+}
+
+impl MemberDescriptionFactory {
fn create_member_descriptions(&self, cx: &CrateContext)
- -> ~[MemberDescription];
+ -> ~[MemberDescription] {
+ match *self {
+ StructMD(ref this) => {
+ this.create_member_descriptions(cx)
+ }
+ TupleMD(ref this) => {
+ this.create_member_descriptions(cx)
+ }
+ GeneralMD(ref this) => {
+ this.create_member_descriptions(cx)
+ }
+ EnumVariantMD(ref this) => {
+ this.create_member_descriptions(cx)
+ }
+ }
+ }
}
struct StructMemberDescriptionFactory {
span: Span,
}
-impl MemberDescriptionFactory for StructMemberDescriptionFactory {
+impl StructMemberDescriptionFactory {
fn create_member_descriptions(&self, cx: &CrateContext)
-> ~[MemberDescription] {
self.fields.map(|field| {
metadata_stub: struct_metadata_stub,
llvm_type: struct_llvm_type,
file_metadata: file_metadata,
- member_description_factory: @StructMemberDescriptionFactory {
+ member_description_factory: StructMD(StructMemberDescriptionFactory {
fields: fields,
span: span,
- } as @MemberDescriptionFactory,
+ }),
}
}
metadata_stub: DICompositeType,
llvm_type: Type,
file_metadata: DIFile,
- member_description_factory: @MemberDescriptionFactory,
+ member_description_factory: MemberDescriptionFactory,
},
FinalMetadata(DICompositeType)
}
metadata_stub,
llvm_type,
file_metadata,
- member_description_factory
+ ref member_description_factory
} => {
// Insert the stub into the cache in order to allow recursive references ...
{
span: Span,
}
-impl MemberDescriptionFactory for TupleMemberDescriptionFactory {
+impl TupleMemberDescriptionFactory {
fn create_member_descriptions(&self, cx: &CrateContext)
-> ~[MemberDescription] {
self.component_types.map(|&component_type| {
span),
llvm_type: tuple_llvm_type,
file_metadata: file_metadata,
- member_description_factory: @TupleMemberDescriptionFactory {
+ member_description_factory: TupleMD(TupleMemberDescriptionFactory {
component_types: component_types.to_owned(),
span: span,
- } as @MemberDescriptionFactory
+ })
}
}
span: Span,
}
-impl MemberDescriptionFactory for GeneralMemberDescriptionFactory {
+impl GeneralMemberDescriptionFactory {
fn create_member_descriptions(&self, cx: &CrateContext)
-> ~[MemberDescription] {
// Capture type_rep, so we don't have to copy the struct_defs array
span: Span,
}
-impl MemberDescriptionFactory for EnumVariantMemberDescriptionFactory {
+impl EnumVariantMemberDescriptionFactory {
fn create_member_descriptions(&self, cx: &CrateContext)
-> ~[MemberDescription] {
self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
containing_scope: DIScope,
file_metadata: DIFile,
span: Span)
- -> (DICompositeType, Type, @MemberDescriptionFactory) {
+ -> (DICompositeType, Type, MemberDescriptionFactory) {
let variant_info_string = token::get_ident(variant_info.name.name);
let variant_name = variant_info_string.get();
let variant_llvm_type = Type::struct_(struct_def.fields.map(|&t| type_of::type_of(cx, t)),
.collect();
let member_description_factory =
- @EnumVariantMemberDescriptionFactory {
+ EnumVariantMD(EnumVariantMemberDescriptionFactory {
args: args,
discriminant_type_metadata: discriminant_type_metadata,
span: span,
- } as @MemberDescriptionFactory;
+ });
(metadata_stub, variant_llvm_type, member_description_factory)
}
metadata_stub: enum_metadata,
llvm_type: enum_llvm_type,
file_metadata: file_metadata,
- member_description_factory: @GeneralMemberDescriptionFactory {
+ member_description_factory: GeneralMD(GeneralMemberDescriptionFactory {
type_rep: type_rep,
variants: variants,
discriminant_type_metadata: discriminant_type_metadata,
containing_scope: containing_scope,
file_metadata: file_metadata,
span: span,
- } as @MemberDescriptionFactory,
+ }),
}
}
adt::NullablePointer { nonnull: ref struct_def, nndiscr, .. } => {
unpack_datum!(bcx, auto_borrow_fn(bcx, adjusted_ty, datum))
}
Some(AutoBorrowObj(..)) => {
- unpack_datum!(bcx, auto_borrow_obj(
- bcx, adj.autoderefs, expr, datum))
+ unpack_datum!(bcx, auto_borrow_obj(bcx, expr, datum))
}
};
}
auto_ref(bcx, datum, expr)
}
- fn auto_borrow_obj<'a>(
- mut bcx: &'a Block<'a>,
- autoderefs: uint,
- expr: &ast::Expr,
- source_datum: Datum<Expr>)
- -> DatumBlock<'a, Expr> {
+ fn auto_borrow_obj<'a>(bcx: &'a Block<'a>,
+ expr: &ast::Expr,
+ source_datum: Datum<Expr>)
+ -> DatumBlock<'a, Expr> {
let tcx = bcx.tcx();
let target_obj_ty = expr_ty_adjusted(bcx, expr);
- debug!("auto_borrow_obj(target={})",
- target_obj_ty.repr(tcx));
-
- // Extract source store information
- let (source_store, source_mutbl) = match ty::get(source_datum.ty).sty {
- ty::ty_trait(_, _, s, m, _) => (s, m),
- _ => {
- bcx.sess().span_bug(
- expr.span,
- format!("auto_borrow_trait_obj expected a trait, found {}",
- source_datum.ty.repr(bcx.tcx())));
- }
- };
-
- // check if any borrowing is really needed or we could reuse
- // the source_datum instead
- match ty::get(target_obj_ty).sty {
- ty::ty_trait(_, _, ty::RegionTraitStore(target_scope), target_mutbl, _) => {
- if target_mutbl == ast::MutImmutable && target_mutbl == source_mutbl {
- match source_store {
- ty::RegionTraitStore(source_scope) => {
- if tcx.region_maps.is_subregion_of(target_scope, source_scope) {
- return DatumBlock { bcx: bcx, datum: source_datum };
- }
- },
- _ => {}
+ debug!("auto_borrow_obj(target={})", target_obj_ty.repr(tcx));
- };
- }
- },
- _ => {}
- }
-
- let scratch = rvalue_scratch_datum(bcx, target_obj_ty,
- "__auto_borrow_obj");
-
- // Convert a @Object, ~Object, or &Object pair into an &Object pair.
-
- // Get a pointer to the source object, which is represented as
- // a (vtable, data) pair.
- let source_datum = unpack_datum!(
- bcx, source_datum.to_lvalue_datum(bcx, "auto_borrow_obj", expr.id));
- let source_llval = source_datum.to_llref();
-
- // Set the vtable field of the new pair
- let vtable_ptr = GEPi(bcx, source_llval, [0u, abi::trt_field_vtable]);
- let vtable = Load(bcx, vtable_ptr);
- Store(bcx, vtable, GEPi(bcx, scratch.val, [0u, abi::trt_field_vtable]));
-
- // Load the data for the source, which is either an @T,
- // ~T, or &T, depending on source_obj_ty.
- let source_data_ptr = GEPi(bcx, source_llval, [0u, abi::trt_field_box]);
- let target_data = match source_store {
- ty::BoxTraitStore(..) => {
- // For deref of @T, create a dummy datum and use the
- // datum's deref method. This is more work than just
- // calling GEPi ourselves, but it ensures that any
- // necessary rooting is performed. Note that we don't
- // know the type T, so just substitute `i8`-- it
- // doesn't really matter for our purposes right now.
- let source_ty = ty::mk_box(tcx, ty::mk_i8());
- let source_datum = Datum(source_data_ptr, source_ty, LvalueExpr);
- let derefd_datum = unpack_datum!(
- bcx, deref_once(bcx, expr, source_datum, autoderefs));
- derefd_datum.assert_lvalue(bcx).to_llref()
- }
- ty::UniqTraitStore(..) | ty::RegionTraitStore(..) => {
- Load(bcx, source_data_ptr)
- }
- };
- Store(bcx, target_data,
- GEPi(bcx, scratch.val, [0u, abi::trt_field_box]));
-
- DatumBlock(bcx, scratch.to_expr_datum())
+ let mut datum = source_datum.to_expr_datum();
+ datum.ty = target_obj_ty;
+ DatumBlock(bcx, datum)
}
}
let _icx = push_ctxt("take_ty");
match ty::get(t).sty {
ty::ty_box(_) => incr_refcnt_of_boxed(bcx, v),
- ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
- incr_refcnt_of_boxed(bcx, GEPi(bcx, v, [0u, abi::trt_field_box]))
- }
_ if ty::type_is_structural(t)
&& ty::type_needs_drop(bcx.tcx(), t) => {
iter_structural_ty(bcx, v, t, take_ty)
let ccx = bcx.ccx();
match ty::get(t).sty {
ty::ty_box(body_ty) => {
- decr_refcnt_maybe_free(bcx, v0, Some(body_ty))
+ decr_refcnt_maybe_free(bcx, v0, body_ty)
}
ty::ty_uniq(content_ty) => {
let llbox = Load(bcx, v0);
}
}
}
- ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
- let llbox_ptr = GEPi(bcx, v0, [0u, abi::trt_field_box]);
- decr_refcnt_maybe_free(bcx, llbox_ptr, None)
- }
ty::ty_trait(_, _, ty::UniqTraitStore, _, _) => {
let lluniquevalue = GEPi(bcx, v0, [0, abi::trt_field_box]);
// Only drop the value when it is non-null
}
}
-fn decr_refcnt_maybe_free<'a>(bcx: &'a Block<'a>, box_ptr_ptr: ValueRef,
- t: Option<ty::t>) -> &'a Block<'a> {
+fn decr_refcnt_maybe_free<'a>(bcx: &'a Block<'a>,
+ box_ptr_ptr: ValueRef,
+ t: ty::t) -> &'a Block<'a> {
let _icx = push_ctxt("decr_refcnt_maybe_free");
let fcx = bcx.fcx;
let ccx = bcx.ccx();
let v = Load(free_bcx, box_ptr_ptr);
let body = GEPi(free_bcx, v, [0u, abi::box_field_body]);
- let free_bcx = match t {
- Some(t) => drop_ty(free_bcx, body, t),
- None => {
- // Generate code that, dynamically, indexes into the
- // tydesc and calls the drop glue that got set dynamically
- let td = Load(free_bcx, GEPi(free_bcx, v, [0u, abi::box_field_tydesc]));
- call_tydesc_glue_full(free_bcx, body, td, abi::tydesc_field_drop_glue, None);
- free_bcx
- }
- };
+ let free_bcx = drop_ty(free_bcx, body, t);
let free_bcx = trans_free(free_bcx, v);
Br(free_bcx, next_bcx.llbb);
-> Callee<'a> {
/*!
* Create a method callee where the method is coming from a trait
- * object (e.g., @Trait type). In this case, we must pull the fn
+ * object (e.g., ~Trait type). In this case, we must pull the fn
* pointer out of the vtable that is packaged up with the object.
* Objects are represented as a pair, so we first evaluate the self
* expression and then extract the self data and vtable out of the
use lib::llvm::{llvm, TypeRef, Bool, False, True, TypeKind};
use lib::llvm::{Float, Double, X86_FP80, PPC_FP128, FP128};
-use middle::ty;
-
use middle::trans::context::CrateContext;
use middle::trans::base;
], false)
}
- pub fn opaque_trait(ctx: &CrateContext, store: ty::TraitStore) -> Type {
+ pub fn opaque_trait() -> Type {
let vtable = Type::glue_fn(Type::i8p()).ptr_to().ptr_to();
- let box_ty = match store {
- ty::BoxTraitStore => Type::at_box(ctx, Type::i8()),
- ty::UniqTraitStore => Type::i8(),
- ty::RegionTraitStore(..) => Type::i8()
- };
- Type::struct_([vtable, box_ty.ptr_to()], false)
+ Type::struct_([vtable, Type::i8p()], false)
}
pub fn kind(&self) -> TypeKind {
ty::ty_bare_fn(..) => Type::i8p(),
ty::ty_closure(..) => Type::struct_([Type::i8p(), Type::i8p()], false),
- ty::ty_trait(_, _, store, _, _) => Type::opaque_trait(cx, store),
+ ty::ty_trait(..) => Type::opaque_trait(),
ty::ty_str(ty::vstore_fixed(size)) => Type::array(&Type::i8(), size as u64),
ty::ty_vec(mt, ty::vstore_fixed(size)) => {
let fn_ty = type_of_fn_from_ty(cx, t).ptr_to();
Type::struct_([fn_ty, Type::i8p()], false)
}
- ty::ty_trait(_, _, store, _, _) => Type::opaque_trait(cx, store),
+ ty::ty_trait(..) => Type::opaque_trait(),
ty::ty_type => cx.tydesc_type.ptr_to(),
ty::ty_tup(..) => {
let repr = adt::represent_type(cx, t);
#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
pub enum TraitStore {
- BoxTraitStore, // @Trait
UniqTraitStore, // ~Trait
RegionTraitStore(Region), // &Trait
}
/// Convert from T to *T
AutoUnsafe(ast::Mutability),
- /// Convert from @Trait/~Trait/&Trait to &Trait
+ /// Convert from ~Trait/&Trait to &Trait
AutoBorrowObj(Region, ast::Mutability),
}
let st = match cty.sigil {
ast::BorrowedSigil =>
object_contents(cx, RegionTraitStore(cty.region), MutMutable, cty.bounds),
- ast::ManagedSigil =>
- object_contents(cx, BoxTraitStore, MutImmutable, cty.bounds),
ast::OwnedSigil =>
object_contents(cx, UniqTraitStore, MutImmutable, cty.bounds),
+ ast::ManagedSigil => unreachable!()
};
// FIXME(#3569): This borrowed_contents call should be taken care of in
UniqTraitStore => {
contents.owned_pointer()
}
- BoxTraitStore => {
- contents.managed_pointer()
- }
RegionTraitStore(r) => {
contents.reference(borrowed_contents(r, mutbl))
}
let trait_store = match *sigil {
BorrowedSigil => RegionTraitStore(region.expect("expected valid region")),
OwnedSigil => UniqTraitStore,
- ManagedSigil => BoxTraitStore
+ ManagedSigil => unreachable!()
};
mk_trait(cx, def_id, substs.clone(), trait_store, m, bounds)
hash.input([17]);
did(&mut hash, d);
match store {
- BoxTraitStore => hash.input([0]),
- UniqTraitStore => hash.input([1]),
+ UniqTraitStore => hash.input([0]),
RegionTraitStore(r) => {
- hash.input([2]);
+ hash.input([1]);
region(&mut hash, r);
}
}
-> ty::TraitStore {
match trait_store {
ty::UniqTraitStore => ty::UniqTraitStore,
- ty::BoxTraitStore => ty::BoxTraitStore,
ty::RegionTraitStore(r) => ty::RegionTraitStore(this.fold_region(r)),
}
}
}
}
- // Handle @, ~, and & being able to mean strs and vecs.
+ // Handle ~, and & being able to mean strs and vecs.
// If a_seq_ty is a str or a vec, make it a str/vec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,
let result = ast_path_to_trait_ref(
this, rscope, trait_def_id, None, path);
let trait_store = match ptr_ty {
- Box => ty::BoxTraitStore,
VStore(ty::vstore_uniq) => ty::UniqTraitStore,
VStore(ty::vstore_slice(r)) => {
ty::RegionTraitStore(r)
}
- VStore(ty::vstore_fixed(..)) => {
+ _ => {
tcx.sess.span_err(
path.span,
- "@trait, ~trait or &trait are the only supported \
+ "~trait or &trait are the only supported \
forms of casting-to-trait");
- ty::BoxTraitStore
+ return ty::mk_err();
}
};
let bounds = conv_builtin_bounds(this.tcx(), bounds, trait_store);
// if none were specified.
ast::BorrowedSigil => ty::RegionTraitStore(ty::ReEmpty), // dummy region
ast::OwnedSigil => ty::UniqTraitStore,
- ast::ManagedSigil => ty::BoxTraitStore,
+ ast::ManagedSigil => return ty::mk_err()
});
let fn_decl = ty_of_closure(this,
rscope,
ty::mt {ty: self_info.untransformed_self_ty,
mutbl: mutability}))
}
- ast::SelfBox => {
- Some(ty::mk_box(this.tcx(), self_info.untransformed_self_ty))
- }
ast::SelfUniq => {
Some(ty::mk_uniq(this.tcx(), self_info.untransformed_self_ty))
}
(&None, ty::UniqTraitStore) => {
let mut set = ty::EmptyBuiltinBounds(); set.add(ty::BoundSend); set
}
- // @Trait is sugar for @Trait:'static.
// &'static Trait is sugar for &'static Trait:'static.
- (&None, ty::BoxTraitStore) |
(&None, ty::RegionTraitStore(ty::ReStatic)) => {
let mut set = ty::EmptyBuiltinBounds(); set.add(ty::BoundStatic); set
}
proceed by progressively deref'ing the receiver type, after all. The
answer is that two phases are needed to elegantly deal with explicit
self. After all, if there is an impl for the type `Foo`, it can
-define a method with the type `@self`, which means that it expects a
-receiver of type `@Foo`. If we have a receiver of type `@Foo`, but we
-waited to search for that impl until we have deref'd the `@` away and
+define a method with the type `~self`, which means that it expects a
+receiver of type `~Foo`. If we have a receiver of type `~Foo`, but we
+waited to search for that impl until we have deref'd the `~` away and
obtained the type `Foo`, we would never match this method.
*/
use std::hashmap::HashSet;
use std::result;
use std::vec;
-use syntax::ast::{DefId, SelfValue, SelfRegion, SelfBox};
+use syntax::ast::{DefId, SelfValue, SelfRegion};
use syntax::ast::{SelfUniq, SelfStatic, NodeId};
use syntax::ast::{MutMutable, MutImmutable};
use syntax::ast;
/// considered to "match" a given method candidate. Typically the test
/// is whether the receiver is of a particular type. However, this
/// type is the type of the receiver *after accounting for the
-/// method's self type* (e.g., if the method is an `@self` method, we
-/// have *already verified* that the receiver is of some type `@T` and
+/// method's self type* (e.g., if the method is an `~self` method, we
+/// have *already verified* that the receiver is of some type `~T` and
/// now we must check that the type `T` is correct). Unfortunately,
/// because traits are not types, this is a pain to do.
#[deriving(Clone)]
ast::SelfValue => {
ty::mk_err() // error reported in `enforce_object_limitations()`
}
- ast::SelfRegion(..) | ast::SelfBox | ast::SelfUniq => {
+ ast::SelfRegion(..) | ast::SelfUniq => {
let transformed_self_ty = method_ty.fty.sig.inputs[0];
match ty::get(transformed_self_ty).sty {
ty::ty_rptr(r, mt) => { // must be SelfRegion
substs, RegionTraitStore(r), mt.mutbl,
ty::EmptyBuiltinBounds())
}
- ty::ty_box(_) => { // must be SelfBox
- ty::mk_trait(self.tcx(), trait_def_id,
- substs, BoxTraitStore, ast::MutImmutable,
- ty::EmptyBuiltinBounds())
- }
ty::ty_uniq(_) => { // must be SelfUniq
ty::mk_trait(self.tcx(), trait_def_id,
substs, UniqTraitStore, ast::MutImmutable,
through an object");
}
- ast::SelfRegion(..) | ast::SelfBox | ast::SelfUniq => {}
+ ast::SelfRegion(..) | ast::SelfUniq => {}
}
// reason (a) above
}
}
- SelfBox => {
- debug!("(is relevant?) explicit self is a box");
- match ty::get(rcvr_ty).sty {
- ty::ty_box(typ) => {
- rcvr_matches_ty(self.fcx, typ, candidate)
- }
-
- ty::ty_trait(self_did, _, BoxTraitStore, ast::MutImmutable, _) => {
- rcvr_matches_object(self_did, candidate)
- }
-
- _ => false
- }
- }
-
SelfUniq => {
debug!("(is relevant?) explicit self is a unique pointer");
match ty::get(rcvr_ty).sty {
ty::item_path_str(self.tcx(), did)));
}
- fn infcx(&self) -> @infer::InferCtxt {
- self.fcx.inh.infcx
+ fn infcx(&'a self) -> &'a infer::InferCtxt {
+ &self.fcx.inh.infcx
}
fn tcx(&self) -> ty::ctxt {
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited {
- infcx: @infer::InferCtxt,
+ infcx: infer::InferCtxt,
locals: @RefCell<HashMap<ast::NodeId, ty::t>>,
param_env: ty::ParameterEnvironment,
};
debug!("trait_fty (post-subst): {}", trait_fty.repr(tcx));
- match infer::mk_subty(infcx, false, infer::MethodCompatCheck(impl_m_span),
+ match infer::mk_subty(&infcx, false, infer::MethodCompatCheck(impl_m_span),
impl_fty, trait_fty) {
result::Ok(()) => {}
result::Err(ref terr) => {
}
impl FnCtxt {
- pub fn infcx(&self) -> @infer::InferCtxt {
- self.inh.infcx
+ pub fn infcx<'a>(&'a self) -> &'a infer::InferCtxt {
+ &self.inh.infcx
}
pub fn err_count_since_creation(&self) -> uint {
}
}
-impl RegionScope for @infer::InferCtxt {
- fn anon_regions(&self,
- span: Span,
- count: uint) -> Result<~[ty::Region], ()> {
- Ok(vec::from_fn(
- count,
- |_| self.next_region_var(infer::MiscVariable(span))))
+impl RegionScope for infer::InferCtxt {
+ fn anon_regions(&self, span: Span, count: uint)
+ -> Result<~[ty::Region], ()> {
+ Ok(vec::from_fn(count, |_| {
+ self.next_region_var(infer::MiscVariable(span))
+ }))
}
}
}
pub fn to_ty(&self, ast_t: &ast::Ty) -> ty::t {
- ast_ty_to_ty(self, &self.infcx(), ast_t)
+ ast_ty_to_ty(self, self.infcx(), ast_t)
}
pub fn pat_to_str(&self, pat: &ast::Pat) -> ~str {
// construct the function type
let fn_ty = astconv::ty_of_closure(fcx,
- &fcx.infcx(),
+ fcx.infcx(),
expr.id,
sigil,
purity,
ty::ty_vec(_, ty::vstore_uniq) => {
OwnedPointer
}
- ty::ty_box(..) |
- ty::ty_ptr(..) |
- ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
+ ty::ty_box(..) | ty::ty_ptr(..) => {
OtherPointer
}
ty::ty_closure(ref closure_ty) => {
/// A vtable context includes an inference context, a crate context, and a
/// callback function to call in case of type error.
pub struct VtableContext<'a> {
- infcx: @infer::InferCtxt,
+ infcx: &'a infer::InferCtxt,
param_env: &'a ty::ParameterEnvironment,
}
// Look up vtables for the type we're casting to,
// passing in the source and target type. The source
// must be a pointer type suitable to the object sigil,
- // e.g.: `@x as @Trait`, `&x as &Trait` or `~x as ~Trait`
+ // e.g.: `&x as &Trait` or `~x as ~Trait`
let ty = structurally_resolved_type(fcx, ex.span,
fcx.expr_ty(src));
match (&ty::get(ty).sty, store) {
- (&ty::ty_box(..), ty::BoxTraitStore) |
(&ty::ty_uniq(..), ty::UniqTraitStore)
if !mutability_allowed(ast::MutImmutable,
target_mutbl) => {
format!("types differ in mutability"));
}
- (&ty::ty_box(..), ty::BoxTraitStore) |
(&ty::ty_uniq(..), ty::UniqTraitStore) |
(&ty::ty_rptr(..), ty::RegionTraitStore(..)) => {
let typ = match &ty::get(ty).sty {
ty::ty_sort_str(fcx.tcx(), ty)));
}
- (_, ty::BoxTraitStore) => {
- fcx.ccx.tcx.sess.span_err(
- ex.span,
- format!("can only cast an @-pointer \
- to an @-object, not a {}",
- ty::ty_sort_str(fcx.tcx(), ty)));
- }
-
(_, ty::RegionTraitStore(_)) => {
fcx.ccx.tcx.sess.span_err(
ex.span,
let impl_trait_ref = @impl_trait_ref.subst(ccx.tcx, ¶m_env.free_substs);
- let infcx = infer::new_infer_ctxt(ccx.tcx);
+ let infcx = &infer::new_infer_ctxt(ccx.tcx);
let vcx = VtableContext { infcx: infcx, param_env: ¶m_env };
let loc_info = location_info_for_item(impl_item);
use std::rc::Rc;
use std::vec;
-pub struct UniversalQuantificationResult {
+struct UniversalQuantificationResult {
monotype: t,
type_variables: ~[ty::t],
type_param_defs: Rc<~[ty::TypeParameterDef]>
}
-pub fn get_base_type(inference_context: @InferCtxt,
- span: Span,
- original_type: t)
- -> Option<t> {
+fn get_base_type(inference_context: &InferCtxt,
+ span: Span,
+ original_type: t)
+ -> Option<t> {
let resolved_type;
match resolve_type(inference_context,
original_type,
}
}
-pub fn type_is_defined_in_local_crate(original_type: t) -> bool {
+fn type_is_defined_in_local_crate(original_type: t) -> bool {
/*!
*
* For coherence, when we have `impl Trait for Type`, we need to
}
// Returns the def ID of the base type, if there is one.
-pub fn get_base_type_def_id(inference_context: @InferCtxt,
- span: Span,
- original_type: t)
- -> Option<DefId> {
+fn get_base_type_def_id(inference_context: &InferCtxt,
+ span: Span,
+ original_type: t)
+ -> Option<DefId> {
match get_base_type(inference_context, span, original_type) {
None => {
return None;
}
}
-pub fn CoherenceChecker(crate_context: @CrateCtxt) -> CoherenceChecker {
- CoherenceChecker {
- crate_context: crate_context,
- inference_context: new_infer_ctxt(crate_context.tcx),
- }
-}
-
-pub struct CoherenceChecker {
+struct CoherenceChecker {
crate_context: @CrateCtxt,
- inference_context: @InferCtxt,
+ inference_context: InferCtxt,
}
-struct CoherenceCheckVisitor { cc: CoherenceChecker }
+struct CoherenceCheckVisitor<'a> {
+ cc: &'a CoherenceChecker
+}
-impl visit::Visitor<()> for CoherenceCheckVisitor {
+impl<'a> visit::Visitor<()> for CoherenceCheckVisitor<'a> {
fn visit_item(&mut self, item: &Item, _: ()) {
// debug!("(checking coherence) item '{}'",
}
}
-struct PrivilegedScopeVisitor { cc: CoherenceChecker }
+struct PrivilegedScopeVisitor<'a> { cc: &'a CoherenceChecker }
-impl visit::Visitor<()> for PrivilegedScopeVisitor {
+impl<'a> visit::Visitor<()> for PrivilegedScopeVisitor<'a> {
fn visit_item(&mut self, item: &Item, _: ()) {
match item.node {
}
impl CoherenceChecker {
- pub fn check_coherence(self, crate: &Crate) {
+ fn new(crate_context: @CrateCtxt) -> CoherenceChecker {
+ CoherenceChecker {
+ crate_context: crate_context,
+ inference_context: new_infer_ctxt(crate_context.tcx),
+ }
+ }
+
+ fn check(&self, crate: &Crate) {
// Check implementations and traits. This populates the tables
// containing the inherent methods and extension methods. It also
// builds up the trait inheritance table.
-
let mut visitor = CoherenceCheckVisitor { cc: self };
visit::walk_crate(&mut visitor, crate, ());
self.populate_destructor_table();
}
- pub fn check_implementation(&self,
- item: &Item,
- associated_traits: &[TraitRef]) {
+ fn check_implementation(&self, item: &Item,
+ associated_traits: &[TraitRef]) {
let tcx = self.crate_context.tcx;
let self_type = ty::lookup_item_type(tcx, local_def(item.id));
'{}'",
self.crate_context.tcx.sess.str_of(item.ident));
- match get_base_type_def_id(self.inference_context,
+ match get_base_type_def_id(&self.inference_context,
item.span,
self_type.ty) {
None => {
// Add the implementation to the mapping from implementation to base
// type def ID, if there is a base type for this implementation and
// the implementation does not have any associated traits.
- match get_base_type_def_id(self.inference_context,
+ match get_base_type_def_id(&self.inference_context,
item.span,
self_type.ty) {
None => {
// Creates default method IDs and performs type substitutions for an impl
// and trait pair. Then, for each provided method in the trait, inserts a
// `ProvidedMethodInfo` instance into the `provided_method_sources` map.
- pub fn instantiate_default_methods(&self,
- impl_id: ast::DefId,
- trait_ref: &ty::TraitRef,
- all_methods: &mut ~[@Method]) {
+ fn instantiate_default_methods(&self, impl_id: ast::DefId,
+ trait_ref: &ty::TraitRef,
+ all_methods: &mut ~[@Method]) {
let tcx = self.crate_context.tcx;
debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})",
impl_id, trait_ref.repr(tcx));
}
}
- pub fn add_inherent_impl(&self,
- base_def_id: DefId,
- implementation: @Impl) {
+ fn add_inherent_impl(&self, base_def_id: DefId,
+ implementation: @Impl) {
let tcx = self.crate_context.tcx;
let implementation_list;
let mut inherent_impls = tcx.inherent_impls.borrow_mut();
implementation_list.get().push(implementation);
}
- pub fn add_trait_impl(&self,
- base_def_id: DefId,
- implementation: @Impl) {
+ fn add_trait_impl(&self, base_def_id: DefId,
+ implementation: @Impl) {
let tcx = self.crate_context.tcx;
let implementation_list;
let mut trait_impls = tcx.trait_impls.borrow_mut();
implementation_list.get().push(implementation);
}
- pub fn check_implementation_coherence(&self) {
+ fn check_implementation_coherence(&self) {
let trait_impls = self.crate_context.tcx.trait_impls.borrow();
for &trait_id in trait_impls.get().keys() {
self.check_implementation_coherence_of(trait_id);
}
}
- pub fn check_implementation_coherence_of(&self, trait_def_id: DefId) {
+ fn check_implementation_coherence_of(&self, trait_def_id: DefId) {
// Unify pairs of polytypes.
self.iter_impls_of_trait_local(trait_def_id, |a| {
let implementation_a = a;
})
}
- pub fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |@Impl|) {
+ fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |@Impl|) {
self.iter_impls_of_trait_local(trait_def_id, |x| f(x));
if trait_def_id.crate == LOCAL_CRATE {
});
}
- pub fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |@Impl|) {
+ fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |@Impl|) {
let trait_impls = self.crate_context.tcx.trait_impls.borrow();
match trait_impls.get().find(&trait_def_id) {
Some(impls) => {
}
}
- pub fn polytypes_unify(&self,
- polytype_a: ty_param_bounds_and_ty,
- polytype_b: ty_param_bounds_and_ty)
- -> bool {
+ fn polytypes_unify(&self,
+ polytype_a: ty_param_bounds_and_ty,
+ polytype_b: ty_param_bounds_and_ty)
+ -> bool {
let universally_quantified_a =
self.universally_quantify_polytype(polytype_a);
let universally_quantified_b =
// Converts a polytype to a monotype by replacing all parameters with
// type variables. Returns the monotype and the type variables created.
- pub fn universally_quantify_polytype(&self,
- polytype: ty_param_bounds_and_ty)
- -> UniversalQuantificationResult {
+ fn universally_quantify_polytype(&self, polytype: ty_param_bounds_and_ty)
+ -> UniversalQuantificationResult {
let region_parameter_count = polytype.generics.region_param_defs().len();
let region_parameters =
self.inference_context.next_region_vars(
}
}
- pub fn can_unify_universally_quantified<'a>(&self,
- a: &'a
- UniversalQuantificationResult,
- b: &'a
- UniversalQuantificationResult)
- -> bool {
- infer::can_mk_subty(self.inference_context,
+ fn can_unify_universally_quantified<'a>(&self,
+ a: &'a UniversalQuantificationResult,
+ b: &'a UniversalQuantificationResult)
+ -> bool {
+ infer::can_mk_subty(&self.inference_context,
a.monotype,
b.monotype).is_ok()
}
- pub fn get_self_type_for_implementation(&self, implementation: @Impl)
- -> ty_param_bounds_and_ty {
+ fn get_self_type_for_implementation(&self, implementation: @Impl)
+ -> ty_param_bounds_and_ty {
let tcache = self.crate_context.tcx.tcache.borrow();
return tcache.get().get_copy(&implementation.did);
}
// Privileged scope checking
- pub fn check_privileged_scopes(self, crate: &Crate) {
- let mut visitor = PrivilegedScopeVisitor{ cc: self };
+ fn check_privileged_scopes(&self, crate: &Crate) {
+ let mut visitor = PrivilegedScopeVisitor { cc: self };
visit::walk_crate(&mut visitor, crate, ());
}
- pub fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId {
+ fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId {
let def_map = self.crate_context.tcx.def_map;
let def_map = def_map.borrow();
let trait_def = def_map.get().get_copy(&trait_ref.ref_id);
/// For coherence, when we have `impl Type`, we need to guarantee that
/// `Type` is "local" to the crate. For our purposes, this means that it
/// must precisely name some nominal type defined in this crate.
- pub fn ast_type_is_defined_in_local_crate(&self, original_type: &ast::Ty)
- -> bool {
+ fn ast_type_is_defined_in_local_crate(&self, original_type: &ast::Ty) -> bool {
match original_type.node {
TyPath(_, _, path_id) => {
let def_map = self.crate_context.tcx.def_map.borrow();
}
// Converts an implementation in the AST to an Impl structure.
- pub fn create_impl_from_item(&self, item: &Item) -> @Impl {
+ fn create_impl_from_item(&self, item: &Item) -> @Impl {
let tcx = self.crate_context.tcx;
match item.node {
ItemImpl(_, ref trait_refs, _, ref ast_methods) => {
}
}
- pub fn span_of_impl(&self, implementation: @Impl) -> Span {
+ fn span_of_impl(&self, implementation: @Impl) -> Span {
assert_eq!(implementation.did.crate, LOCAL_CRATE);
match self.crate_context.tcx.items.find(implementation.did.node) {
Some(NodeItem(item, _)) => {
// External crate handling
- pub fn add_external_impl(&self,
- impls_seen: &mut HashSet<DefId>,
- impl_def_id: DefId) {
+ fn add_external_impl(&self,
+ impls_seen: &mut HashSet<DefId>,
+ impl_def_id: DefId) {
let tcx = self.crate_context.tcx;
let implementation = @csearch::get_impl(tcx, impl_def_id);
// Adds implementations and traits from external crates to the coherence
// info.
- pub fn add_external_crates(&self) {
+ fn add_external_crates(&self) {
let mut impls_seen = HashSet::new();
let crate_store = self.crate_context.tcx.sess.cstore;
// Destructors
//
- pub fn populate_destructor_table(&self) {
+ fn populate_destructor_table(&self) {
let tcx = self.crate_context.tcx;
let drop_trait = match tcx.lang_items.drop_trait() {
Some(id) => id, None => { return }
}
pub fn check_coherence(crate_context: @CrateCtxt, crate: &Crate) {
- let coherence_checker = CoherenceChecker(crate_context);
- coherence_checker.check_coherence(crate);
+ CoherenceChecker::new(crate_context).check(crate);
}
// Note: Coerce is not actually a combiner, in that it does not
// conform to the same interface, though it performs a similar
// function.
-pub struct Coerce(CombineFields);
+pub struct Coerce<'f>(CombineFields<'f>);
-impl Coerce {
- pub fn get_ref<'a>(&'a self) -> &'a CombineFields {
+impl<'f> Coerce<'f> {
+ pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> {
let Coerce(ref v) = *self; v
}
});
}
- ty::ty_trait(def_id, ref substs, ty::BoxTraitStore, m, bounds) => {
- let result = self.unpack_actual_value(a, |sty_a| {
- match *sty_a {
- ty::ty_box(..) => {
- self.coerce_object(a, sty_a, b, def_id, substs,
- ty::BoxTraitStore, m, bounds)
- }
- _ => Err(ty::terr_mismatch)
- }
- });
-
- match result {
- Ok(t) => return Ok(t),
- Err(..) => {}
- }
- }
-
ty::ty_trait(def_id, ref substs, ty::UniqTraitStore, m, bounds) => {
let result = self.unpack_actual_value(a, |sty_a| {
match *sty_a {
b.inf_str(self.get_ref().infcx));
let (sigil, region) = match trait_store {
- ty::BoxTraitStore => (ast::ManagedSigil, None),
ty::UniqTraitStore => (ast::OwnedSigil, None),
ty::RegionTraitStore(region) => (ast::BorrowedSigil, Some(region))
};
use syntax::abi::AbiSet;
pub trait Combine {
- fn infcx(&self) -> @InferCtxt;
+ fn infcx<'a>(&'a self) -> &'a InferCtxt;
fn tag(&self) -> ~str;
fn a_is_expected(&self) -> bool;
fn trace(&self) -> TypeTrace;
- fn sub(&self) -> Sub;
- fn lub(&self) -> Lub;
- fn glb(&self) -> Glb;
+ fn sub<'a>(&'a self) -> Sub<'a>;
+ fn lub<'a>(&'a self) -> Lub<'a>;
+ fn glb<'a>(&'a self) -> Glb<'a>;
fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt>;
fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t>;
}
}
-pub struct CombineFields {
- infcx: @InferCtxt,
+pub struct CombineFields<'a> {
+ infcx: &'a InferCtxt,
a_is_expected: bool,
trace: TypeTrace,
}
use util::ppaux::note_and_explain_region;
pub trait ErrorReporting {
- fn report_region_errors(@self,
+ fn report_region_errors(&self,
errors: &OptVec<RegionResolutionError>);
- fn report_and_explain_type_error(@self,
+ fn report_and_explain_type_error(&self,
trace: TypeTrace,
terr: &ty::type_err);
- fn values_str(@self, values: &ValuePairs) -> Option<~str>;
+ fn values_str(&self, values: &ValuePairs) -> Option<~str>;
fn expected_found_str<T:UserString+Resolvable>(
- @self,
+ &self,
exp_found: &ty::expected_found<T>)
-> Option<~str>;
- fn report_concrete_failure(@self,
+ fn report_concrete_failure(&self,
origin: SubregionOrigin,
sub: Region,
sup: Region);
- fn report_sub_sup_conflict(@self,
+ fn report_sub_sup_conflict(&self,
var_origin: RegionVariableOrigin,
sub_origin: SubregionOrigin,
sub_region: Region,
sup_origin: SubregionOrigin,
sup_region: Region);
- fn report_sup_sup_conflict(@self,
+ fn report_sup_sup_conflict(&self,
var_origin: RegionVariableOrigin,
origin1: SubregionOrigin,
region1: Region,
}
trait ErrorReportingHelpers {
- fn report_inference_failure(@self,
+ fn report_inference_failure(&self,
var_origin: RegionVariableOrigin);
- fn note_region_origin(@self,
+ fn note_region_origin(&self,
origin: SubregionOrigin);
}
impl ErrorReporting for InferCtxt {
- fn report_region_errors(@self,
+ fn report_region_errors(&self,
errors: &OptVec<RegionResolutionError>) {
for error in errors.iter() {
match *error {
}
}
- fn report_and_explain_type_error(@self,
+ fn report_and_explain_type_error(&self,
trace: TypeTrace,
terr: &ty::type_err) {
- let tcx = self.tcx;
-
let expected_found_str = match self.values_str(&trace.values) {
Some(v) => v,
None => {
format!("{}: {} ({})",
message_root_str,
expected_found_str,
- ty::type_err_to_str(tcx, terr)));
+ ty::type_err_to_str(self.tcx, terr)));
ty::note_and_explain_type_err(self.tcx, terr);
}
- fn values_str(@self, values: &ValuePairs) -> Option<~str> {
+ fn values_str(&self, values: &ValuePairs) -> Option<~str> {
/*!
* Returns a string of the form "expected `{}` but found `{}`",
* or None if this is a derived error.
}
fn expected_found_str<T:UserString+Resolvable>(
- @self,
+ &self,
exp_found: &ty::expected_found<T>)
-> Option<~str>
{
found.user_string(self.tcx)))
}
- fn report_concrete_failure(@self,
+ fn report_concrete_failure(&self,
origin: SubregionOrigin,
sub: Region,
sup: Region) {
}
}
- fn report_sub_sup_conflict(@self,
+ fn report_sub_sup_conflict(&self,
var_origin: RegionVariableOrigin,
sub_origin: SubregionOrigin,
sub_region: Region,
self.note_region_origin(sub_origin);
}
- fn report_sup_sup_conflict(@self,
+ fn report_sup_sup_conflict(&self,
var_origin: RegionVariableOrigin,
origin1: SubregionOrigin,
region1: Region,
}
impl ErrorReportingHelpers for InferCtxt {
- fn report_inference_failure(@self,
+ fn report_inference_failure(&self,
var_origin: RegionVariableOrigin) {
let var_description = match var_origin {
infer::MiscVariable(_) => ~"",
var_description));
}
- fn note_region_origin(@self, origin: SubregionOrigin) {
+ fn note_region_origin(&self, origin: SubregionOrigin) {
match origin {
infer::Subtype(ref trace) => {
let desc = match trace.origin {
}
trait Resolvable {
- fn resolve(&self, infcx: @InferCtxt) -> Self;
+ fn resolve(&self, infcx: &InferCtxt) -> Self;
fn contains_error(&self) -> bool;
}
impl Resolvable for ty::t {
- fn resolve(&self, infcx: @InferCtxt) -> ty::t {
+ fn resolve(&self, infcx: &InferCtxt) -> ty::t {
infcx.resolve_type_vars_if_possible(*self)
}
fn contains_error(&self) -> bool {
}
impl Resolvable for @ty::TraitRef {
- fn resolve(&self, infcx: @InferCtxt) -> @ty::TraitRef {
+ fn resolve(&self, infcx: &InferCtxt) -> @ty::TraitRef {
@infcx.resolve_type_vars_in_trait_ref_if_possible(*self)
}
fn contains_error(&self) -> bool {
use util::common::{indenter};
use util::ppaux::mt_to_str;
-pub struct Glb(CombineFields); // "greatest lower bound" (common subtype)
+pub struct Glb<'f>(CombineFields<'f>); // "greatest lower bound" (common subtype)
-impl Glb {
- pub fn get_ref<'a>(&'a self) -> &'a CombineFields { let Glb(ref v) = *self; v }
+impl<'f> Glb<'f> {
+ pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Glb(ref v) = *self; v }
}
-impl Combine for Glb {
- fn infcx(&self) -> @InferCtxt { self.get_ref().infcx }
+impl<'f> Combine for Glb<'f> {
+ fn infcx<'a>(&'a self) -> &'a InferCtxt { self.get_ref().infcx }
fn tag(&self) -> ~str { ~"glb" }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
- fn sub(&self) -> Sub { Sub(*self.get_ref()) }
- fn lub(&self) -> Lub { Lub(*self.get_ref()) }
- fn glb(&self) -> Glb { Glb(*self.get_ref()) }
+ fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) }
+ fn lub<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) }
+ fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) }
fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt> {
let tcx = self.get_ref().infcx.tcx;
-> ures;
}
-impl CombineFieldsLatticeMethods for CombineFields {
+impl<'f> CombineFieldsLatticeMethods for CombineFields<'f> {
fn var_sub_var<T:Clone + InferStr + LatticeValue,
V:Clone + Eq + ToStr + Vid + UnifyVid<Bounds<T>>>(
&self,
// for pairs of variables or for variables and values.
pub trait LatticeDir {
- fn combine_fields(&self) -> CombineFields;
+ fn combine_fields<'a>(&'a self) -> CombineFields<'a>;
fn bnd<T:Clone>(&self, b: &Bounds<T>) -> Option<T>;
fn with_bnd<T:Clone>(&self, b: &Bounds<T>, t: T) -> Bounds<T>;
}
fn ty_bot(&self, t: ty::t) -> cres<ty::t>;
}
-impl LatticeDir for Lub {
- fn combine_fields(&self) -> CombineFields { *self.get_ref() }
+impl<'f> LatticeDir for Lub<'f> {
+ fn combine_fields<'a>(&'a self) -> CombineFields<'a> { *self.get_ref() }
fn bnd<T:Clone>(&self, b: &Bounds<T>) -> Option<T> { b.ub.clone() }
fn with_bnd<T:Clone>(&self, b: &Bounds<T>, t: T) -> Bounds<T> {
Bounds { ub: Some(t), ..(*b).clone() }
}
}
-impl TyLatticeDir for Lub {
+impl<'f> TyLatticeDir for Lub<'f> {
fn ty_bot(&self, t: ty::t) -> cres<ty::t> {
Ok(t)
}
}
-impl LatticeDir for Glb {
- fn combine_fields(&self) -> CombineFields { *self.get_ref() }
+impl<'f> LatticeDir for Glb<'f> {
+ fn combine_fields<'a>(&'a self) -> CombineFields<'a> { *self.get_ref() }
fn bnd<T:Clone>(&self, b: &Bounds<T>) -> Option<T> { b.lb.clone() }
fn with_bnd<T:Clone>(&self, b: &Bounds<T>, t: T) -> Bounds<T> {
Bounds { lb: Some(t), ..(*b).clone() }
}
}
-impl TyLatticeDir for Glb {
+impl<'f> TyLatticeDir for Glb<'f> {
fn ty_bot(&self, _t: ty::t) -> cres<ty::t> {
Ok(ty::mk_bot())
}
use syntax::ast::{Onceness, Purity};
use util::ppaux::mt_to_str;
-pub struct Lub(CombineFields); // least-upper-bound: common supertype
+pub struct Lub<'f>(CombineFields<'f>); // least-upper-bound: common supertype
-impl Lub {
- pub fn get_ref<'a>(&'a self) -> &'a CombineFields { let Lub(ref v) = *self; v }
+impl<'f> Lub<'f> {
+ pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Lub(ref v) = *self; v }
pub fn bot_ty(&self, b: ty::t) -> cres<ty::t> { Ok(b) }
pub fn ty_bot(&self, b: ty::t) -> cres<ty::t> {
self.bot_ty(b) // commutative
}
}
-impl Combine for Lub {
- fn infcx(&self) -> @InferCtxt { self.get_ref().infcx }
+impl<'f> Combine for Lub<'f> {
+ fn infcx<'a>(&'a self) -> &'a InferCtxt { self.get_ref().infcx }
fn tag(&self) -> ~str { ~"lub" }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
- fn sub(&self) -> Sub { Sub(*self.get_ref()) }
- fn lub(&self) -> Lub { Lub(*self.get_ref()) }
- fn glb(&self) -> Glb { Glb(*self.get_ref()) }
+ fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) }
+ fn lub<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) }
+ fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) }
fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt> {
let tcx = self.get_ref().infcx.tcx;
}
}
-pub fn new_infer_ctxt(tcx: ty::ctxt) -> @InferCtxt {
- @InferCtxt {
+pub fn new_infer_ctxt(tcx: ty::ctxt) -> InferCtxt {
+ InferCtxt {
tcx: tcx,
ty_var_bindings: RefCell::new(new_ValsAndBindings()),
}
}
-pub fn common_supertype(cx: @InferCtxt,
+pub fn common_supertype(cx: &InferCtxt,
origin: TypeOrigin,
a_is_expected: bool,
a: ty::t,
}
}
-pub fn mk_subty(cx: @InferCtxt,
+pub fn mk_subty(cx: &InferCtxt,
a_is_expected: bool,
origin: TypeOrigin,
a: ty::t,
}).to_ures()
}
-pub fn can_mk_subty(cx: @InferCtxt, a: ty::t, b: ty::t) -> ures {
+pub fn can_mk_subty(cx: &InferCtxt, a: ty::t, b: ty::t) -> ures {
debug!("can_mk_subty({} <: {})", a.inf_str(cx), b.inf_str(cx));
indent(|| {
cx.probe(|| {
}).to_ures()
}
-pub fn mk_subr(cx: @InferCtxt,
+pub fn mk_subr(cx: &InferCtxt,
_a_is_expected: bool,
origin: SubregionOrigin,
a: ty::Region,
cx.region_vars.commit();
}
-pub fn mk_eqty(cx: @InferCtxt,
+pub fn mk_eqty(cx: &InferCtxt,
a_is_expected: bool,
origin: TypeOrigin,
a: ty::t,
}).to_ures()
}
-pub fn mk_sub_trait_refs(cx: @InferCtxt,
+pub fn mk_sub_trait_refs(cx: &InferCtxt,
a_is_expected: bool,
origin: TypeOrigin,
a: @ty::TraitRef,
}
}
-pub fn mk_coercety(cx: @InferCtxt,
+pub fn mk_coercety(cx: &InferCtxt,
a_is_expected: bool,
origin: TypeOrigin,
a: ty::t,
})
}
-pub fn can_mk_coercety(cx: @InferCtxt, a: ty::t, b: ty::t) -> ures {
+pub fn can_mk_coercety(cx: &InferCtxt, a: ty::t, b: ty::t) -> ures {
debug!("can_mk_coercety({} -> {})", a.inf_str(cx), b.inf_str(cx));
indent(|| {
cx.probe(|| {
}
// See comment on the type `resolve_state` below
-pub fn resolve_type(cx: @InferCtxt,
+pub fn resolve_type(cx: &InferCtxt,
a: ty::t,
modes: uint)
-> fres<ty::t> {
resolver.resolve_type_chk(a)
}
-pub fn resolve_region(cx: @InferCtxt, r: ty::Region, modes: uint)
+pub fn resolve_region(cx: &InferCtxt, r: ty::Region, modes: uint)
-> fres<ty::Region> {
let mut resolver = resolver(cx, modes);
resolver.resolve_region_chk(r)
}
impl InferCtxt {
- pub fn combine_fields(@self, a_is_expected: bool, trace: TypeTrace)
- -> CombineFields {
+ pub fn combine_fields<'a>(&'a self, a_is_expected: bool, trace: TypeTrace)
+ -> CombineFields<'a> {
CombineFields {infcx: self,
a_is_expected: a_is_expected,
trace: trace}
}
- pub fn sub(@self, a_is_expected: bool, trace: TypeTrace) -> Sub {
+ pub fn sub<'a>(&'a self, a_is_expected: bool, trace: TypeTrace) -> Sub<'a> {
Sub(self.combine_fields(a_is_expected, trace))
}
- pub fn lub(@self, a_is_expected: bool, trace: TypeTrace) -> Lub {
+ pub fn lub<'a>(&'a self, a_is_expected: bool, trace: TypeTrace) -> Lub<'a> {
Lub(self.combine_fields(a_is_expected, trace))
}
}
/// Execute `f` and commit the bindings if successful
- pub fn commit<T,E>(@self, f: || -> Result<T,E>) -> Result<T,E> {
+ pub fn commit<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> {
assert!(!self.in_snapshot());
debug!("commit()");
}
/// Execute `f`, unroll bindings on failure
- pub fn try<T,E>(@self, f: || -> Result<T,E>) -> Result<T,E> {
+ pub fn try<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> {
debug!("try()");
let snapshot = self.start_snapshot();
let r = f();
}
/// Execute `f` then unroll any bindings it creates
- pub fn probe<T,E>(@self, f: || -> Result<T,E>) -> Result<T,E> {
+ pub fn probe<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> {
debug!("probe()");
indent(|| {
let snapshot = self.start_snapshot();
self.region_vars.new_bound(binder_id)
}
- pub fn resolve_regions(@self) {
+ pub fn resolve_regions(&self) {
let errors = self.region_vars.resolve_regions();
self.report_region_errors(&errors); // see error_reporting.rs
}
- pub fn ty_to_str(@self, t: ty::t) -> ~str {
+ pub fn ty_to_str(&self, t: ty::t) -> ~str {
ty_to_str(self.tcx,
self.resolve_type_vars_if_possible(t))
}
- pub fn tys_to_str(@self, ts: &[ty::t]) -> ~str {
+ pub fn tys_to_str(&self, ts: &[ty::t]) -> ~str {
let tstrs = ts.map(|t| self.ty_to_str(*t));
format!("({})", tstrs.connect(", "))
}
- pub fn trait_ref_to_str(@self, t: &ty::TraitRef) -> ~str {
+ pub fn trait_ref_to_str(&self, t: &ty::TraitRef) -> ~str {
let t = self.resolve_type_vars_in_trait_ref_if_possible(t);
trait_ref_to_str(self.tcx, &t)
}
- pub fn resolve_type_vars_if_possible(@self, typ: ty::t) -> ty::t {
+ pub fn resolve_type_vars_if_possible(&self, typ: ty::t) -> ty::t {
match resolve_type(self, typ, resolve_nested_tvar | resolve_ivar) {
result::Ok(new_type) => new_type,
result::Err(_) => typ
}
}
- pub fn resolve_type_vars_in_trait_ref_if_possible(@self,
+ pub fn resolve_type_vars_in_trait_ref_if_possible(&self,
trait_ref:
&ty::TraitRef)
-> ty::TraitRef {
// in this case. The typechecker should only ever report type errors involving mismatched
// types using one of these four methods, and should not call span_err directly for such
// errors.
- pub fn type_error_message_str(@self,
+ pub fn type_error_message_str(&self,
sp: Span,
mk_msg: |Option<~str>, ~str| -> ~str,
actual_ty: ~str,
self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
}
- pub fn type_error_message_str_with_expected(@self,
+ pub fn type_error_message_str_with_expected(&self,
sp: Span,
mk_msg: |Option<~str>,
~str|
}
}
- pub fn type_error_message(@self,
+ pub fn type_error_message(&self,
sp: Span,
mk_msg: |~str| -> ~str,
actual_ty: ty::t,
self.type_error_message_str(sp, |_e, a| { mk_msg(a) }, self.ty_to_str(actual_ty), err);
}
- pub fn report_mismatched_types(@self,
+ pub fn report_mismatched_types(&self,
sp: Span,
e: ty::t,
a: ty::t,
pub static resolve_and_force_all_but_regions: uint =
(resolve_all | force_all) & not_regions;
-pub struct ResolveState {
- infcx: @InferCtxt,
+pub struct ResolveState<'a> {
+ infcx: &'a InferCtxt,
modes: uint,
err: Option<fixup_err>,
v_seen: ~[TyVid],
type_depth: uint
}
-pub fn resolver(infcx: @InferCtxt, modes: uint) -> ResolveState {
+pub fn resolver<'a>(infcx: &'a InferCtxt, modes: uint) -> ResolveState<'a> {
ResolveState {
infcx: infcx,
modes: modes,
}
}
-impl ty_fold::TypeFolder for ResolveState {
+impl<'a> ty_fold::TypeFolder for ResolveState<'a> {
fn tcx(&self) -> ty::ctxt {
self.infcx.tcx
}
}
}
-impl ResolveState {
+impl<'a> ResolveState<'a> {
pub fn should(&mut self, mode: uint) -> bool {
(self.modes & mode) == mode
}
use syntax::ast::{Onceness, Purity};
-pub struct Sub(CombineFields); // "subtype", "subregion" etc
+pub struct Sub<'f>(CombineFields<'f>); // "subtype", "subregion" etc
-impl Sub {
- pub fn get_ref<'a>(&'a self) -> &'a CombineFields { let Sub(ref v) = *self; v }
+impl<'f> Sub<'f> {
+ pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Sub(ref v) = *self; v }
}
-impl Combine for Sub {
- fn infcx(&self) -> @InferCtxt { self.get_ref().infcx }
+impl<'f> Combine for Sub<'f> {
+ fn infcx<'a>(&'a self) -> &'a InferCtxt { self.get_ref().infcx }
fn tag(&self) -> ~str { ~"sub" }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
- fn sub(&self) -> Sub { Sub(*self.get_ref()) }
- fn lub(&self) -> Lub { Lub(*self.get_ref()) }
- fn glb(&self) -> Glb { Glb(*self.get_ref()) }
+ fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) }
+ fn lub<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) }
+ fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) }
fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> {
let opp = CombineFields {
use std::cell::RefCell;
use std::hashmap::HashMap;
use std::rc::Rc;
-use std::result;
use extra::list::List;
use extra::list;
use syntax::codemap::Span;
}
pub fn require_same_types(tcx: ty::ctxt,
- maybe_infcx: Option<@infer::InferCtxt>,
+ maybe_infcx: Option<&infer::InferCtxt>,
t1_is_expected: bool,
span: Span,
t1: ty::t,
t2: ty::t,
msg: || -> ~str)
-> bool {
- let l_tcx;
- let l_infcx;
- match maybe_infcx {
- None => {
- l_tcx = tcx;
- l_infcx = infer::new_infer_ctxt(tcx);
- }
- Some(i) => {
- l_tcx = i.tcx;
- l_infcx = i;
- }
- }
+ let result = match maybe_infcx {
+ None => {
+ let infcx = infer::new_infer_ctxt(tcx);
+ infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
+ }
+ Some(infcx) => {
+ infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
+ }
+ };
- match infer::mk_eqty(l_infcx, t1_is_expected, infer::Misc(span), t1, t2) {
- result::Ok(()) => true,
- result::Err(ref terr) => {
- l_tcx.sess.span_err(span, msg() + ": " +
- ty::type_err_to_str(l_tcx, terr));
- ty::note_and_explain_type_err(l_tcx, terr);
+ match result {
+ Ok(_) => true,
+ Err(ref terr) => {
+ tcx.sess.span_err(span, msg() + ": " +
+ ty::type_err_to_str(tcx, terr));
+ ty::note_and_explain_type_err(tcx, terr);
false
}
}
pub fn trait_store_to_str(cx: ctxt, s: ty::TraitStore) -> ~str {
match s {
ty::UniqTraitStore => ~"~",
- ty::BoxTraitStore => ~"@",
ty::RegionTraitStore(r) => region_ptr_to_str(cx, r)
}
}
impl Repr for ty::TraitStore {
fn repr(&self, tcx: ctxt) -> ~str {
match self {
- &ty::BoxTraitStore => ~"@Trait",
&ty::UniqTraitStore => ~"~Trait",
&ty::RegionTraitStore(r) => format!("&{} Trait", r.repr(tcx))
}
SelfStatic,
SelfValue,
SelfBorrowed(Option<Lifetime>, Mutability),
- SelfManaged,
SelfOwned,
}
ast::SelfValue => SelfValue,
ast::SelfUniq => SelfOwned,
ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
- ast::SelfBox => SelfManaged,
}
}
}
use rustc::middle::privacy;
use syntax::ast;
-use syntax::diagnostic;
use syntax::parse::token;
use syntax::parse;
use syntax;
phase_2_configure_and_expand,
phase_3_run_analysis_passes};
- let parsesess = parse::new_parse_sess(None);
+ let parsesess = parse::new_parse_sess();
let input = FileInput(cpath.clone());
let sessopts = @driver::session::Options {
};
- let diagnostic_handler = syntax::diagnostic::mk_handler(None);
+ let diagnostic_handler = syntax::diagnostic::mk_handler();
let span_diagnostic_handler =
syntax::diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm);
let sess = driver::driver::build_session_(sessopts,
Some(cpath.clone()),
parsesess.cm,
- @diagnostic::DefaultEmitter,
span_diagnostic_handler);
let mut cfg = build_configuration(sess);
clean::SelfStatic => {},
clean::SelfValue => args.push_str("self"),
clean::SelfOwned => args.push_str("~self"),
- clean::SelfManaged => args.push_str("@self"),
clean::SelfBorrowed(Some(ref lt), clean::Immutable) => {
args.push_str(format!("&{} self", *lt));
}
use visit_ast::RustdocVisitor;
pub fn run(input: &str, matches: &getopts::Matches) -> int {
- let parsesess = parse::new_parse_sess(None);
+ let parsesess = parse::new_parse_sess();
let input_path = Path::new(input);
let input = driver::FileInput(input_path.clone());
let libs = matches.opt_strs("L").map(|s| Path::new(s.as_slice()));
};
- let diagnostic_handler = diagnostic::mk_handler(None);
+ let diagnostic_handler = diagnostic::mk_handler();
let span_diagnostic_handler =
diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm);
let sess = driver::build_session_(sessopts,
Some(input_path),
parsesess.cm,
- @diagnostic::DefaultEmitter,
span_diagnostic_handler);
let cfg = driver::build_configuration(sess);
fn runtest(test: &str, cratename: &str, libs: HashSet<Path>) {
let test = maketest(test, cratename);
- let parsesess = parse::new_parse_sess(None);
+ let parsesess = parse::new_parse_sess();
let input = driver::StrInput(test);
let sessopts = @session::Options {
.. (*session::basic_options()).clone()
};
- let diagnostic_handler = diagnostic::mk_handler(None);
+ let diagnostic_handler = diagnostic::mk_handler();
let span_diagnostic_handler =
diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm);
let sess = driver::build_session_(sessopts,
None,
parsesess.cm,
- @diagnostic::DefaultEmitter,
span_diagnostic_handler);
let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir");
assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
- let (a, b, c) = (@5u as @Any, @TEST as @Any, @Test as @Any);
- let a_r: &Any = a;
- let b_r: &Any = b;
- let c_r: &Any = c;
-
- assert_eq!(a.as_void_ptr(), a_r.as_void_ptr());
- assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
- assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
-
let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
let a_r: &Any = a;
let b_r: &Any = b;
assert!(c.is::<Test>());
}
- #[test]
- fn any_managed() {
- let (a, b, c) = (@5u as @Any, @TEST as @Any, @Test as @Any);
-
- assert!(a.is::<uint>());
- assert!(!b.is::<uint>());
- assert!(!c.is::<uint>());
-
- assert!(!a.is::<&'static str>());
- assert!(b.is::<&'static str>());
- assert!(!c.is::<&'static str>());
-
- assert!(!a.is::<Test>());
- assert!(!b.is::<Test>());
- assert!(c.is::<Test>());
- }
-
#[test]
fn any_as_ref() {
let a = &5u as &Any;
}
fn visit_trait(&mut self, name: &str) -> bool {
- self.align_to::<@TyVisitor>();
+ self.align_to::<~TyVisitor>();
if ! self.inner.visit_trait(name) { return false; }
- self.bump_past::<@TyVisitor>();
+ self.bump_past::<~TyVisitor>();
true
}
SelfStatic, // no self
SelfValue, // `self`
SelfRegion(Option<Lifetime>, Mutability), // `&'lt self`, `&'lt mut self`
- SelfBox, // `@self`
SelfUniq // `~self`
}
},
};
// doesn't matter which encoder we use....
- let _f = (@e as @serialize::Encodable<extra::json::Encoder>);
+ let _f = (&e as &serialize::Encodable<extra::json::Encoder>);
}
}
static MAX_LINES: uint = 6u;
pub trait Emitter {
- fn emit(&self,
- cmsp: Option<(&codemap::CodeMap, Span)>,
- msg: &str,
- lvl: Level);
+ fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>,
+ msg: &str, lvl: Level);
fn custom_emit(&self, cm: &codemap::CodeMap,
sp: Span, msg: &str, lvl: Level);
}
}
impl SpanHandler {
- pub fn span_fatal(@self, sp: Span, msg: &str) -> ! {
+ pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
self.handler.emit(Some((&*self.cm, sp)), msg, Fatal);
fail!(FatalError);
}
- pub fn span_err(@self, sp: Span, msg: &str) {
+ pub fn span_err(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Error);
self.handler.bump_err_count();
}
- pub fn span_warn(@self, sp: Span, msg: &str) {
+ pub fn span_warn(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Warning);
}
- pub fn span_note(@self, sp: Span, msg: &str) {
+ pub fn span_note(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Note);
}
- pub fn span_end_note(@self, sp: Span, msg: &str) {
+ pub fn span_end_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&*self.cm, sp, msg, Note);
}
- pub fn span_bug(@self, sp: Span, msg: &str) -> ! {
+ pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
self.span_fatal(sp, ice_msg(msg));
}
- pub fn span_unimpl(@self, sp: Span, msg: &str) -> ! {
+ pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
self.span_bug(sp, ~"unimplemented " + msg);
}
- pub fn handler(@self) -> @Handler {
+ pub fn handler(&self) -> @Handler {
self.handler
}
}
// others log errors for later reporting.
pub struct Handler {
err_count: Cell<uint>,
- emit: @Emitter,
+ emit: DefaultEmitter,
}
impl Handler {
- pub fn fatal(@self, msg: &str) -> ! {
+ pub fn fatal(&self, msg: &str) -> ! {
self.emit.emit(None, msg, Fatal);
fail!(FatalError);
}
- pub fn err(@self, msg: &str) {
+ pub fn err(&self, msg: &str) {
self.emit.emit(None, msg, Error);
self.bump_err_count();
}
- pub fn bump_err_count(@self) {
+ pub fn bump_err_count(&self) {
self.err_count.set(self.err_count.get() + 1u);
}
- pub fn err_count(@self) -> uint {
+ pub fn err_count(&self) -> uint {
self.err_count.get()
}
- pub fn has_errors(@self) -> bool {
+ pub fn has_errors(&self) -> bool {
self.err_count.get()> 0u
}
- pub fn abort_if_errors(@self) {
+ pub fn abort_if_errors(&self) {
let s;
match self.err_count.get() {
0u => return,
}
self.fatal(s);
}
- pub fn warn(@self, msg: &str) {
+ pub fn warn(&self, msg: &str) {
self.emit.emit(None, msg, Warning);
}
- pub fn note(@self, msg: &str) {
+ pub fn note(&self, msg: &str) {
self.emit.emit(None, msg, Note);
}
- pub fn bug(@self, msg: &str) -> ! {
+ pub fn bug(&self, msg: &str) -> ! {
self.fatal(ice_msg(msg));
}
- pub fn unimpl(@self, msg: &str) -> ! {
+ pub fn unimpl(&self, msg: &str) -> ! {
self.bug(~"unimplemented " + msg);
}
- pub fn emit(@self,
- cmsp: Option<(&codemap::CodeMap, Span)>,
- msg: &str,
- lvl: Level) {
+ pub fn emit(&self,
+ cmsp: Option<(&codemap::CodeMap, Span)>,
+ msg: &str,
+ lvl: Level) {
self.emit.emit(cmsp, msg, lvl);
}
- pub fn custom_emit(@self, cm: &codemap::CodeMap,
+ pub fn custom_emit(&self, cm: &codemap::CodeMap,
sp: Span, msg: &str, lvl: Level) {
self.emit.custom_emit(cm, sp, msg, lvl);
}
}
}
-pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler {
- let emit: @Emitter = match emitter {
- Some(e) => e,
- None => @DefaultEmitter as @Emitter
- };
-
+pub fn mk_handler() -> @Handler {
@Handler {
err_count: Cell::new(0),
- emit: emit,
+ emit: DefaultEmitter,
}
}
pub enum MacResult {
MRExpr(@ast::Expr),
MRItem(@ast::Item),
- MRAny(@AnyMacro),
+ MRAny(~AnyMacro:),
MRDef(MacroDef),
}
impl MacResult {
lifetime: Option<ast::Lifetime>,
mutbl: ast::Mutability) -> P<ast::Ty>;
fn ty_uniq(&self, span: Span, ty: P<ast::Ty>) -> P<ast::Ty>;
- fn ty_box(&self, span: Span, ty: P<ast::Ty>) -> P<ast::Ty>;
fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty>;
fn ty_infer(&self, sp: Span) -> P<ast::Ty>;
self.ty(span, ast::TyUniq(ty))
}
- fn ty_box(&self, span: Span, ty: P<ast::Ty>) -> P<ast::Ty> {
- self.ty(span, ast::TyBox(ty))
- }
-
fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty> {
self.ty_path(
self.path_all(DUMMY_SP,
}
*/
-use ast::{MetaItem, Item, Expr, MutImmutable, MutMutable};
+use ast::{MetaItem, Item, Expr, MutMutable};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
MethodDef {
name: "encode",
generics: LifetimeBounds::empty(),
- explicit_self: Some(Some(Borrowed(None, MutImmutable))),
+ explicit_self: borrowed_explicit_self(),
args: ~[Ptr(~Literal(Path::new_local("__E")),
Borrowed(None, MutMutable))],
ret_ty: nil_ty(),
/// The types of pointers
pub enum PtrTy<'a> {
Send, // ~
- Managed, // @
Borrowed(Option<&'a str>, ast::Mutability), // &['lifetime] [mut]
}
Send => {
cx.ty_uniq(span, raw_ty)
}
- Managed => {
- cx.ty_box(span, raw_ty)
- }
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
span,
match *ptr {
Send => ast::SelfUniq,
- Managed => ast::SelfBox,
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(s)));
ast::SelfRegion(lt, mutbl)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use ast::{P, Block, Crate, DeclLocal, ExprMac, SyntaxContext};
+use ast::{P, Block, Crate, DeclLocal, ExprMac};
use ast::{Local, Ident, MacInvocTT};
use ast::{ItemMac, Mrk, Stmt, StmtDecl, StmtMac, StmtExpr, StmtSemi};
use ast::{TokenTree};
// Desugar expr_for_loop
// From: `['<ident>:] for <src_pat> in <src_expr> <src_loop_block>`
- // FIXME #6993 : change type of opt_ident to Option<Name>
+ // FIXME #6993: change type of opt_ident to Option<Name>
ast::ExprForLoop(src_pat, src_expr, src_loop_block, opt_ident) => {
// Expand any interior macros etc.
// NB: we don't fold pats yet. Curious.
// element that has one. a CtxtFn is a trait-ified
// version of a closure in (SyntaxContext -> SyntaxContext).
// the ones defined here include:
-// Renamer - add a rename to a context
-// MultiRenamer - add a set of renames to a context
// Marker - add a mark to a context
-// Repainter - replace a context (maybe Replacer would be a better name?)
-// a function in SyntaxContext -> SyntaxContext
-pub trait CtxtFn{
- fn f(&self, ast::SyntaxContext) -> ast::SyntaxContext;
-}
-
-// a renamer adds a rename to the syntax context
-pub struct Renamer {
- from : ast::Ident,
- to : ast::Name
-}
+// A Marker adds the given mark to the syntax context
+struct Marker { mark: Mrk }
-impl CtxtFn for Renamer {
- fn f(&self, ctxt : ast::SyntaxContext) -> ast::SyntaxContext {
- new_rename(self.from,self.to,ctxt)
- }
-}
-
-// a marker adds the given mark to the syntax context
-pub struct Marker { mark : Mrk }
-
-impl CtxtFn for Marker {
- fn f(&self, ctxt : ast::SyntaxContext) -> ast::SyntaxContext {
- new_mark(self.mark,ctxt)
- }
-}
-
-// a repainter just replaces the given context with the one it's closed over
-pub struct Repainter { ctxt : SyntaxContext }
-
-impl CtxtFn for Repainter {
- fn f(&self, _ctxt : ast::SyntaxContext) -> ast::SyntaxContext {
- self.ctxt
- }
-}
-
-pub struct ContextWrapper {
- context_function: @CtxtFn,
-}
-
-impl Folder for ContextWrapper {
+impl Folder for Marker {
fn fold_ident(&mut self, id: ast::Ident) -> ast::Ident {
- let ast::Ident {
- name,
- ctxt
- } = id;
ast::Ident {
- name: name,
- ctxt: self.context_function.f(ctxt),
+ name: id.name,
+ ctxt: new_mark(self.mark, id.ctxt)
}
}
fn fold_mac(&mut self, m: &ast::Mac) -> ast::Mac {
MacInvocTT(ref path, ref tts, ctxt) => {
MacInvocTT(self.fold_path(path),
fold_tts(*tts, self),
- self.context_function.f(ctxt))
+ new_mark(self.mark, ctxt))
}
};
Spanned {
}
}
-// given a function from ctxts to ctxts, produce
-// a Folder that applies that function to all ctxts:
-pub fn fun_to_ctxt_folder<T : 'static + CtxtFn>(cf: @T) -> ContextWrapper {
- ContextWrapper {
- context_function: cf as @CtxtFn,
- }
-}
-
// just a convenience:
-pub fn new_mark_folder(m: Mrk) -> ContextWrapper {
- fun_to_ctxt_folder(@Marker{mark:m})
-}
-
-pub fn new_rename_folder(from: ast::Ident, to: ast::Name) -> ContextWrapper {
- fun_to_ctxt_folder(@Renamer{from:from,to:to})
+fn new_mark_folder(m: Mrk) -> Marker {
+ Marker {mark: m}
}
// apply a given mark to the given token trees. Used prior to expansion of a macro.
-fn mark_tts(tts : &[TokenTree], m : Mrk) -> ~[TokenTree] {
+fn mark_tts(tts: &[TokenTree], m: Mrk) -> ~[TokenTree] {
fold_tts(tts, &mut new_mark_folder(m))
}
// apply a given mark to the given expr. Used following the expansion of a macro.
-fn mark_expr(expr : @ast::Expr, m : Mrk) -> @ast::Expr {
+fn mark_expr(expr: @ast::Expr, m: Mrk) -> @ast::Expr {
new_mark_folder(m).fold_expr(expr)
}
// apply a given mark to the given stmt. Used following the expansion of a macro.
-fn mark_stmt(expr : &ast::Stmt, m : Mrk) -> @ast::Stmt {
+fn mark_stmt(expr: &ast::Stmt, m: Mrk) -> @ast::Stmt {
new_mark_folder(m).fold_stmt(expr)
.expect_one("marking a stmt didn't return a stmt")
}
// apply a given mark to the given item. Used following the expansion of a macro.
-fn mark_item(expr : @ast::Item, m : Mrk) -> SmallVector<@ast::Item> {
+fn mark_item(expr: @ast::Item, m: Mrk) -> SmallVector<@ast::Item> {
new_mark_folder(m).fold_item(expr)
}
-// replace all contexts in a given expr with the given mark. Used
-// for capturing macros
-pub fn replace_ctxts(expr : @ast::Expr, ctxt : SyntaxContext) -> @ast::Expr {
- fun_to_ctxt_folder(@Repainter{ctxt:ctxt}).fold_expr(expr)
-}
-
fn original_span(cx: &ExtCtxt) -> @codemap::ExpnInfo {
let mut relevant_info = cx.backtrace();
let mut einfo = relevant_info.unwrap();
#[test] fn macros_cant_escape_fns_test () {
let src = ~"fn bogus() {macro_rules! z (() => (3+4))}\
fn inty() -> int { z!() }";
- let sess = parse::new_parse_sess(None);
+ let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
~"<test>",
src,
#[test] fn macros_cant_escape_mods_test () {
let src = ~"mod foo {macro_rules! z (() => (3+4))}\
fn inty() -> int { z!() }";
- let sess = parse::new_parse_sess(None);
+ let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
~"<test>",
src,
#[test] fn macros_can_escape_flattened_mods_test () {
let src = ~"#[macro_escape] mod foo {macro_rules! z (() => (3+4))}\
fn inty() -> int { z!() }";
- let sess = parse::new_parse_sess(None);
+ let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
~"<test>",
src,
}
}
- #[test]
- fn renaming () {
- let item_ast = string_to_crate(~"fn f() -> int { a }");
- let a_name = intern("a");
- let a2_name = gensym("a2");
- let mut renamer = new_rename_folder(ast::Ident{name:a_name,ctxt:EMPTY_CTXT},
- a2_name);
- let renamed_ast = renamer.fold_crate(item_ast.clone());
- let mut path_finder = new_path_finder(~[]);
- visit::walk_crate(&mut path_finder, &renamed_ast, ());
-
- match path_finder.path_accumulator {
- [ast::Path{segments:[ref seg],..}] =>
- assert_eq!(mtwt_resolve(seg.identifier),a2_name),
- _ => assert_eq!(0,1)
- }
-
- // try a double-rename, with pending_renames.
- let a3_name = gensym("a3");
- // a context that renames from ("a",empty) to "a2" :
- let ctxt2 = new_rename(ast::Ident::new(a_name),a2_name,EMPTY_CTXT);
- let mut pending_renames = ~[
- (ast::Ident::new(a_name),a2_name),
- (ast::Ident{name:a_name,ctxt:ctxt2},a3_name)
- ];
- let double_renamed = renames_to_fold(&mut pending_renames).fold_crate(item_ast);
- let mut path_finder = new_path_finder(~[]);
- visit::walk_crate(&mut path_finder, &double_renamed, ());
- match path_finder.path_accumulator {
- [ast::Path{segments:[ref seg],..}] =>
- assert_eq!(mtwt_resolve(seg.identifier),a3_name),
- _ => assert_eq!(0,1)
- }
- }
-
//fn fake_print_crate(crate: &ast::Crate) {
// let mut out = ~std::io::stderr() as ~std::io::Writer;
// let mut s = pprust::rust_printer(out, get_ident_interner());
// println!("expanded: {:?}\n",expanded_ast);
//mtwt_resolve_crate(expanded_ast)
//}
- //fn expand_and_resolve_and_pretty_print (crate_str : @str) -> ~str {
+ //fn expand_and_resolve_and_pretty_print (crate_str: @str) -> ~str {
//let resolved_ast = expand_and_resolve(crate_str);
//pprust::to_str(&resolved_ast,fake_print_crate,get_ident_interner())
//}
#[test]
fn automatic_renaming () {
- let tests : ~[RenamingTest] =
+ let tests: ~[RenamingTest] =
~[// b & c should get new names throughout, in the expr too:
("fn a() -> int { let b = 13; let c = b; b+c }",
~[~[0,1],~[2]], false),
// both x's should be renamed (how is this causing a bug?)
- ("fn main () {let x : int = 13;x;}",
+ ("fn main () {let x: int = 13;x;}",
~[~[0]], false),
// the use of b after the + should be renamed, the other one not:
("macro_rules! f (($x:ident) => (b + $x)) fn a() -> int { let b = 13; f!(b)}",
visit::walk_crate(&mut name_finder, &cr, ());
let bindings = name_finder.ident_accumulator;
- let cxbinds : ~[&ast::Ident] =
+ let cxbinds: ~[&ast::Ident] =
bindings.iter().filter(|b| {
let string = token::get_ident(b.name);
"xx" == string.get()
{
let table = table.table.borrow();
for (idx,val) in table.get().iter().enumerate() {
- println!("{:4u} : {:?}",idx,val);
+ println!("{:4u}: {:?}",idx,val);
}
}
}
let tt_rdr = new_tt_reader(cx.parse_sess().span_diagnostic,
None,
tt.to_owned());
- let rdr = tt_rdr as @Reader;
- let mut rust_parser = Parser(sess, cfg.clone(), rdr.dup());
+ let mut rust_parser = Parser(sess, cfg.clone(), tt_rdr.dup());
if rust_parser.is_keyword(keywords::True) {
cx.set_trace_macros(true);
rust_parser.bump();
- let mut rust_parser = Parser(sess, cfg, rdr.dup());
+ let mut rust_parser = Parser(sess, cfg, tt_rdr.dup());
let result = rust_parser.parse_expr();
base::MRExpr(result)
}
Error(codemap::Span, ~str)
}
-pub fn parse_or_else(sess: @ParseSess,
- cfg: ast::CrateConfig,
- rdr: @Reader,
- ms: ~[Matcher])
- -> HashMap<Ident, @NamedMatch> {
+pub fn parse_or_else<R: Reader>(sess: @ParseSess,
+ cfg: ast::CrateConfig,
+ rdr: R,
+ ms: ~[Matcher])
+ -> HashMap<Ident, @NamedMatch> {
match parse(sess, cfg, rdr, ms) {
Success(m) => m,
Failure(sp, str) => sess.span_diagnostic.span_fatal(sp, str),
}
}
-pub fn parse(sess: @ParseSess,
- cfg: ast::CrateConfig,
- rdr: @Reader,
- ms: &[Matcher])
- -> ParseResult {
+pub fn parse<R: Reader>(sess: @ParseSess,
+ cfg: ast::CrateConfig,
+ rdr: R,
+ ms: &[Matcher])
+ -> ParseResult {
let mut cur_eis = ~[];
cur_eis.push(initial_matcher_pos(ms.to_owned(), None, rdr.peek().sp.lo));
use ext::tt::macro_parser::{Success, Error, Failure};
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use ext::tt::macro_parser::{parse, parse_or_else};
-use parse::lexer::{new_tt_reader, Reader};
+use parse::lexer::new_tt_reader;
use parse::parser::Parser;
use parse::attr::ParserAttr;
use parse::token::{get_ident_interner, special_idents, gensym_ident};
for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
match **lhs {
MatchedNonterminal(NtMatchers(ref mtcs)) => {
- // `none` is because we're not interpolating
- let arg_rdr = new_tt_reader(s_d, None, arg.to_owned()) as @Reader;
+ // `None` is because we're not interpolating
+ let arg_rdr = new_tt_reader(s_d, None, arg.to_owned());
match parse(cx.parse_sess(), cx.cfg(), arg_rdr, *mtcs) {
Success(named_matches) => {
let rhs = match *rhses[i] {
// rhs has holes ( `$id` and `$(...)` that need filled)
let trncbr = new_tt_reader(s_d, Some(named_matches),
rhs);
- let p = Parser(cx.parse_sess(), cx.cfg(), trncbr as @Reader);
+ let p = Parser(cx.parse_sess(), cx.cfg(), ~trncbr);
// Let the context choose how to interpret the result.
// Weird, but useful for X-macros.
- return MRAny(@ParserAnyMacro {
+ return MRAny(~ParserAnyMacro {
parser: RefCell::new(p),
- } as @AnyMacro)
+ })
}
Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo {
best_fail_spot = sp;
arg.clone());
let argument_map = parse_or_else(cx.parse_sess(),
cx.cfg(),
- arg_reader as @Reader,
+ arg_reader,
argument_gram);
// Extract the arguments:
pub fn new_tt_reader(sp_diag: @SpanHandler,
interp: Option<HashMap<Ident, @NamedMatch>>,
src: ~[ast::TokenTree])
- -> @TtReader {
- let r = @TtReader {
+ -> TtReader {
+ let r = TtReader {
sp_diag: sp_diag,
stack: RefCell::new(@TtFrame {
forest: @src,
cur_tok: RefCell::new(EOF),
cur_span: RefCell::new(DUMMY_SP),
};
- tt_next_token(r); /* get cur_tok and cur_span set up */
+ tt_next_token(&r); /* get cur_tok and cur_span set up */
return r;
}
}
}
-pub fn dup_tt_reader(r: @TtReader) -> @TtReader {
- @TtReader {
+pub fn dup_tt_reader(r: &TtReader) -> TtReader {
+ TtReader {
sp_diag: r.sp_diag,
stack: RefCell::new(dup_tt_frame(r.stack.get())),
repeat_idx: r.repeat_idx.clone(),
fn fold_explicit_self_(&mut self, es: &ExplicitSelf_) -> ExplicitSelf_ {
match *es {
- SelfStatic | SelfValue | SelfUniq | SelfBox => *es,
+ SelfStatic | SelfValue | SelfUniq => *es,
SelfRegion(ref lifetime, m) => {
SelfRegion(fold_opt_lifetime(lifetime, self), m)
}
fail!("not a doc-comment: {}", comment);
}
-fn read_to_eol(rdr: @StringReader) -> ~str {
+fn read_to_eol(rdr: &StringReader) -> ~str {
let mut val = ~"";
while rdr.curr.get() != '\n' && !is_eof(rdr) {
val.push_char(rdr.curr.get());
return val;
}
-fn read_one_line_comment(rdr: @StringReader) -> ~str {
+fn read_one_line_comment(rdr: &StringReader) -> ~str {
let val = read_to_eol(rdr);
assert!((val[0] == '/' as u8 && val[1] == '/' as u8) ||
(val[0] == '#' as u8 && val[1] == '!' as u8));
return val;
}
-fn consume_non_eol_whitespace(rdr: @StringReader) {
+fn consume_non_eol_whitespace(rdr: &StringReader) {
while is_whitespace(rdr.curr.get()) && rdr.curr.get() != '\n' &&
!is_eof(rdr) {
bump(rdr);
}
}
-fn push_blank_line_comment(rdr: @StringReader, comments: &mut ~[Comment]) {
+fn push_blank_line_comment(rdr: &StringReader, comments: &mut ~[Comment]) {
debug!(">>> blank-line comment");
let v: ~[~str] = ~[];
comments.push(Comment {
});
}
-fn consume_whitespace_counting_blank_lines(rdr: @StringReader,
+fn consume_whitespace_counting_blank_lines(rdr: &StringReader,
comments: &mut ~[Comment]) {
while is_whitespace(rdr.curr.get()) && !is_eof(rdr) {
if rdr.col.get() == CharPos(0u) && rdr.curr.get() == '\n' {
}
-fn read_shebang_comment(rdr: @StringReader, code_to_the_left: bool,
+fn read_shebang_comment(rdr: &StringReader, code_to_the_left: bool,
comments: &mut ~[Comment]) {
debug!(">>> shebang comment");
let p = rdr.last_pos.get();
});
}
-fn read_line_comments(rdr: @StringReader, code_to_the_left: bool,
+fn read_line_comments(rdr: &StringReader, code_to_the_left: bool,
comments: &mut ~[Comment]) {
debug!(">>> line comments");
let p = rdr.last_pos.get();
lines.push(s1);
}
-fn read_block_comment(rdr: @StringReader,
+fn read_block_comment(rdr: &StringReader,
code_to_the_left: bool,
comments: &mut ~[Comment]) {
debug!(">>> block comment");
while level > 0 {
debug!("=== block comment level {}", level);
if is_eof(rdr) {
- (rdr as @Reader).fatal(~"unterminated block comment");
+ rdr.fatal(~"unterminated block comment");
}
if rdr.curr.get() == '\n' {
trim_whitespace_prefix_and_push_line(&mut lines, curr_line,
comments.push(Comment {style: style, lines: lines, pos: p});
}
-fn peeking_at_comment(rdr: @StringReader) -> bool {
+fn peeking_at_comment(rdr: &StringReader) -> bool {
return ((rdr.curr.get() == '/' && nextch(rdr) == '/') ||
(rdr.curr.get() == '/' && nextch(rdr) == '*')) ||
(rdr.curr.get() == '#' && nextch(rdr) == '!');
}
-fn consume_comment(rdr: @StringReader,
+fn consume_comment(rdr: &StringReader,
code_to_the_left: bool,
comments: &mut ~[Comment]) {
debug!(">>> consume comment");
let mut comments: ~[Comment] = ~[];
let mut literals: ~[Literal] = ~[];
let mut first_read: bool = true;
- while !is_eof(rdr) {
+ while !is_eof(&rdr) {
loop {
let mut code_to_the_left = !first_read;
- consume_non_eol_whitespace(rdr);
+ consume_non_eol_whitespace(&rdr);
if rdr.curr.get() == '\n' {
code_to_the_left = false;
- consume_whitespace_counting_blank_lines(rdr, &mut comments);
+ consume_whitespace_counting_blank_lines(&rdr, &mut comments);
}
- while peeking_at_comment(rdr) {
- consume_comment(rdr, code_to_the_left, &mut comments);
- consume_whitespace_counting_blank_lines(rdr, &mut comments);
+ while peeking_at_comment(&rdr) {
+ consume_comment(&rdr, code_to_the_left, &mut comments);
+ consume_whitespace_counting_blank_lines(&rdr, &mut comments);
}
break;
}
//discard, and look ahead; we're working with internal state
let TokenAndSpan {tok: tok, sp: sp} = rdr.peek();
if token::is_lit(&tok) {
- with_str_from(rdr, bstart, |s| {
+ with_str_from(&rdr, bstart, |s| {
debug!("tok lit: {}", s);
literals.push(Literal {lit: s.to_owned(), pos: sp.lo});
})
use codemap::{BytePos, CharPos, CodeMap, Pos, Span};
use codemap;
use diagnostic::SpanHandler;
-use ext::tt::transcribe::{tt_next_token};
-use ext::tt::transcribe::{dup_tt_reader};
+use ext::tt::transcribe::{dup_tt_reader, tt_next_token};
use parse::token;
use parse::token::{str_to_ident};
pub use ext::tt::transcribe::{TtReader, new_tt_reader};
pub trait Reader {
- fn is_eof(@self) -> bool;
- fn next_token(@self) -> TokenAndSpan;
- fn fatal(@self, ~str) -> !;
- fn span_diag(@self) -> @SpanHandler;
- fn peek(@self) -> TokenAndSpan;
- fn dup(@self) -> @Reader;
+ fn is_eof(&self) -> bool;
+ fn next_token(&self) -> TokenAndSpan;
+ fn fatal(&self, ~str) -> !;
+ fn span_diag(&self) -> @SpanHandler;
+ fn peek(&self) -> TokenAndSpan;
+ fn dup(&self) -> ~Reader:;
}
#[deriving(Clone, Eq)]
pub fn new_string_reader(span_diagnostic: @SpanHandler,
filemap: @codemap::FileMap)
- -> @StringReader {
+ -> StringReader {
let r = new_low_level_string_reader(span_diagnostic, filemap);
- string_advance_token(r); /* fill in peek_* */
- return r;
+ string_advance_token(&r); /* fill in peek_* */
+ r
}
/* For comments.rs, which hackily pokes into 'pos' and 'curr' */
pub fn new_low_level_string_reader(span_diagnostic: @SpanHandler,
filemap: @codemap::FileMap)
- -> @StringReader {
+ -> StringReader {
// Force the initial reader bump to start on a fresh line
let initial_char = '\n';
- let r = @StringReader {
+ let r = StringReader {
span_diagnostic: span_diagnostic,
pos: Cell::new(filemap.start_pos),
last_pos: Cell::new(filemap.start_pos),
peek_tok: RefCell::new(token::EOF),
peek_span: RefCell::new(codemap::DUMMY_SP),
};
- bump(r);
- return r;
+ bump(&r);
+ r
}
// duplicating the string reader is probably a bad idea, in
// that using them will cause interleaved pushes of line
// offsets to the underlying filemap...
-fn dup_string_reader(r: @StringReader) -> @StringReader {
- @StringReader {
+fn dup_string_reader(r: &StringReader) -> StringReader {
+ StringReader {
span_diagnostic: r.span_diagnostic,
pos: Cell::new(r.pos.get()),
last_pos: Cell::new(r.last_pos.get()),
}
impl Reader for StringReader {
- fn is_eof(@self) -> bool { is_eof(self) }
+ fn is_eof(&self) -> bool { is_eof(self) }
// return the next token. EFFECT: advances the string_reader.
- fn next_token(@self) -> TokenAndSpan {
+ fn next_token(&self) -> TokenAndSpan {
let ret_val = {
let mut peek_tok = self.peek_tok.borrow_mut();
TokenAndSpan {
string_advance_token(self);
ret_val
}
- fn fatal(@self, m: ~str) -> ! {
+ fn fatal(&self, m: ~str) -> ! {
self.span_diagnostic.span_fatal(self.peek_span.get(), m)
}
- fn span_diag(@self) -> @SpanHandler { self.span_diagnostic }
- fn peek(@self) -> TokenAndSpan {
+ fn span_diag(&self) -> @SpanHandler { self.span_diagnostic }
+ fn peek(&self) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy!
TokenAndSpan {
tok: self.peek_tok.get(),
sp: self.peek_span.get(),
}
}
- fn dup(@self) -> @Reader { dup_string_reader(self) as @Reader }
+ fn dup(&self) -> ~Reader: { ~dup_string_reader(self) as ~Reader: }
}
impl Reader for TtReader {
- fn is_eof(@self) -> bool {
+ fn is_eof(&self) -> bool {
let cur_tok = self.cur_tok.borrow();
*cur_tok.get() == token::EOF
}
- fn next_token(@self) -> TokenAndSpan {
+ fn next_token(&self) -> TokenAndSpan {
let r = tt_next_token(self);
debug!("TtReader: r={:?}", r);
return r;
}
- fn fatal(@self, m: ~str) -> ! {
+ fn fatal(&self, m: ~str) -> ! {
self.sp_diag.span_fatal(self.cur_span.get(), m);
}
- fn span_diag(@self) -> @SpanHandler { self.sp_diag }
- fn peek(@self) -> TokenAndSpan {
+ fn span_diag(&self) -> @SpanHandler { self.sp_diag }
+ fn peek(&self) -> TokenAndSpan {
TokenAndSpan {
tok: self.cur_tok.get(),
sp: self.cur_span.get(),
}
}
- fn dup(@self) -> @Reader { dup_tt_reader(self) as @Reader }
+ fn dup(&self) -> ~Reader: { ~dup_tt_reader(self) as ~Reader: }
}
// report a lexical error spanning [`from_pos`, `to_pos`)
-fn fatal_span(rdr: @StringReader,
+fn fatal_span(rdr: &StringReader,
from_pos: BytePos,
to_pos: BytePos,
m: ~str)
// report a lexical error spanning [`from_pos`, `to_pos`), appending an
// escaped character to the error message
-fn fatal_span_char(rdr: @StringReader,
+fn fatal_span_char(rdr: &StringReader,
from_pos: BytePos,
to_pos: BytePos,
m: ~str,
// report a lexical error spanning [`from_pos`, `to_pos`), appending the
// offending string to the error message
-fn fatal_span_verbose(rdr: @StringReader,
+fn fatal_span_verbose(rdr: &StringReader,
from_pos: BytePos,
to_pos: BytePos,
m: ~str)
// EFFECT: advance peek_tok and peek_span to refer to the next token.
// EFFECT: update the interner, maybe.
-fn string_advance_token(r: @StringReader) {
+fn string_advance_token(r: &StringReader) {
match consume_whitespace_and_comments(r) {
Some(comment) => {
r.peek_span.set(comment.sp);
/// up to but excluding `rdr.last_pos`, meaning the slice does not include
/// the character `rdr.curr`.
pub fn with_str_from<T>(
- rdr: @StringReader,
+ rdr: &StringReader,
start: BytePos,
f: |s: &str| -> T)
-> T {
/// Calls `f` with astring slice of the source text spanning from `start`
/// up to but excluding `end`.
fn with_str_from_to<T>(
- rdr: @StringReader,
+ rdr: &StringReader,
start: BytePos,
end: BytePos,
f: |s: &str| -> T)
rdr.curr.set(unsafe { transmute(-1u32) }); // FIXME: #8971: unsound
}
}
-pub fn is_eof(rdr: @StringReader) -> bool {
+pub fn is_eof(rdr: &StringReader) -> bool {
rdr.curr.get() == unsafe { transmute(-1u32) } // FIXME: #8971: unsound
}
-pub fn nextch(rdr: @StringReader) -> char {
+pub fn nextch(rdr: &StringReader) -> char {
let offset = byte_offset(rdr, rdr.pos.get()).to_uint();
if offset < (rdr.filemap.src).len() {
return rdr.filemap.src.char_at(offset);
// EFFECT: eats whitespace and comments.
// returns a Some(sugared-doc-attr) if one exists, None otherwise.
-fn consume_whitespace_and_comments(rdr: @StringReader)
+fn consume_whitespace_and_comments(rdr: &StringReader)
-> Option<TokenAndSpan> {
while is_whitespace(rdr.curr.get()) { bump(rdr); }
return consume_any_line_comment(rdr);
// PRECONDITION: rdr.curr is not whitespace
// EFFECT: eats any kind of comment.
// returns a Some(sugared-doc-attr) if one exists, None otherwise
-fn consume_any_line_comment(rdr: @StringReader)
+fn consume_any_line_comment(rdr: &StringReader)
-> Option<TokenAndSpan> {
if rdr.curr.get() == '/' {
match nextch(rdr) {
}
// might return a sugared-doc-attr
-fn consume_block_comment(rdr: @StringReader) -> Option<TokenAndSpan> {
+fn consume_block_comment(rdr: &StringReader) -> Option<TokenAndSpan> {
// block comments starting with "/**" or "/*!" are doc-comments
let is_doc_comment = rdr.curr.get() == '*' || rdr.curr.get() == '!';
let start_bpos = rdr.pos.get() - BytePos(if is_doc_comment {3} else {2});
if res.is_some() { res } else { consume_whitespace_and_comments(rdr) }
}
-fn scan_exponent(rdr: @StringReader, start_bpos: BytePos) -> Option<~str> {
+fn scan_exponent(rdr: &StringReader, start_bpos: BytePos) -> Option<~str> {
let mut c = rdr.curr.get();
let mut rslt = ~"";
if c == 'e' || c == 'E' {
} else { return None::<~str>; }
}
-fn scan_digits(rdr: @StringReader, radix: uint) -> ~str {
+fn scan_digits(rdr: &StringReader, radix: uint) -> ~str {
let mut rslt = ~"";
loop {
let c = rdr.curr.get();
};
}
-fn check_float_base(rdr: @StringReader, start_bpos: BytePos, last_bpos: BytePos,
+fn check_float_base(rdr: &StringReader, start_bpos: BytePos, last_bpos: BytePos,
base: uint) {
match base {
16u => fatal_span(rdr, start_bpos, last_bpos,
}
}
-fn scan_number(c: char, rdr: @StringReader) -> token::Token {
+fn scan_number(c: char, rdr: &StringReader) -> token::Token {
let mut num_str;
let mut base = 10u;
let mut c = c;
}
}
-fn scan_numeric_escape(rdr: @StringReader, n_hex_digits: uint) -> char {
+fn scan_numeric_escape(rdr: &StringReader, n_hex_digits: uint) -> char {
let mut accum_int = 0;
let mut i = n_hex_digits;
let start_bpos = rdr.last_pos.get();
// return the next token from the string
// EFFECT: advances the input past that token
// EFFECT: updates the interner
-fn next_token_inner(rdr: @StringReader) -> token::Token {
+fn next_token_inner(rdr: &StringReader) -> token::Token {
let c = rdr.curr.get();
if ident_start(c) && nextch(rdr) != '"' && nextch(rdr) != '#' {
// Note: r as in r" or r#" is part of a raw string literal,
if is_dec_digit(c) {
return scan_number(c, rdr);
}
- fn binop(rdr: @StringReader, op: token::BinOp) -> token::Token {
+ fn binop(rdr: &StringReader, op: token::BinOp) -> token::Token {
bump(rdr);
if rdr.curr.get() == '=' {
bump(rdr);
}
}
-fn consume_whitespace(rdr: @StringReader) {
+fn consume_whitespace(rdr: &StringReader) {
while is_whitespace(rdr.curr.get()) && !is_eof(rdr) { bump(rdr); }
}
// represents a testing reader (incl. both reader and interner)
struct Env {
- string_reader: @StringReader
+ string_reader: StringReader
}
// open a string reader for the given string
fn setup(teststr: ~str) -> Env {
let cm = CodeMap::new();
let fm = cm.new_filemap(~"zebra.rs", teststr);
- let span_handler =
- diagnostic::mk_span_handler(diagnostic::mk_handler(None),@cm);
+ let span_handler = diagnostic::mk_span_handler(diagnostic::mk_handler(), @cm);
Env {
string_reader: new_string_reader(span_handler,fm)
}
use ast;
use codemap::{Span, CodeMap, FileMap};
use codemap;
-use diagnostic::{SpanHandler, mk_span_handler, mk_handler, Emitter};
+use diagnostic::{SpanHandler, mk_span_handler, mk_handler};
use parse::attr::ParserAttr;
use parse::parser::Parser;
included_mod_stack: RefCell<~[Path]>,
}
-pub fn new_parse_sess(demitter: Option<@Emitter>) -> @ParseSess {
+pub fn new_parse_sess() -> @ParseSess {
let cm = @CodeMap::new();
@ParseSess {
cm: cm,
- span_diagnostic: mk_span_handler(mk_handler(demitter), cm),
+ span_diagnostic: mk_span_handler(mk_handler(), cm),
included_mod_stack: RefCell::new(~[]),
}
}
// parsing tt's probably shouldn't require a parser at all.
let cfg = ~[];
let srdr = lexer::new_string_reader(sess.span_diagnostic, filemap);
- let mut p1 = Parser(sess, cfg, srdr as @lexer::Reader);
+ let mut p1 = Parser(sess, cfg, ~srdr);
p1.parse_all_token_trees()
}
tts: ~[ast::TokenTree],
cfg: ast::CrateConfig) -> Parser {
let trdr = lexer::new_tt_reader(sess.span_diagnostic, None, tts);
- Parser(sess, cfg, trdr as @lexer::Reader)
+ Parser(sess, cfg, ~trdr)
}
// abort if necessary
use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
use ast::{StructVariantKind, BiSub};
use ast::StrStyle;
-use ast::{SelfBox, SelfRegion, SelfStatic, SelfUniq, SelfValue};
+use ast::{SelfRegion, SelfStatic, SelfUniq, SelfValue};
use ast::{TokenTree, TraitMethod, TraitRef, TTDelim, TTSeq, TTTok};
use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
use ast::{TypeField, TyFixedLengthVec, TyClosure, TyBareFn, TyTypeof};
/* ident is handled by common.rs */
-pub fn Parser(sess: @ParseSess, cfg: ast::CrateConfig, rdr: @Reader)
+pub fn Parser(sess: @ParseSess, cfg: ast::CrateConfig, rdr: ~Reader:)
-> Parser {
let tok0 = rdr.next_token();
let interner = get_ident_interner();
tokens_consumed: uint,
restriction: restriction,
quote_depth: uint, // not (yet) related to the quasiquoter
- reader: @Reader,
+ reader: ~Reader:,
interner: @token::IdentInterner,
/// The set of seen errors about obsolete syntax. Used to suppress
/// extra detail when the same error is seen twice
// that may have a self type.
fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
-> (ExplicitSelf, P<FnDecl>) {
- fn maybe_parse_explicit_self(explicit_self: ast::ExplicitSelf_,
- p: &mut Parser)
- -> ast::ExplicitSelf_ {
- // We need to make sure it isn't a type
- if p.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
- p.bump();
- p.expect_self_ident();
- explicit_self
- } else {
- SelfStatic
- }
- }
-
fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
-> ast::ExplicitSelf_ {
// The following things are possible to see here:
token::BINOP(token::AND) => {
maybe_parse_borrowed_explicit_self(self)
}
- token::AT => {
- maybe_parse_explicit_self(SelfBox, self)
- }
token::TILDE => {
- maybe_parse_explicit_self(SelfUniq, self)
+ // We need to make sure it isn't a type
+ if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
+ self.bump();
+ self.expect_self_ident();
+ SelfUniq
+ } else {
+ SelfStatic
+ }
}
token::IDENT(..) if self.is_self_ident() => {
self.bump();
use std::io::MemWriter;
// The &mut State is stored here to prevent recursive type.
-pub enum AnnNode<'a,'b> {
- NodeBlock(&'b mut State, &'a ast::Block),
- NodeItem(&'b mut State, &'a ast::Item),
- NodeExpr(&'b mut State, &'a ast::Expr),
- NodePat(&'b mut State, &'a ast::Pat),
+pub enum AnnNode<'a, 'b> {
+ NodeBlock(&'a mut State<'a>, &'b ast::Block),
+ NodeItem(&'a mut State<'a>, &'b ast::Item),
+ NodeExpr(&'a mut State<'a>, &'b ast::Expr),
+ NodePat(&'a mut State<'a>, &'b ast::Pat),
}
pub trait PpAnn {
cur_lit: uint,
}
-pub struct State {
+pub struct State<'a> {
s: pp::Printer,
cm: Option<@CodeMap>,
intr: @token::IdentInterner,
literals: Option<~[comments::Literal]>,
cur_cmnt_and_lit: CurrentCommentAndLiteral,
boxes: RefCell<~[pp::Breaks]>,
- ann: @PpAnn
+ ann: &'a PpAnn
}
pub fn ibox(s: &mut State, u: uint) -> io::IoResult<()> {
pp::end(&mut s.s)
}
-pub fn rust_printer(writer: ~io::Writer, intr: @IdentInterner) -> State {
- return rust_printer_annotated(writer, intr, @NoAnn as @PpAnn);
+pub fn rust_printer(writer: ~io::Writer, intr: @IdentInterner) -> State<'static> {
+ rust_printer_annotated(writer, intr, &NoAnn)
}
-pub fn rust_printer_annotated(writer: ~io::Writer,
- intr: @IdentInterner,
- ann: @PpAnn)
- -> State {
- return State {
+pub fn rust_printer_annotated<'a>(writer: ~io::Writer,
+ intr: @IdentInterner,
+ ann: &'a PpAnn)
+ -> State<'a> {
+ State {
s: pp::mk_printer(writer, default_columns),
cm: None,
intr: intr,
},
boxes: RefCell::new(~[]),
ann: ann
- };
+ }
}
pub static indent_unit: uint = 4u;
filename: ~str,
input: &mut io::Reader,
out: ~io::Writer,
- ann: @PpAnn,
+ ann: &PpAnn,
is_expanded: bool) -> io::IoResult<()> {
let (cmnts, lits) = comments::gather_comments_and_literals(
span_diagnostic,
if_ok!(print_mutability(s, m));
if_ok!(word(&mut s.s, "self"));
}
- ast::SelfBox => {
- if_ok!(word(&mut s.s, "@self"));
- }
}
return Ok(true);
}
// map a string to tts, using a made-up filename: return both the TokenTree's
// and the ParseSess
pub fn string_to_tts_and_sess (source_str : ~str) -> (~[ast::TokenTree], @ParseSess) {
- let ps = new_parse_sess(None);
+ let ps = new_parse_sess();
(filemap_to_tts(ps,string_to_filemap(ps,source_str,~"bogofile")),ps)
}
}
pub fn string_to_parser_and_sess(source_str: ~str) -> (Parser,@ParseSess) {
- let ps = new_parse_sess(None);
+ let ps = new_parse_sess();
(new_parser_from_source_str(ps,~[],~"bogofile",source_str),ps)
}
explicit_self: &ExplicitSelf,
env: E) {
match explicit_self.node {
- SelfStatic | SelfValue | SelfBox | SelfUniq => {}
+ SelfStatic | SelfValue | SelfUniq => {}
SelfRegion(ref lifetime, _) => {
visitor.visit_opt_lifetime_ref(explicit_self.span, lifetime, env)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
#[crate_id="a"];
#[crate_type = "lib"];
pub trait i<T> { }
-pub fn f<T>() -> @i<T> {
+pub fn f<T>() -> ~i<T> {
impl<T> i<T> for () { }
- @() as @i<T>
+ ~() as ~i<T>
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait Foo {
fn borrowed<'a>(&'a self) -> &'a ();
}
x.borrowed()
}
-fn managed_receiver(x: @Foo) -> &() {
- x.borrowed() //~ ERROR cannot root managed value long enough
-}
-
-fn managed_receiver_1(x: @Foo) {
- *x.borrowed()
-}
-
fn owned_receiver(x: ~Foo) -> &() {
x.borrowed() //~ ERROR borrowed value does not live long enough
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait Foo {
fn borrowed(&self);
fn borrowed_mut(&mut self);
x.borrowed_mut();
}
-fn managed_receiver(x: @Foo) {
- x.borrowed();
- x.borrowed_mut(); //~ ERROR cannot borrow
-}
-
fn owned_receiver(x: ~Foo) {
x.borrowed();
x.borrowed_mut(); //~ ERROR cannot borrow
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait noisy {
fn speak(&self);
}
}
fn main() {
- let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy;
+ let nyan: ~noisy = ~cat(0, 2, ~"nyan") as ~noisy;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
-// error-pattern: type `@Foo:'static` does not implement any method in scope named `foo`
+// error-pattern: type `&Foo<no-bounds>` does not implement any method in scope named `foo`
trait Foo {
fn foo(~self);
}
fn main() {
- (@5 as @Foo).foo();
+ (&5 as &Foo).foo();
}
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-trait foo { fn foo(&self); }
-
-fn to_foo<T:Clone + foo>(t: T) -> @foo {
- @t as @foo
- //~^ ERROR value may contain references; add `'static` bound
- //~^^ ERROR cannot pack type
- //~^^^ ERROR value may contain references
-}
-
-fn to_foo2<T:Clone + foo + 'static>(t: T) -> @foo {
- @t as @foo
-}
-
-fn main() {}
@2; //~ ERROR type uses managed
- fn f(_: @Clone) {} //~ ERROR type uses managed
-
~2; //~ ERROR type uses owned
~[1]; //~ ERROR type uses owned
//~^ ERROR type uses owned
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
use std::container::Map;
use std::hashmap::HashMap;
// Test that trait types printed in error msgs include the type arguments.
fn main() {
- let x: @HashMap<~str, ~str> = @HashMap::new();
- let x: @Map<~str, ~str> = x;
- let y: @Map<uint, ~str> = @x;
- //~^ ERROR failed to find an implementation of trait std::container::Map<uint,~str> for @std::container::Map<~str,~str>:'static
+ let x: ~HashMap<~str, ~str> = ~HashMap::new();
+ let x: ~Map<~str, ~str> = x;
+ let y: ~Map<uint, ~str> = ~x;
+ //~^ ERROR failed to find an implementation of trait std::container::Map<uint,~str> for ~std::container::Map<~str,~str>:Send
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
-// Test that an object type `@Foo` is not considered to implement the
+// Test that an object type `~Foo` is not considered to implement the
// trait `Foo`. Issue #5087.
trait Foo {}
fn take_foo<F:Foo>(f: F) {}
-fn take_object(f: @Foo) { take_foo(f); } //~ ERROR failed to find an implementation of trait
+fn take_object(f: ~Foo) { take_foo(f); } //~ ERROR failed to find an implementation of trait
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait Foo {
fn borrowed(&self);
fn borrowed_mut(&mut self);
- fn managed(@self);
-
fn owned(~self);
}
fn borrowed_receiver(x: &Foo) {
x.borrowed();
x.borrowed_mut(); // See [1]
- x.managed(); //~ ERROR does not implement any method
x.owned(); //~ ERROR does not implement any method
}
fn borrowed_mut_receiver(x: &mut Foo) {
x.borrowed();
x.borrowed_mut();
- x.managed(); //~ ERROR does not implement any method
- x.owned(); //~ ERROR does not implement any method
-}
-
-fn managed_receiver(x: @Foo) {
- x.borrowed();
- x.borrowed_mut(); // See [1]
- x.managed();
x.owned(); //~ ERROR does not implement any method
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
struct ctxt { v: uint }
trait get_ctxt {
}
-fn get_v(gc: @get_ctxt) -> uint {
+fn get_v(gc: ~get_ctxt) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
- assert_eq!(get_v(@hc as @get_ctxt), 22u);
+ assert_eq!(get_v(~hc as ~get_ctxt), 22u);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait add {
fn plus(&self, x: Self) -> Self;
}
-fn do_add(x: @add, y: @add) -> @add {
+fn do_add(x: ~add, y: ~add) -> ~add {
x.plus(y) //~ ERROR cannot call a method whose type contains a self-type through an object
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// Tests for "default" bounds inferred for traits with no bounds list.
-trait Foo {
-}
+trait Foo {}
fn a(_x: ~Foo) { // should be same as ~Foo:Send
}
-fn b(_x: @Foo) { // should be same as ~Foo:'static
-}
-
-fn c(_x: &'static Foo) { // should be same as &'static Foo:'static
+fn b(_x: &'static Foo) { // should be same as &'static Foo:'static
}
-fn d(x: ~Foo:Freeze) {
+fn c(x: ~Foo:Freeze) {
a(x); //~ ERROR expected bounds `Send`
}
-fn e(x: @Foo:Freeze) {
+fn d(x: &'static Foo:Freeze) {
b(x); //~ ERROR expected bounds `'static`
}
-fn f(x: &'static Foo:Freeze) {
- c(x); //~ ERROR expected bounds `'static`
-}
-
-fn main() { }
+fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
struct Struct {
person: &'static str
}
}
fn main() {
- let s: @Trait<int> = @Struct { person: "Fred" }; //~ ERROR expected Trait<int>, but found Trait<&'static str>
+ let s: ~Trait<int> = ~Struct { person: "Fred" }; //~ ERROR expected Trait<int>, but found Trait<&'static str>
//~^ ERROR expected Trait<int>, but found Trait<&'static str>
s.f(1);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
struct Struct {
person: &'static str
}
fn main() {
let person = ~"Fred";
let person: &str = person; //~ ERROR borrowed value does not live long enough
- let s: @Trait<&'static str> = @Struct { person: person };
+ let s: ~Trait<&'static str> = ~Struct { person: person };
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait bar { fn dup(&self) -> Self; fn blah<X>(&self); }
impl bar for int { fn dup(&self) -> int { *self } fn blah<X>(&self) {} }
impl bar for uint { fn dup(&self) -> uint { *self } fn blah<X>(&self) {} }
fn main() {
10i.dup::<int>(); //~ ERROR does not take type parameters
10i.blah::<int, int>(); //~ ERROR incorrect number of type parameters
- (@10 as @bar).dup(); //~ ERROR contains a self-type
+ (~10 as ~bar).dup(); //~ ERROR contains a self-type
}
// check:$15 = -10.5
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {x = -1}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12.5
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {x = -1}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print *arg2
-// check:$21 = {-14, 14}
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {x = -1}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print *arg2
-// check:$24 = {-16, 16.5}
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct Struct<T> {
x: T
}
zzz();
arg1
}
-
- fn self_managed<T2>(@self, arg1: int, arg2: T2) -> int {
- zzz();
- arg1
- }
}
fn main() {
let _ = owned.self_by_ref(-5, -6_i32);
let _ = owned.self_by_val(-7, -8_i64);
let _ = owned.self_owned(-9, -10.5_f32);
-
- let managed = @Struct { x: -1_i16 };
- let _ = managed.self_by_ref(-11, -12.5_f64);
- let _ = managed.self_by_val(-13, &(-14, 14));
- let _ = managed.self_managed(-15, &(-16, 16.5));
}
fn zzz() {()}
// check:$15 = -10
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {{Variant2, [...]}, {Variant2, 117901063}}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {{Variant2, [...]}, {Variant2, 117901063}}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print arg2
-// check:$21 = -14
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {{Variant2, [...]}, {Variant2, 117901063}}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print arg2
-// check:$24 = -16
-// debugger:continue
-
-#[feature(managed_boxes)];
#[feature(struct_variant)];
enum Enum {
zzz();
arg1 + arg2
}
-
- fn self_managed(@self, arg1: int, arg2: int) -> int {
- zzz();
- arg1 + arg2
- }
}
fn main() {
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
-
- let managed = @Variant2(117901063);
- let _ = managed.self_by_ref(-11, -12);
- let _ = managed.self_by_val(-13, -14);
- let _ = managed.self_managed(-15, -16);
}
fn zzz() {()}
// check:$15 = -10
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {x = -1}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {x = -1}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print arg2
-// check:$21 = -14
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {x = -1}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print arg2
-// check:$24 = -16
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct Struct<T> {
x: T
}
zzz();
arg1 + arg2
}
-
- fn self_managed(@self, arg1: int, arg2: int) -> int {
- zzz();
- arg1 + arg2
- }
}
fn main() {
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
-
- let managed = @Struct { x: -1_i16 };
- let _ = managed.self_by_ref(-11, -12);
- let _ = managed.self_by_val(-13, -14);
- let _ = managed.self_managed(-15, -16);
}
fn zzz() {()}
// check:$15 = -10
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {x = 300}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {x = 300}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print arg2
-// check:$21 = -14
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {x = 300}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print arg2
-// check:$24 = -16
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct Struct {
x: int
}
zzz();
self.x + arg1 + arg2
}
-
- fn self_managed(@self, arg1: int, arg2: int) -> int {
- zzz();
- self.x + arg1 + arg2
- }
}
fn main() {
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
-
- let managed = @Struct { x: 300 };
- let _ = managed.self_by_ref(-11, -12);
- let _ = managed.self_by_val(-13, -14);
- let _ = managed.self_managed(-15, -16);
}
fn zzz() {()}
// check:$15 = -10
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {x = 300}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {x = 300}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print arg2
-// check:$21 = -14
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {x = 300}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print arg2
-// check:$24 = -16
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct Struct {
x: int
}
fn self_by_ref(&self, arg1: int, arg2: int) -> int;
fn self_by_val(self, arg1: int, arg2: int) -> int;
fn self_owned(~self, arg1: int, arg2: int) -> int;
- fn self_managed(@self, arg1: int, arg2: int) -> int;
}
impl Trait for Struct {
zzz();
self.x + arg1 + arg2
}
-
- fn self_managed(@self, arg1: int, arg2: int) -> int {
- zzz();
- self.x + arg1 + arg2
- }
}
fn main() {
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
-
- let managed = @Struct { x: 300 };
- let _ = managed.self_by_ref(-11, -12);
- let _ = managed.self_by_val(-13, -14);
- let _ = managed.self_managed(-15, -16);
}
fn zzz() {()}
// check:$15 = -10
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {300, -300.5}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {300, -300.5}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print arg2
-// check:$21 = -14
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {300, -300.5}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print arg2
-// check:$24 = -16
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct TupleStruct(int, f64);
impl TupleStruct {
zzz();
arg1 + arg2
}
-
- fn self_managed(@self, arg1: int, arg2: int) -> int {
- zzz();
- arg1 + arg2
- }
}
fn main() {
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
-
- let managed = @TupleStruct(300, -300.5);
- let _ = managed.self_by_ref(-11, -12);
- let _ = managed.self_by_val(-13, -14);
- let _ = managed.self_managed(-15, -16);
}
fn zzz() {()}
// check:$15 = -10
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {x = 300}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {x = 300}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print arg2
-// check:$21 = -14
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {x = 300}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print arg2
-// check:$24 = -16
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct Struct {
x: int
}
zzz();
arg1 + arg2
}
-
- fn self_managed(@self, arg1: int, arg2: int) -> int {
- zzz();
- arg1 + arg2
- }
}
impl Trait for Struct {}
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
-
- let managed = @Struct { x: 300 };
- let _ = managed.self_by_ref(-11, -12);
- let _ = managed.self_by_val(-13, -14);
- let _ = managed.self_managed(-15, -16);
}
fn zzz() {()}
// check:$15 = -10.5
// debugger:continue
-// MANAGED BY REF
-// debugger:finish
-// debugger:print *self
-// check:$16 = {x = 897}
-// debugger:print arg1
-// check:$17 = -11
-// debugger:print arg2
-// check:$18 = -12.5
-// debugger:continue
-
-// MANAGED BY VAL
-// debugger:finish
-// debugger:print self
-// check:$19 = {x = 897}
-// debugger:print arg1
-// check:$20 = -13
-// debugger:print *arg2
-// check:$21 = {-14, 14}
-// debugger:continue
-
-// MANAGED SELF
-// debugger:finish
-// debugger:print self->val
-// check:$22 = {x = 897}
-// debugger:print arg1
-// check:$23 = -15
-// debugger:print *arg2
-// check:$24 = {-16, 16.5}
-// debugger:continue
-
-#[feature(managed_boxes)];
-
struct Struct {
x: int
}
zzz();
arg1
}
-
- fn self_managed<T>(@self, arg1: int, arg2: T) -> int {
- zzz();
- arg1
- }
}
impl Trait for Struct {}
let _ = owned.self_by_ref(-5, -6_i32);
let _ = owned.self_by_val(-7, -8_i64);
let _ = owned.self_owned(-9, -10.5_f32);
-
- let managed = @Struct { x: 897 };
- let _ = managed.self_by_ref(-11, -12.5_f64);
- let _ = managed.self_by_val(-13, &(-14, 14));
- let _ = managed.self_managed(-15, &(-16, 16.5));
}
fn zzz() {()}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// xfail-android: FIXME(#10381)
// compile-flags:-Z extra-debug-info
fn main() {
let stack_struct = Struct { a:0, b: 1.0 };
let reference: &Trait = &stack_struct as &Trait;
- let managed: @Trait = @Struct { a:2, b: 3.0 } as @Trait;
let unique: ~Trait = ~Struct { a:2, b: 3.0 } as ~Trait;
}
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-// error-pattern:fail
-
-fn failfn() {
- fail!();
-}
-
-trait i {
- fn foo(&self);
-}
-
-impl i for ~int {
- fn foo(&self) { }
-}
-
-fn main() {
- let x = @~0 as @i;
- failfn();
- error!("{:?}", x);
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
struct pair<A,B> {
a: A, b: B
}
}
}
-fn f<A:Clone + 'static>(a: A, b: u16) -> @Invokable<A> {
- @Invoker {
+fn f<A:Clone + 'static>(a: A, b: u16) -> ~Invokable:<A> {
+ ~Invoker {
a: a,
b: b,
- } as @Invokable<A>
+ } as ~Invokable:<A>
}
pub fn main() {
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-use std::cell::RefCell;
-
-struct Pair<A,B> {
- a: A, b: B
-}
-
-struct RecEnum<A>(Rec<A>);
-struct Rec<A> {
- val: A,
- rec: Option<@RefCell<RecEnum<A>>>
-}
-
-fn make_cycle<A:'static>(a: A) {
- let g: @RefCell<RecEnum<A>> = @RefCell::new(RecEnum(Rec {val: a, rec: None}));
- {
- let mut gb = g.borrow_mut();
- let gg = gb.get();
- let RecEnum(ref mut gg) = *gg;
- gg.rec = Some(g);
- }
-}
-
-struct Invoker<A,B> {
- a: A,
- b: B,
-}
-
-trait Invokable<A,B> {
- fn f(&self) -> (A, B);
-}
-
-impl<A:Clone,B:Clone> Invokable<A,B> for Invoker<A,B> {
- fn f(&self) -> (A, B) {
- (self.a.clone(), self.b.clone())
- }
-}
-
-fn f<A:Send + Clone + 'static,
- B:Send + Clone + 'static>(
- a: A,
- b: B)
- -> @Invokable<A,B> {
- @Invoker {
- a: a,
- b: b,
- } as @Invokable<A,B>
-}
-
-pub fn main() {
- let x = 22_u8;
- let y = 44_u64;
- let z = f(~x, y);
- make_cycle(z);
- let (a, b) = z.f();
- info!("a={} b={}", *a as uint, b as uint);
- assert_eq!(*a, x);
- assert_eq!(b, y);
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait double {
- fn double(@self) -> uint;
+ fn double(~self) -> uint;
}
impl double for uint {
- fn double(@self) -> uint { *self * 2u }
+ fn double(~self) -> uint { *self * 2u }
}
pub fn main() {
- let x = @(@3u as @double);
+ let x = ~(~3u as ~double);
assert_eq!(x.double(), 6u);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait double {
- fn double(@self) -> uint;
+ fn double(~self) -> uint;
}
-impl double for @uint {
- fn double(@self) -> uint { **self * 2u }
+impl double for ~uint {
+ fn double(~self) -> uint { **self * 2u }
}
pub fn main() {
- let x = @@@@@3u;
+ let x = ~~~~~3u;
assert_eq!(x.double(), 6u);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait double {
- fn double(@self) -> uint;
+ fn double(~self) -> uint;
}
impl double for uint {
- fn double(@self) -> uint { *self * 2u }
+ fn double(~self) -> uint { *self * 2u }
}
pub fn main() {
- let x = @@3u;
+ let x = ~~3u;
assert_eq!(x.double(), 6u);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait double {
- fn double(@self) -> uint;
+ fn double(~self) -> uint;
}
impl double for uint {
- fn double(@self) -> uint { *self * 2u }
+ fn double(~self) -> uint { *self * 2u }
}
pub fn main() {
- let x = @3u;
+ let x = ~3u;
assert_eq!(x.double(), 6u);
}
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-trait Foo {
- fn foo(@self);
-}
-
-impl Foo for int {
- fn foo(@self) {
- println!("Hello world!");
- }
-}
-
-pub fn main() {
- let x = @3 as @Foo;
- x.foo();
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// xfail-fast
// aux-build:cci_class_cast.rs
extern mod cci_class_cast;
use std::to_str::ToStr;
use cci_class_cast::kitty::cat;
-fn print_out(thing: @ToStr, expected: ~str) {
+fn print_out(thing: ~ToStr, expected: ~str) {
let actual = thing.to_str();
info!("{}", actual);
assert_eq!(actual, expected);
}
pub fn main() {
- let nyan : @ToStr = @cat(0u, 2, ~"nyan") as @ToStr;
+ let nyan: ~ToStr = ~cat(0u, 2, ~"nyan") as ~ToStr;
print_out(nyan, ~"nyan");
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// xfail-fast
struct cat {
meows : uint,
}
}
-fn print_out(thing: @ToStr, expected: ~str) {
+fn print_out(thing: ~ToStr, expected: ~str) {
let actual = thing.to_str();
info!("{}", actual);
assert_eq!(actual, expected);
}
pub fn main() {
- let nyan : @ToStr = @cat(0u, 2, ~"nyan") as @ToStr;
+ let nyan: ~ToStr = ~cat(0u, 2, ~"nyan") as ~ToStr;
print_out(nyan, ~"nyan");
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// If we use GEPi rathern than GEP_tup_like when
// storing closure data (as we used to do), the u64 would
// overwrite the u16.
}
}
-fn f<A:Clone + 'static>(a: A, b: u16) -> @Invokable<A> {
- @Invoker {
+fn f<A:Clone + 'static>(a: A, b: u16) -> ~Invokable:<A> {
+ ~Invoker {
a: a,
b: b,
- } as @Invokable<A>
+ } as ~Invokable:<A>
}
pub fn main() {
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-trait Foo {
- fn f(@self);
-}
-
-struct S {
- x: int
-}
-
-impl Foo for S {
- fn f(@self) {
- assert_eq!(self.x, 3);
- }
-}
-
-pub fn main() {
- let x = @S { x: 3 };
- let y = x as @Foo;
- y.f();
- y.f();
- y.f();
- y.f();
-}
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-trait Foo {
- fn f(&self);
-}
-
-struct S {
- x: int
-}
-
-impl Foo for S {
- fn f(&self) {
- assert_eq!(self.x, 3);
- }
-}
-
-pub fn main() {
- let x = @S { x: 3 };
- let y = x as @Foo;
- y.f();
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
static tau: f64 = 2.0*3.14159265358979323;
struct Point {x: f64, y: f64}
#[deriving(Clone)]
struct A {
- a: @int
+ a: int
}
fn thing(x: A) -> thing {
}
impl thing {
- pub fn foo(@self) -> int { *self.x.a }
- pub fn bar(~self) -> int { *self.x.a }
- pub fn quux(&self) -> int { *self.x.a }
+ pub fn bar(~self) -> int { self.x.a }
+ pub fn quux(&self) -> int { self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
- pub fn spam(self) -> int { *self.x.a }
+ pub fn spam(self) -> int { self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
-
- let x = @thing(A {a: @10});
- assert_eq!(x.foo(), 10);
- assert_eq!(x.quux(), 10);
-
- let y = ~thing(A {a: @10});
+ let y = ~thing(A {a: 10});
assert_eq!(y.clone().bar(), 10);
assert_eq!(y.quux(), 10);
- let z = thing(A {a: @11});
+ let z = thing(A {a: 11});
assert_eq!(z.spam(), 11);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait Foo<T> {
fn get(&self) -> T;
}
}
pub fn main() {
- let x = @S { x: 1 };
- let y = x as @Foo<int>;
+ let x = ~S { x: 1 };
+ let y = x as ~Foo<int>;
assert_eq!(y.get(), 1);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait clam<A> {
fn chowder(&self, y: A);
}
}
}
-fn f<A>(x: @clam<A>, a: A) {
+fn f<A>(x: ~clam<A>, a: A) {
x.chowder(a);
}
pub fn main() {
let c = foo(42);
- let d: @clam<int> = @c as @clam<int>;
+ let d: ~clam<int> = ~c as ~clam<int>;
f(d, c.x);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// xfail-fast
// aux-build:issue-2380.rs
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait hax { }
impl<A> hax for A { }
-fn perform_hax<T:'static>(x: @T) -> @hax {
- @x as @hax
+fn perform_hax<T: 'static>(x: ~T) -> ~hax: {
+ ~x as ~hax:
}
fn deadcode() {
- perform_hax(@~"deadcode");
+ perform_hax(~~"deadcode");
}
pub fn main() {
- let _ = perform_hax(@42);
+ let _ = perform_hax(~42);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait hax { }
impl<A> hax for A { }
-fn perform_hax<T:'static>(x: @T) -> @hax {
- @x as @hax
+fn perform_hax<T: 'static>(x: ~T) -> ~hax: {
+ ~x as ~hax:
}
fn deadcode() {
- perform_hax(@~"deadcode");
+ perform_hax(~~"deadcode");
}
pub fn main() {
- perform_hax(@42);
+ perform_hax(~42);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
//type t = { a: int };
// type t = { a: bool };
type t = bool;
pub fn main() {
// let x = ({a: 4i} as it);
- // let y = @({a: 4i});
- // let z = @({a: 4i} as it);
- // let z = @({a: true} as it);
- let z = @(@true as @it);
+ // let y = ~({a: 4i});
+ // let z = ~({a: 4i} as it);
+ // let z = ~({a: true} as it);
+ let z = ~(~true as ~it);
// x.f();
// y.f();
// (*z).f();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
pub fn main() {
trait Text {
fn to_str(&self) -> ~str;
}
- fn to_string(t: @Text) {
+ fn to_string(t: ~Text) {
println!("{}", t.to_str());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait T {
fn print(&self);
}
}
pub fn main() {
- let s: @S = @S { s: 5 };
+ let s: ~S = ~S { s: 5 };
print_s(s);
- let t: @T = s as @T;
+ let t: ~T = s as ~T;
print_t(t);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
/*
#7673 Polymorphically creating traits barely works
fn owned1<T: 'static>(a: T) { ~a as ~A:; } /* note `:` */
fn owned2<T: 'static>(a: ~T) { a as ~A:; }
fn owned3<T: 'static>(a: ~T) { ~a as ~A:; }
-
-fn managed1<T: 'static>(a: T) { @a as @A; }
-fn managed2<T: 'static>(a: @T) { a as @A; }
-fn managed3<T: 'static>(a: @T) { @a as @A; }
// xfail-pretty
-#[feature(managed_boxes, macro_rules)];
+#[feature(macro_rules)];
-pub trait bomb { fn boom(@self, Ident); }
+pub trait bomb { fn boom(&self, Ident); }
pub struct S;
-impl bomb for S { fn boom(@self, _: Ident) { } }
+impl bomb for S { fn boom(&self, _: Ident) { } }
pub struct Ident { name: uint }
Ident {name: 0x6789ABCD }
}
-pub fn light_fuse(fld: @bomb) {
+pub fn light_fuse(fld: ~bomb) {
int3!();
let f = || {
int3!();
}
pub fn main() {
- let b = @S as @bomb;
+ let b = ~S as ~bomb;
light_fuse(b);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
trait repeat<A> { fn get(&self) -> A; }
-impl<A:Clone + 'static> repeat<A> for @A {
+impl<A:Clone + 'static> repeat<A> for ~A {
fn get(&self) -> A {
(**self).clone()
}
}
-fn repeater<A:Clone + 'static>(v: @A) -> @repeat:<A> {
+fn repeater<A:Clone + 'static>(v: ~A) -> ~repeat:<A> {
// Note: owned kind is not necessary as A appears in the trait type
- @v as @repeat:<A> // No
+ ~v as ~repeat:<A> // No
}
pub fn main() {
let x = 3;
- let y = repeater(@x);
+ let y = repeater(~x);
assert_eq!(x, y.get());
}
+++ /dev/null
-// 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.
-
-#[feature(managed_boxes)];
-
-// Test that we can coerce an `@Object` to an `&Object`
-
-trait Foo {
- fn foo(&self) -> uint;
-}
-
-impl Foo for uint {
- fn foo(&self) -> uint {
- *self
- }
-}
-
-fn do_it_imm(obj: &Foo, v: uint) {
- let y = obj.foo();
- assert_eq!(v, y);
-}
-
-pub fn main() {
- let x = @22u as @Foo;
- do_it_imm(x, 22u);
-}
}
fn visit_trait(&mut self, name: &str) -> bool {
- self.align_to::<@TyVisitor>();
+ self.align_to::<~TyVisitor>();
if ! self.inner().visit_trait(name) { return false; }
- self.bump_past::<@TyVisitor>();
+ self.bump_past::<~TyVisitor>();
true
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
-use std::io::println;
-
trait Trait<T> {
fn f(&self, x: T);
}
}
}
-fn f(x: @Trait<&'static str>) {
- x.f("Sue");
-}
-
pub fn main() {
let a = Struct { x: 1, y: 2 };
- let b: @Trait<&'static str> = @a;
- b.f("Fred");
- let c: ~Trait<&'static str> = ~a;
- c.f("Mary");
- let d: &Trait<&'static str> = &a;
- d.f("Joe");
- f(@a);
+ let b: ~Trait<&'static str> = ~a;
+ b.f("Mary");
+ let c: &Trait<&'static str> = &a;
+ c.f("Joe");
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
use std::io;
trait Trait {
}
}
-fn f(x: @Trait) {
- x.f();
-}
-
fn foo(mut a: ~Writer) {
a.write(bytes!("Hello\n"));
}
pub fn main() {
let a = Struct { x: 1, y: 2 };
- let b: @Trait = @a;
+ let b: ~Trait = ~a;
b.f();
- let c: ~Trait = ~a;
+ let c: &Trait = &a;
c.f();
- let d: &Trait = &a;
- d.f();
- f(@a);
let out = io::stdout();
foo(~out);
-#[feature(managed_boxes)];
-
// xfail-fast
// aux-build:trait_default_method_xc_aux.rs
assert_eq!(g(0i, 3.14, 1), (3.14, 1));
assert_eq!(g(false, 3.14, 1), (3.14, 1));
- let obj = @0i as @A;
+ let obj = ~0i as ~A;
assert_eq!(obj.h(), 11);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[feature(managed_boxes)];
-
// test for #8664
pub trait Trait2<A> {
fn method(&self, _x: Type<(u8,V)>) -> int { 0 }
}
-pub fn main () {
- let a = @() as @Trait<u8, u8>;
+pub fn main() {
+ let a = ~() as ~Trait<u8, u8>;
assert_eq!(a.method(Constant), 0);
}