From 2b07f0fb0018649588cda06bd33c33b71c5cac70 Mon Sep 17 00:00:00 2001 From: John Clements Date: Tue, 12 Mar 2013 11:37:31 -0700 Subject: [PATCH 01/35] field renaming --- src/libsyntax/ext/tt/transcribe.rs | 57 +++++++++++++++--------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 67c2f438269d8..f0e1273534ab1 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -26,7 +26,7 @@ use core::vec; `~` */ ///an unzipping of `token_tree`s struct TtFrame { - readme: @mut ~[ast::token_tree], + forest: @mut ~[ast::token_tree], idx: uint, dotdotdoted: bool, sep: Option, @@ -37,7 +37,7 @@ pub struct TtReader { sp_diag: @span_handler, interner: @ident_interner, // the unzipped tree: - cur: @mut TtFrame, + stack: @mut TtFrame, /* for MBE-style macro transcription */ interpolations: LinearMap, repeat_idx: ~[uint], @@ -58,8 +58,8 @@ pub fn new_tt_reader(sp_diag: @span_handler, let r = @mut TtReader { sp_diag: sp_diag, interner: itr, - cur: @mut TtFrame { - readme: @mut src, + stack: @mut TtFrame { + forest: @mut src, idx: 0u, dotdotdoted: false, sep: None, @@ -81,7 +81,7 @@ pub fn new_tt_reader(sp_diag: @span_handler, fn dup_tt_frame(f: @mut TtFrame) -> @mut TtFrame { @mut TtFrame { - readme: @mut (copy *f.readme), + forest: @mut (copy *f.forest), idx: f.idx, dotdotdoted: f.dotdotdoted, sep: copy f.sep, @@ -96,7 +96,7 @@ pub fn dup_tt_reader(r: @mut TtReader) -> @mut TtReader { @mut TtReader { sp_diag: r.sp_diag, interner: r.interner, - cur: dup_tt_frame(r.cur), + stack: dup_tt_frame(r.stack), interpolations: r.interpolations, repeat_idx: copy r.repeat_idx, repeat_len: copy r.repeat_len, @@ -167,7 +167,8 @@ fn lockstep_iter_size(t: token_tree, r: &mut TtReader) -> lis { } } - +// return the next token from the TtReader. +// EFFECT: advances the reader's token field pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { let ret_val = TokenAndSpan { tok: copy r.cur_tok, @@ -175,37 +176,37 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { }; loop { { - let cur = &mut *r.cur; - let readme = &mut *cur.readme; - if cur.idx < readme.len() { + let stack = &mut *r.stack; + let forest = &mut *stack.forest; + if stack.idx < forest.len() { break; } } /* done with this set; pop or repeat? */ - if ! r.cur.dotdotdoted + if ! r.stack.dotdotdoted || { *r.repeat_idx.last() == *r.repeat_len.last() - 1 } { - match r.cur.up { + match r.stack.up { None => { r.cur_tok = EOF; return ret_val; } Some(tt_f) => { - if r.cur.dotdotdoted { + if r.stack.dotdotdoted { r.repeat_idx.pop(); r.repeat_len.pop(); } - r.cur = tt_f; - r.cur.idx += 1u; + r.stack = tt_f; + r.stack.idx += 1u; } } } else { /* repeat */ - r.cur.idx = 0u; + r.stack.idx = 0u; r.repeat_idx[r.repeat_idx.len() - 1u] += 1u; - match r.cur.sep { + match r.stack.sep { Some(copy tk) => { r.cur_tok = tk; /* repeat same span, I guess */ return ret_val; @@ -216,21 +217,21 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { } loop { /* because it's easiest, this handles `tt_delim` not starting with a `tt_tok`, even though it won't happen */ - match r.cur.readme[r.cur.idx] { + match r.stack.forest[r.stack.idx] { tt_delim(copy tts) => { - r.cur = @mut TtFrame { - readme: @mut tts, + r.stack = @mut TtFrame { + forest: @mut tts, idx: 0u, dotdotdoted: false, sep: None, - up: option::Some(r.cur) + up: option::Some(r.stack) }; // if this could be 0-length, we'd need to potentially recur here } tt_tok(sp, copy tok) => { r.cur_span = sp; r.cur_tok = tok; - r.cur.idx += 1u; + r.stack.idx += 1u; return ret_val; } tt_seq(sp, copy tts, copy sep, zerok) => { @@ -256,17 +257,17 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { once"); } - r.cur.idx += 1u; + r.stack.idx += 1u; return tt_next_token(r); } else { r.repeat_len.push(len); r.repeat_idx.push(0u); - r.cur = @mut TtFrame { - readme: @mut tts, + r.stack = @mut TtFrame { + forest: @mut tts, idx: 0u, dotdotdoted: true, sep: sep, - up: Some(r.cur) + up: Some(r.stack) }; } } @@ -280,13 +281,13 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { (b) we actually can, since it's a token. */ matched_nonterminal(nt_ident(sn,b)) => { r.cur_span = sp; r.cur_tok = IDENT(sn,b); - r.cur.idx += 1u; + r.stack.idx += 1u; return ret_val; } matched_nonterminal(ref other_whole_nt) => { r.cur_span = sp; r.cur_tok = INTERPOLATED(copy *other_whole_nt); - r.cur.idx += 1u; + r.stack.idx += 1u; return ret_val; } matched_seq(*) => { From 556143c488f8b8b2ac25ac29efdf030017cba7d7 Mon Sep 17 00:00:00 2001 From: John Clements Date: Fri, 8 Mar 2013 10:19:19 -0800 Subject: [PATCH 02/35] commenting parser --- src/libsyntax/parse/common.rs | 15 ++++++++++++++- src/libsyntax/parse/lexer.rs | 7 ++++++- src/libsyntax/parse/mod.rs | 8 ++++++-- src/libsyntax/parse/parser.rs | 24 ++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/libsyntax/parse/common.rs b/src/libsyntax/parse/common.rs index c14c7bed1399f..ae7dd8ff96fce 100644 --- a/src/libsyntax/parse/common.rs +++ b/src/libsyntax/parse/common.rs @@ -159,6 +159,9 @@ pub impl Parser { } } + // if the given word is not a keyword, signal an error. + // if the next token is the given keyword, eat it and return + // true. Otherwise, return false. fn eat_keyword(&self, word: &~str) -> bool { self.require_keyword(word); let is_kw = match *self.token { @@ -169,6 +172,9 @@ pub impl Parser { is_kw } + // if the given word is not a keyword, signal an error. + // if the next token is not the given word, signal an error. + // otherwise, eat it. fn expect_keyword(&self, word: &~str) { self.require_keyword(word); if !self.eat_keyword(word) { @@ -182,10 +188,12 @@ pub impl Parser { } } + // return true if the given string is a strict keyword fn is_strict_keyword(&self, word: &~str) -> bool { self.strict_keywords.contains(word) } + // signal an error if the current token is a strict keyword fn check_strict_keywords(&self) { match *self.token { token::IDENT(_, false) => { @@ -196,16 +204,19 @@ pub impl Parser { } } + // signal an error if the given string is a strict keyword fn check_strict_keywords_(&self, w: &~str) { if self.is_strict_keyword(w) { self.fatal(fmt!("found `%s` in ident position", *w)); } } + // return true if this is a reserved keyword fn is_reserved_keyword(&self, word: &~str) -> bool { self.reserved_keywords.contains(word) } + // signal an error if the current token is a reserved keyword fn check_reserved_keywords(&self) { match *self.token { token::IDENT(_, false) => { @@ -216,6 +227,7 @@ pub impl Parser { } } + // signal an error if the given string is a reserved keyword fn check_reserved_keywords_(&self, w: &~str) { if self.is_reserved_keyword(w) { self.fatal(fmt!("`%s` is a reserved keyword", *w)); @@ -223,7 +235,8 @@ pub impl Parser { } // expect and consume a GT. if a >> is seen, replace it - // with a single > and continue. + // with a single > and continue. If a GT is not seen, + // signal an error. fn expect_gt(&self) { if *self.token == token::GT { self.bump(); diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index ffd2a1d801c96..512b6c0ec78eb 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -80,7 +80,8 @@ pub fn new_low_level_string_reader(span_diagnostic: @span_handler, last_pos: filemap.start_pos, col: CharPos(0), curr: initial_char, - filemap: filemap, interner: itr, + filemap: filemap, + interner: itr, /* dummy values; not read */ peek_tok: token::EOF, peek_span: codemap::dummy_sp() @@ -150,6 +151,7 @@ impl reader for TtReader { } // EFFECT: advance peek_tok and peek_span to refer to the next token. +// EFFECT: update the interner, maybe. fn string_advance_token(r: @mut StringReader) { match (consume_whitespace_and_comments(r)) { Some(comment) => { @@ -539,6 +541,9 @@ fn ident_continue(c: char) -> bool { || (c > 'z' && char::is_XID_continue(c)) } +// return the next token from the string +// EFFECT: advances the input past that token +// EFFECT: updates the interner fn next_token_inner(rdr: @mut StringReader) -> token::Token { let mut accum_str = ~""; let mut c = rdr.curr; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index cdb67129c355b..ba7a9624c1895 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -45,10 +45,14 @@ pub mod classify; /// Reporting obsolete syntax pub mod obsolete; +// info about a parsing session. +// This structure and the reader both have +// an interner associated with them. If they're +// not the same, bad things can happen. pub struct ParseSess { - cm: @codemap::CodeMap, + cm: @codemap::CodeMap, // better be the same as the one in the reader! next_id: node_id, - span_diagnostic: @span_handler, + span_diagnostic: @span_handler, // better be the same as the one in the reader! interner: @ident_interner, } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index d93e5995d4f8e..fc5254726534d 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -246,6 +246,7 @@ pub fn Parser(sess: @mut ParseSess, } } +// ooh, nasty mutable fields everywhere.... pub struct Parser { sess: @mut ParseSess, cfg: crate_cfg, @@ -338,6 +339,7 @@ pub impl Parser { self.sess.interner.get(id) } + // is this one of the keywords that signals a closure type? fn token_is_closure_keyword(&self, tok: &token::Token) -> bool { self.token_is_keyword(&~"pure", tok) || self.token_is_keyword(&~"unsafe", tok) || @@ -345,6 +347,7 @@ pub impl Parser { self.token_is_keyword(&~"fn", tok) } + // parse a ty_bare_fun type: fn parse_ty_bare_fn(&self) -> ty_ { /* @@ -372,6 +375,7 @@ pub impl Parser { }); } + // parse a ty_closure type fn parse_ty_closure(&self, sigil: ast::Sigil, region: Option<@ast::Lifetime>) -> ty_ @@ -430,6 +434,7 @@ pub impl Parser { } } + // parse a function type (following the 'fn') fn parse_ty_fn_decl(&self) -> (fn_decl, OptVec) { /* @@ -541,12 +546,14 @@ pub impl Parser { } + // parse a possibly mutable type fn parse_mt(&self) -> mt { let mutbl = self.parse_mutability(); let t = self.parse_ty(false); mt { ty: t, mutbl: mutbl } } + // parse [mut/const/imm] ID : TY fn parse_ty_field(&self) -> ty_field { let lo = self.span.lo; let mutbl = self.parse_mutability(); @@ -563,6 +570,7 @@ pub impl Parser { ) } + // parse optional return type [ -> TY ] in function decl fn parse_ret_ty(&self) -> (ret_style, @Ty) { return if self.eat(&token::RARROW) { let lo = self.span.lo; @@ -591,6 +599,7 @@ pub impl Parser { } } + // parse a type. // Useless second parameter for compatibility with quasiquote macros. // Bleh! fn parse_ty(&self, _: bool) -> @Ty { @@ -627,15 +636,19 @@ pub impl Parser { t } } else if *self.token == token::AT { + // MANAGED POINTER self.bump(); self.parse_box_or_uniq_pointee(ManagedSigil, ty_box) } else if *self.token == token::TILDE { + // OWNED POINTER self.bump(); self.parse_box_or_uniq_pointee(OwnedSigil, ty_uniq) } else if *self.token == token::BINOP(token::STAR) { + // STAR POINTER (bare pointer?) self.bump(); ty_ptr(self.parse_mt()) } else if *self.token == token::LBRACE { + // STRUCTURAL RECORD (remove?) let elems = self.parse_unspanned_seq( &token::LBRACE, &token::RBRACE, @@ -648,6 +661,7 @@ pub impl Parser { self.obsolete(*self.last_span, ObsoleteRecordType); ty_nil } else if *self.token == token::LBRACKET { + // VECTOR self.expect(&token::LBRACKET); let mt = self.parse_mt(); if mt.mutbl == m_mutbl { // `m_const` too after snapshot @@ -663,16 +677,20 @@ pub impl Parser { self.expect(&token::RBRACKET); t } else if *self.token == token::BINOP(token::AND) { + // BORROWED POINTER self.bump(); self.parse_borrowed_pointee() } else if self.eat_keyword(&~"extern") { + // EXTERN FUNCTION self.parse_ty_bare_fn() } else if self.token_is_closure_keyword(© *self.token) { + // CLOSURE let result = self.parse_ty_closure(ast::BorrowedSigil, None); self.obsolete(*self.last_span, ObsoleteBareFnType); result } else if *self.token == token::MOD_SEP || is_ident_or_path(&*self.token) { + // NAMED TYPE let path = self.parse_path_with_tps(false); ty_path(path, self.get_id()) } else { @@ -881,6 +899,8 @@ pub impl Parser { let global = self.eat(&token::MOD_SEP); let mut ids = ~[]; loop { + // if there's a ::< coming, stop processing + // the path. let is_not_last = self.look_ahead(2u) != token::LT && self.look_ahead(1u) == token::MOD_SEP; @@ -900,6 +920,9 @@ pub impl Parser { types: ~[] } } + // parse a path optionally with type parameters. If 'colons' + // is true, then type parameters must be preceded by colons, + // as in a::t:: fn parse_path_with_tps(&self, colons: bool) -> @ast::path { debug!("parse_path_with_tps(colons=%b)", colons); @@ -1067,6 +1090,7 @@ pub impl Parser { self.token_is_keyword(&~"const", tok) } + // parse mutability declaration (mut/const/imm) fn parse_mutability(&self) -> mutability { if self.eat_keyword(&~"mut") { m_mutbl From f2e47cddf835af49a925d91639d7fefb8c23d08f Mon Sep 17 00:00:00 2001 From: John Clements Date: Wed, 6 Mar 2013 12:38:13 -0800 Subject: [PATCH 03/35] change to parsing using tts also, updates test cases a bit --- src/librustc/driver/driver.rs | 2 +- src/libsyntax/parse/mod.rs | 44 ++++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 3aa0959317a4a..1f463a1614d23 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -150,7 +150,7 @@ pub fn parse_input(sess: Session, +cfg: ast::crate_cfg, input: input) -> @ast::crate { match input { file_input(ref file) => { - parse::parse_crate_from_file(&(*file), cfg, sess.parse_sess) + parse::parse_crate_from_file_using_tts(&(*file), cfg, sess.parse_sess) } str_input(ref src) => { // FIXME (#2319): Don't really want to box the source string diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index ba7a9624c1895..10d3de4acee81 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -94,6 +94,19 @@ pub fn parse_crate_from_file( // why is there no p.abort_if_errors here? } +pub fn parse_crate_from_file_using_tts( + input: &Path, + cfg: ast::crate_cfg, + sess: @mut ParseSess +) -> @ast::crate { + let p = new_parser_from_file(sess, /*bad*/ copy cfg, input); + let tts = p.parse_all_token_trees(); + new_parser_from_tts(sess,cfg,tts).parse_crate_mod(/*bad*/ copy cfg) + // why is there no p.abort_if_errors here? +} + + + pub fn parse_crate_from_source_str( name: ~str, source: @~str, @@ -317,6 +330,7 @@ mod test { use std; use core::io; use core::option::None; + use ast; #[test] fn to_json_str>(val: @E) -> ~str { do io::with_str_writer |writer| { @@ -324,10 +338,38 @@ mod test { } } + fn string_to_crate (source_str : @~str) -> @ast::crate { + parse_crate_from_source_str( + ~"bogofile", + source_str, + ~[], + new_parse_sess(None)) + } + + fn string_to_tt_to_crate (source_str : @~str) -> @ast::crate { + let tts = parse_tts_from_source_str( + ~"bogofile", + source_str, + ~[], + new_parse_sess(None)); + new_parser_from_tts(new_parse_sess(None),~[],tts) + .parse_crate_mod(~[]) + } + + // make sure that parsing from TTs produces the same result + // as parsing from strings + #[test] fn tts_produce_the_same_result () { + let source_str = @~"fn foo (x : int) { x; }"; + assert_eq!(string_to_tt_to_crate(source_str), + string_to_crate(source_str)); + } + + // check the contents of the tt manually: #[test] fn alltts () { + let source_str = @~"fn foo (x : int) { x; }"; let tts = parse_tts_from_source_str( ~"bogofile", - @~"fn foo (x : int) { x; }", + source_str, ~[], new_parse_sess(None)); assert_eq!( From a20d1ad0cbcca13ee386fd819f33563b465f1185 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 1 Apr 2013 16:37:40 -0700 Subject: [PATCH 04/35] Improve documentation for core::io. --- src/libcore/io.rs | 76 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 60a0ee4fa9713..be3e100631488 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -49,29 +49,89 @@ pub mod rustrt { // FIXME (#2004): This is all buffered. We might need an unbuffered variant // as well +/** +* The SeekStyle enum describes the relationship between the position +* we'd like to seek to from our current position. It's used as an argument +* to the `seek` method defined on the `Reader` trait. +* +* There are three seek styles: +* +* 1. `SeekSet` means that the new position should become our position. +* 2. `SeekCur` means that we should seek from the current position. +* 3. `SeekEnd` means that we should seek from the end. +* +* # Examples +* +* None right now. +*/ pub enum SeekStyle { SeekSet, SeekEnd, SeekCur, } -/// The raw underlying reader trait. All readers must implement this. +/** +* The core Reader trait. All readers must implement this trait. +* +* # Examples +* +* None right now. +*/ pub trait Reader { // FIXME (#2004): Seekable really should be orthogonal. - /// Read up to len bytes (or EOF) and put them into bytes (which - /// must be at least len bytes long). Return number of bytes read. // FIXME (#2982): This should probably return an error. + /** + * Reads bytes and puts them into `bytes`. Returns the number of + * bytes read. + * + * The number of bytes to be read is `len` or the end of the file, + * whichever comes first. + * + * The buffer must be at least `len` bytes long. + * + * # Examples + * + * None right now. + */ fn read(&self, bytes: &mut [u8], len: uint) -> uint; - /// Read a single byte, returning a negative value for EOF or read error. + /** + * Reads a single byte. + * + * In the case of an EOF or an error, returns a negative value. + * + * # Examples + * + * None right now. + */ fn read_byte(&self) -> int; - /// Return whether the stream is currently at EOF position. + /** + * Returns a boolean value: are we currently at EOF? + * + * # Examples + * + * None right now. + */ fn eof(&self) -> bool; - /// Move the current position within the stream. The second parameter - /// determines the position that the first parameter is relative to. + /** + * Seek to a given `position` in the stream. + * + * Takes an optional SeekStyle, which affects how we seek from the + * position. See `SeekStyle` docs for more details. + * + * # Examples + * + * None right now. + */ fn seek(&self, position: int, style: SeekStyle); - /// Return the current position within the stream. + /** + * Returns the current position within the stream. + * + * # Examples + * + * None right now. + */ fn tell(&self) -> uint; } From 1d658d9b97434a391a7e202a033080555a2bc69e Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 1 Apr 2013 18:03:54 -0700 Subject: [PATCH 05/35] Improve docs for Core::ReaderUtil. I filled out better descriptions for all of the neccesary functions. --- src/libcore/io.rs | 375 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 335 insertions(+), 40 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 60a0ee4fa9713..1a15a9f5d809c 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -93,120 +93,415 @@ impl Reader for @Reader { } } -/// Generic utility functions defined on readers. +/** +* The `ReaderUtil` trait is a home for many of the utility functions +* a particular Reader should implement. +* +* The default `Reader` trait is focused entirely on bytes. `ReaderUtil` is based +* on higher-level concepts like 'chars' and 'lines.' +* +* # Examples: +* +* None right now. +*/ pub trait ReaderUtil { - /// Read len bytes into a new vec. + /** + * Reads `len` number of bytes, and gives you a new vector back. + * + * # Examples + * + * None right now. + */ fn read_bytes(&self, len: uint) -> ~[u8]; - /// Read up until a specified character (which is optionally included) or EOF. + /** + * Reads up until a specific character or EOF. + * + * The `include` parameter specifies if the character should be included + * in the returned string. + * + * # Examples + * + * None right now. + */ fn read_until(&self, c: char, include: bool) -> ~str; - /// Read up until the first '\n' char (which is not returned), or EOF. + /** + * Reads up until the first '\n' or EOF. + * + * The '\n' is not included in the result. + * + * # Examples + * + * None right now. + */ fn read_line(&self) -> ~str; - /// Read n utf-8 encoded chars. + /** + * Reads `n` chars. + * + * Assumes that those chars are UTF-8 encoded. + * + * The '\n' is not included in the result. + * + * # Examples + * + * None right now. + */ fn read_chars(&self, n: uint) -> ~[char]; - /// Read a single utf-8 encoded char. + /** + * Reads a single UTF-8 encoded char. + * + * # Examples + * + * None right now. + */ fn read_char(&self) -> char; - /// Read up until the first null byte (which is not returned), or EOF. + /** + * Reads up until the first null byte or EOF. + * + * The null byte is not returned. + * + * # Examples + * + * None right now. + */ fn read_c_str(&self) -> ~str; - /// Read all the data remaining in the stream in one go. + /** + * Reads all remaining data in the stream. + * + * # Examples + * + * None right now. + */ fn read_whole_stream(&self) -> ~[u8]; - /// Iterate over every byte until the iterator breaks or EOF. + /** + * Iterate over every byte until EOF or the iterator breaks. + * + * # Examples + * + * None right now. + */ fn each_byte(&self, it: &fn(int) -> bool); - /// Iterate over every char until the iterator breaks or EOF. + /** + * Iterate over every char until EOF or the iterator breaks. + * + * # Examples + * + * None right now. + */ fn each_char(&self, it: &fn(char) -> bool); - /// Iterate over every line until the iterator breaks or EOF. + /** + * Iterate over every line until EOF or the iterator breaks. + * + * # Examples + * + * None right now. + */ fn each_line(&self, it: &fn(&str) -> bool); - /// Read all the lines of the file into a vector. + /** + * Reads all of the lines in the stream. + * + * Returns a vector of those lines. + * + * # Examples + * + * None right now. + */ fn read_lines(&self) -> ~[~str]; - /// Read n (between 1 and 8) little-endian unsigned integer bytes. + /** + * Reads `n` little-endian unsigned integer bytes. + * + * `n` must be between 1 and 8, inclusive. + * + * # Examples + * + * None right now. + */ fn read_le_uint_n(&self, nbytes: uint) -> u64; - /// Read n (between 1 and 8) little-endian signed integer bytes. + /** + * Reads `n` little-endian signed integer bytes. + * + * `n` must be between 1 and 8, inclusive. + * + * # Examples + * + * None right now. + */ fn read_le_int_n(&self, nbytes: uint) -> i64; - /// Read n (between 1 and 8) big-endian unsigned integer bytes. + /** + * Reads `n` big-endian unsigned integer bytes. + * + * `n` must be between 1 and 8, inclusive. + * + * # Examples + * + * None right now. + */ fn read_be_uint_n(&self, nbytes: uint) -> u64; - /// Read n (between 1 and 8) big-endian signed integer bytes. + /** + * Reads `n` big-endian signed integer bytes. + * + * `n` must be between 1 and 8, inclusive. + * + * # Examples + * + * None right now. + */ fn read_be_int_n(&self, nbytes: uint) -> i64; - /// Read a little-endian uint (number of bytes depends on system). + /** + * Reads a little-endian unsigned integer. + * + * The number of bytes returned is system-dependant. + * + * # Examples + * + * None right now. + */ fn read_le_uint(&self) -> uint; - /// Read a little-endian int (number of bytes depends on system). + /** + * Reads a little-endian integer. + * + * The number of bytes returned is system-dependant. + * + * # Examples + * + * None right now. + */ fn read_le_int(&self) -> int; - /// Read a big-endian uint (number of bytes depends on system). + /** + * Reads a big-endian unsigned integer. + * + * The number of bytes returned is system-dependant. + * + * # Examples + * + * None right now. + */ fn read_be_uint(&self) -> uint; - /// Read a big-endian int (number of bytes depends on system). + /** + * Reads a big-endian integer. + * + * The number of bytes returned is system-dependant. + * + * # Examples + * + * None right now. + */ fn read_be_int(&self) -> int; - /// Read a big-endian u64 (8 bytes). + /** + * Reads a big-endian `u64`. + * + * `u64`s are 8 bytes long. + * + * # Examples + * + * None right now. + */ fn read_be_u64(&self) -> u64; - /// Read a big-endian u32 (4 bytes). + /** + * Reads a big-endian `u32`. + * + * `u32`s are 4 bytes long. + * + * # Examples + * + * None right now. + */ fn read_be_u32(&self) -> u32; - /// Read a big-endian u16 (2 bytes). + /** + * Reads a big-endian `u16`. + * + * `u16`s are 2 bytes long. + * + * # Examples + * + * None right now. + */ fn read_be_u16(&self) -> u16; - /// Read a big-endian i64 (8 bytes). + /** + * Reads a big-endian `i64`. + * + * `i64`s are 8 bytes long. + * + * # Examples + * + * None right now. + */ fn read_be_i64(&self) -> i64; - /// Read a big-endian i32 (4 bytes). + /** + * Reads a big-endian `i32`. + * + * `i32`s are 4 bytes long. + * + * # Examples + * + * None right now. + */ fn read_be_i32(&self) -> i32; - /// Read a big-endian i16 (2 bytes). + /** + * Reads a big-endian `i16`. + * + * `i16`s are 2 bytes long. + * + * # Examples + * + * None right now. + */ fn read_be_i16(&self) -> i16; - /// Read a big-endian IEEE754 double-precision floating-point (8 bytes). + /** + * Reads a big-endian `f64`. + * + * `f64`s are 8 byte, IEEE754 double-precision floating point numbers. + * + * # Examples + * + * None right now. + */ fn read_be_f64(&self) -> f64; - /// Read a big-endian IEEE754 single-precision floating-point (4 bytes). + /** + * Reads a big-endian `f32`. + * + * `f32`s are 4 byte, IEEE754 single-precision floating point numbers. + * + * # Examples + * + * None right now. + */ fn read_be_f32(&self) -> f32; - /// Read a little-endian u64 (8 bytes). + /** + * Reads a little-endian `u64`. + * + * `u64`s are 8 bytes long. + * + * # Examples + * + * None right now. + */ fn read_le_u64(&self) -> u64; - /// Read a little-endian u32 (4 bytes). + /** + * Reads a little-endian `u32`. + * + * `u32`s are 4 bytes long. + * + * # Examples + * + * None right now. + */ fn read_le_u32(&self) -> u32; - /// Read a little-endian u16 (2 bytes). + /** + * Reads a little-endian `u16`. + * + * `u16`s are 2 bytes long. + * + * # Examples + * + * None right now. + */ fn read_le_u16(&self) -> u16; - /// Read a litle-endian i64 (8 bytes). + /** + * Reads a little-endian `i64`. + * + * `i64`s are 8 bytes long. + * + * # Examples + * + * None right now. + */ fn read_le_i64(&self) -> i64; - /// Read a litle-endian i32 (4 bytes). + /** + * Reads a little-endian `i32`. + * + * `i32`s are 4 bytes long. + * + * # Examples + * + * None right now. + */ fn read_le_i32(&self) -> i32; - /// Read a litle-endian i16 (2 bytes). + /** + * Reads a little-endian `i16`. + * + * `i16`s are 2 bytes long. + * + * # Examples + * + * None right now. + */ fn read_le_i16(&self) -> i16; - /// Read a litten-endian IEEE754 double-precision floating-point - /// (8 bytes). + /** + * Reads a little-endian `f64`. + * + * `f64`s are 8 byte, IEEE754 double-precision floating point numbers. + * + * # Examples + * + * None right now. + */ fn read_le_f64(&self) -> f64; - /// Read a litten-endian IEEE754 single-precision floating-point - /// (4 bytes). + /** + * Reads a little-endian `f32`. + * + * `f32`s are 4 byte, IEEE754 single-precision floating point numbers. + * + * # Examples + * + * None right now. + */ fn read_le_f32(&self) -> f32; - /// Read a u8 (1 byte). + /** + * Read a u8. + * + * `u8`s are 1 byte. + * + * # Examples + * + * None right now. + */ fn read_u8(&self) -> u8; - /// Read a i8 (1 byte). + /** + * Read an i8. + * + * `u8`s are 1 byte. + * + * # Examples + * + * None right now. + */ fn read_i8(&self) -> i8; } From 948ff6056f9f4c2fe312da98456d3d6b7d1ce699 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 1 Apr 2013 18:20:30 -0700 Subject: [PATCH 06/35] Typo fix. u8 -> i8 --- src/libcore/io.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 1a15a9f5d809c..b3dfe8d46af2c 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -496,7 +496,7 @@ pub trait ReaderUtil { /** * Read an i8. * - * `u8`s are 1 byte. + * `i8`s are 1 byte. * * # Examples * From 88e4b5de8350968b69b9e4d9037f35a5eaf3f796 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Tue, 2 Apr 2013 19:25:03 -0400 Subject: [PATCH 07/35] install the librust{doc,pkg} host libraries --- mk/install.mk | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mk/install.mk b/mk/install.mk index fd7f44ddae57c..a84f527a165b4 100644 --- a/mk/install.mk +++ b/mk/install.mk @@ -119,6 +119,8 @@ install-host: $(CSREQ$(ISTAGE)_T_$(CFG_BUILD_TRIPLE)_H_$(CFG_BUILD_TRIPLE)) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBSYNTAX_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTI_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUST_GLOB_$(CFG_BUILD_TRIPLE))) + $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTPKG_GLOB_$(CFG_BUILD_TRIPLE))) + $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTDOC_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_RUNTIME_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_RUSTLLVM_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL,$(S)/man, \ From 86d5ce5cef29e388de04c667e8cfd205327629cc Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 2 Apr 2013 17:29:02 -0700 Subject: [PATCH 08/35] remove trailing whitespace --- src/libcore/io.rs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index be3e100631488..925079f4cf212 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -55,14 +55,14 @@ pub mod rustrt { * to the `seek` method defined on the `Reader` trait. * * There are three seek styles: -* +* * 1. `SeekSet` means that the new position should become our position. * 2. `SeekCur` means that we should seek from the current position. * 3. `SeekEnd` means that we should seek from the end. * * # Examples -* -* None right now. +* +* None right now. */ pub enum SeekStyle { SeekSet, SeekEnd, SeekCur, } @@ -71,8 +71,8 @@ pub enum SeekStyle { SeekSet, SeekEnd, SeekCur, } * The core Reader trait. All readers must implement this trait. * * # Examples -* -* None right now. +* +* None right now. */ pub trait Reader { // FIXME (#2004): Seekable really should be orthogonal. @@ -82,14 +82,14 @@ pub trait Reader { * Reads bytes and puts them into `bytes`. Returns the number of * bytes read. * - * The number of bytes to be read is `len` or the end of the file, + * The number of bytes to be read is `len` or the end of the file, * whichever comes first. * * The buffer must be at least `len` bytes long. * * # Examples - * - * None right now. + * + * None right now. */ fn read(&self, bytes: &mut [u8], len: uint) -> uint; @@ -99,8 +99,8 @@ pub trait Reader { * In the case of an EOF or an error, returns a negative value. * * # Examples - * - * None right now. + * + * None right now. */ fn read_byte(&self) -> int; @@ -108,20 +108,20 @@ pub trait Reader { * Returns a boolean value: are we currently at EOF? * * # Examples - * - * None right now. + * + * None right now. */ fn eof(&self) -> bool; /** * Seek to a given `position` in the stream. - * + * * Takes an optional SeekStyle, which affects how we seek from the * position. See `SeekStyle` docs for more details. * * # Examples - * - * None right now. + * + * None right now. */ fn seek(&self, position: int, style: SeekStyle); @@ -129,8 +129,8 @@ pub trait Reader { * Returns the current position within the stream. * * # Examples - * - * None right now. + * + * None right now. */ fn tell(&self) -> uint; } From a3e2d6ea81b93bf41b4387be935b5f488e47ef73 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 2 Apr 2013 17:31:42 -0700 Subject: [PATCH 09/35] Remove excess trailing whitespace. --- src/libcore/io.rs | 122 +++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index b3dfe8d46af2c..c49117fe23d48 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -96,10 +96,10 @@ impl Reader for @Reader { /** * The `ReaderUtil` trait is a home for many of the utility functions * a particular Reader should implement. -* +* * The default `Reader` trait is focused entirely on bytes. `ReaderUtil` is based * on higher-level concepts like 'chars' and 'lines.' -* +* * # Examples: * * None right now. @@ -117,7 +117,7 @@ pub trait ReaderUtil { /** * Reads up until a specific character or EOF. - * + * * The `include` parameter specifies if the character should be included * in the returned string. * @@ -129,7 +129,7 @@ pub trait ReaderUtil { /** * Reads up until the first '\n' or EOF. - * + * * The '\n' is not included in the result. * * # Examples @@ -140,9 +140,9 @@ pub trait ReaderUtil { /** * Reads `n` chars. - * + * * Assumes that those chars are UTF-8 encoded. - * + * * The '\n' is not included in the result. * * # Examples @@ -209,7 +209,7 @@ pub trait ReaderUtil { /** * Reads all of the lines in the stream. - * + * * Returns a vector of those lines. * * # Examples @@ -220,9 +220,9 @@ pub trait ReaderUtil { /** * Reads `n` little-endian unsigned integer bytes. - * + * * `n` must be between 1 and 8, inclusive. - * + * * # Examples * * None right now. @@ -231,9 +231,9 @@ pub trait ReaderUtil { /** * Reads `n` little-endian signed integer bytes. - * + * * `n` must be between 1 and 8, inclusive. - * + * * # Examples * * None right now. @@ -242,9 +242,9 @@ pub trait ReaderUtil { /** * Reads `n` big-endian unsigned integer bytes. - * + * * `n` must be between 1 and 8, inclusive. - * + * * # Examples * * None right now. @@ -253,9 +253,9 @@ pub trait ReaderUtil { /** * Reads `n` big-endian signed integer bytes. - * + * * `n` must be between 1 and 8, inclusive. - * + * * # Examples * * None right now. @@ -264,9 +264,9 @@ pub trait ReaderUtil { /** * Reads a little-endian unsigned integer. - * + * * The number of bytes returned is system-dependant. - * + * * # Examples * * None right now. @@ -275,9 +275,9 @@ pub trait ReaderUtil { /** * Reads a little-endian integer. - * + * * The number of bytes returned is system-dependant. - * + * * # Examples * * None right now. @@ -286,9 +286,9 @@ pub trait ReaderUtil { /** * Reads a big-endian unsigned integer. - * + * * The number of bytes returned is system-dependant. - * + * * # Examples * * None right now. @@ -297,9 +297,9 @@ pub trait ReaderUtil { /** * Reads a big-endian integer. - * + * * The number of bytes returned is system-dependant. - * + * * # Examples * * None right now. @@ -308,9 +308,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `u64`. - * + * * `u64`s are 8 bytes long. - * + * * # Examples * * None right now. @@ -319,9 +319,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `u32`. - * + * * `u32`s are 4 bytes long. - * + * * # Examples * * None right now. @@ -330,9 +330,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `u16`. - * + * * `u16`s are 2 bytes long. - * + * * # Examples * * None right now. @@ -341,9 +341,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `i64`. - * + * * `i64`s are 8 bytes long. - * + * * # Examples * * None right now. @@ -352,9 +352,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `i32`. - * + * * `i32`s are 4 bytes long. - * + * * # Examples * * None right now. @@ -363,9 +363,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `i16`. - * + * * `i16`s are 2 bytes long. - * + * * # Examples * * None right now. @@ -374,9 +374,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `f64`. - * + * * `f64`s are 8 byte, IEEE754 double-precision floating point numbers. - * + * * # Examples * * None right now. @@ -385,9 +385,9 @@ pub trait ReaderUtil { /** * Reads a big-endian `f32`. - * + * * `f32`s are 4 byte, IEEE754 single-precision floating point numbers. - * + * * # Examples * * None right now. @@ -396,9 +396,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `u64`. - * + * * `u64`s are 8 bytes long. - * + * * # Examples * * None right now. @@ -407,9 +407,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `u32`. - * + * * `u32`s are 4 bytes long. - * + * * # Examples * * None right now. @@ -418,9 +418,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `u16`. - * + * * `u16`s are 2 bytes long. - * + * * # Examples * * None right now. @@ -429,9 +429,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `i64`. - * + * * `i64`s are 8 bytes long. - * + * * # Examples * * None right now. @@ -440,9 +440,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `i32`. - * + * * `i32`s are 4 bytes long. - * + * * # Examples * * None right now. @@ -451,9 +451,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `i16`. - * + * * `i16`s are 2 bytes long. - * + * * # Examples * * None right now. @@ -462,9 +462,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `f64`. - * + * * `f64`s are 8 byte, IEEE754 double-precision floating point numbers. - * + * * # Examples * * None right now. @@ -473,9 +473,9 @@ pub trait ReaderUtil { /** * Reads a little-endian `f32`. - * + * * `f32`s are 4 byte, IEEE754 single-precision floating point numbers. - * + * * # Examples * * None right now. @@ -483,10 +483,10 @@ pub trait ReaderUtil { fn read_le_f32(&self) -> f32; /** - * Read a u8. - * + * Read a u8. + * * `u8`s are 1 byte. - * + * * # Examples * * None right now. @@ -494,10 +494,10 @@ pub trait ReaderUtil { fn read_u8(&self) -> u8; /** - * Read an i8. - * + * Read an i8. + * * `i8`s are 1 byte. - * + * * # Examples * * None right now. From e4edfa046af08a345c607ec9c80426d9eabc7c82 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sat, 23 Feb 2013 17:46:04 +1100 Subject: [PATCH 10/35] libstd: implement fileinput. Iterate over lines in a series of files. API (mostly) adopted from Python's fileinput module. --- src/libstd/fileinput.rs | 464 ++++++++++++++++++++++++++++++++++++++++ src/libstd/std.rc | 1 + 2 files changed, 465 insertions(+) create mode 100644 src/libstd/fileinput.rs diff --git a/src/libstd/fileinput.rs b/src/libstd/fileinput.rs new file mode 100644 index 0000000000000..3f281150331d6 --- /dev/null +++ b/src/libstd/fileinput.rs @@ -0,0 +1,464 @@ +// Copyright 2013 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +A convience device for iterating through the lines in a series of +files. Very similar to [the Python module of the same +name](http://docs.python.org/3.3/library/fileinput.html). + +It allows the programmer to automatically take filenames from the +command line arguments (via `input` and `input_state`), as well as +specify them as a vector directly (`input_vec` and +`input_vec_state`). The files are opened as necessary, so any files +that can't be opened only cause an error when reached in the +iteration. + +On the command line, `stdin` is represented by a filename of `-` (a +single hyphen) and in the functions that take a vector directly +(e.g. `input_vec`) it is represented by `None`. Note `stdin` is *not* +reset once it has been finished, so attempting to iterate on `[None, +None]` will only take input once unless `io::stdin().seek(0, SeekSet)` +is called between. + +The `pathify` function handles converting a list of file paths as +strings to the appropriate format, including the (optional) conversion +of `"-"` to `stdin`. + +# Basic + +In many cases, one can use the `input_*` functions without having +to handle any `FileInput` structs. E.g. a simple `cat` program + + for input |line| { + io::println(line) + } + +or a program that numbers lines after concatenating two files + + for input_vec_state(pathify([~"a.txt", ~"b.txt"])) |line, state| { + io::println(fmt!("%u: %s", state.line_num, + line)); + } + +The 2 `_vec` functions take a vec of file names (and empty means +read from `stdin`), the other 2 use the command line arguments. + +# Advanced + +For more complicated uses (e.g. if one needs to pause iteration and +resume it later), a `FileInput` instance can be constructed via the +`from_vec`, `from_vec_raw` and `from_args` functions. + +Once created, the `lines_each` and `lines_each_state` methods +allow one to iterate on the lines (the latter provides more +information about the position within the iteration to the caller. + +It is possible (and safe) to skip lines and files using the +`read_line` and `next_file` methods. + +E.g. the following (pointless) program reads until an empty line, +pauses for user input, skips the current file and then numbers the +remaining lines (where the numbers are from the start of the file, +rather than the total line count). + + let mut in = FileInput::from_vec(pathify([~"a.txt", ~"b.txt", ~"c.txt"], + true)); + + for in.lines_each |line| { + if line.is_empty() { + break + } + io::println(line); + } + + io::println("Continue?"); + + if io::stdin().read_line() == ~"yes" { + in.next_file(); // skip! + + for in.lines_each_state |line, state| { + io::println(fmt!("%u: %s", state.line_num_file, + line)) + } + } +*/ + +use core::prelude::*; +use core::io::ReaderUtil; + +/** +A summary of the internal state of a FileInput object. `line_num` and +`line_num_file` represent the number of lines read in total and in the +current file respectively. +*/ +pub struct FileInputState { + current_path: Option, + line_num: uint, + line_num_file: uint +} + +impl FileInputState { + fn is_stdin(&self) -> bool { + self.current_path.is_none() + } + + fn is_first_line(&self) -> bool { + self.line_num_file == 1 + } +} + +priv struct FileInput { + /** + `Some(path)` is the file represented by `path`, `None` is + `stdin`. Consumed as the files are read. + */ + files: ~[Option], + /** + The current file: `Some(r)` for an open file, `None` before + starting and after reading everything. + */ + current_reader: Option<@io::Reader>, + state: FileInputState +} + +impl FileInput { + /** + Create a `FileInput` object from a vec of files. An empty + vec means lines are read from `stdin` (use `from_vec_raw` to stop + this behaviour). Any occurence of `None` represents `stdin`. + */ + static pure fn from_vec(files: ~[Option]) -> FileInput { + FileInput::from_vec_raw( + if files.is_empty() { + ~[None] + } else { + files + }) + } + + /** + Identical to `from_vec`, but an empty `files` vec stays + empty. (`None` is `stdin`.) + */ + static pure fn from_vec_raw(files: ~[Option]) + -> FileInput { + FileInput { + files: files, + current_reader: None, + state: FileInputState { + current_path: None, + line_num: 0, + line_num_file: 0 + } + } + } + + /** + Create a `FileInput` object from the command line + arguments. `-` represents `stdin`. + */ + static fn from_args() -> FileInput { + let args = os::args(), + pathed = pathify(args.tail(), true); + FileInput::from_vec(pathed) + } + + priv fn current_file_eof(&self) -> bool { + match self.current_reader { + None => false, + Some(r) => r.eof() + } + } + + /** + Skip to the next file in the queue. Can `fail` when opening + a file. + */ + pub fn next_file(&mut self) { + // No more files + if self.files.is_empty() { + self.current_reader = None; + return; + } + + let path_option = self.files.shift(), + file = match path_option { + None => io::stdin(), + Some(ref path) => io::file_reader(path).get() + }; + + self.current_reader = Some(file); + self.state.current_path = path_option; + self.state.line_num_file = 0; + } + + /** + Attempt to open the next file if there is none currently open, + or if the current one is EOF'd. + */ + priv fn next_file_if_eof(&mut self) { + match self.current_reader { + None => self.next_file(), + Some(r) => { + if r.eof() { + self.next_file() + } + } + } + } + + /** + Read a single line. Returns `None` if there are no remaining lines + in any remaining file. (Automatically opens files as required, see + `next_file` for details.) + + (Name to avoid conflicting with `core::io::ReaderUtil::read_line`.) + */ + pub fn next_line(&mut self) -> Option<~str> { + loop { + // iterate until there is a file that can be read from + self.next_file_if_eof(); + match self.current_reader { + None => { + // no file has any content + return None; + }, + Some(r) => { + let l = r.read_line(); + + // at the end of this file, and we read nothing, so + // go to the next file + if r.eof() && l.is_empty() { + loop; + } + self.state.line_num += 1; + self.state.line_num_file += 1; + return Some(l); + } + } + } + } + + /** + Call `f` on the lines in the files in succession, stopping if + it ever returns `false`. + + State is preserved across calls. + + (The name is to avoid conflict with + `core::io::ReaderUtil::each_line`.) + */ + pub fn lines_each(&mut self, f: &fn(~str) -> bool) { + loop { + match self.next_line() { + None => break, + Some(line) => { + if !f(line) { + break; + } + } + } + } + } + + /** + Apply `f` to each line successively, along with some state + (line numbers and file names, see documentation for + `FileInputState`). Otherwise identical to `lines_each`. + */ + pub fn lines_each_state(&mut self, + f: &fn(~str, &FileInputState) -> bool) { + loop { + match self.next_line() { + None => break, + Some(line) => { + if !f(line, &self.state) { + break; + } + } + } + } + } +} + +/** +Convert a list of strings to an appropriate form for a `FileInput` +instance. `stdin_hyphen` controls whether `-` represents `stdin` or +not. +*/ +// XXX: stupid, unclear name +pub fn pathify(vec: &[~str], stdin_hyphen : bool) -> ~[Option] { + vec::map(vec, |&str : & ~str| { + if stdin_hyphen && str == ~"-" { + None + } else { + Some(Path(str)) + } + }) +} + +/** +Iterate directly over the command line arguments (no arguments implies +reading from `stdin`). + +Fails when attempting to read from a file that can't be opened. +*/ +pub fn input(f: &fn(~str) -> bool) { + let mut i = FileInput::from_args(); + i.lines_each(f); +} + +/** +Iterate directly over the command line arguments (no arguments +implies reading from `stdin`) with the current state of the iteration +provided at each call. + +Fails when attempting to read from a file that can't be opened. +*/ +pub fn input_state(f: &fn(~str, &FileInputState) -> bool) { + let mut i = FileInput::from_args(); + i.lines_each_state(f); +} + +/** +Iterate over a vec of files (an empty vec implies just `stdin`). + +Fails when attempting to read from a file that can't be opened. +*/ +pub fn input_vec(files: ~[Option], f: &fn(~str) -> bool) { + let mut i = FileInput::from_vec(files); + i.lines_each(f); +} + +/** +Iterate over a vec of files (an empty vec implies just `stdin`) with +the current state of the iteration provided at each call. + +Fails when attempting to read from a file that can't be opened. +*/ +pub fn input_vec_state(files: ~[Option], + f: &fn(~str, &FileInputState) -> bool) { + let mut i = FileInput::from_vec(files); + i.lines_each_state(f); +} + +#[cfg(test)] +mod test { + use core::io::WriterUtil; + use core::prelude::*; + use super::{FileInput, pathify, input_vec, input_vec_state}; + + fn make_file(path : &Path, contents: &[~str]) { + let file = io::file_writer(path, [io::Create, io::Truncate]).get(); + + for contents.each |&str| { + file.write_str(str); + file.write_char('\n'); + } + } + + #[test] + fn test_pathify() { + let strs = [~"some/path", + ~"some/other/path"], + paths = ~[Some(Path("some/path")), + Some(Path("some/other/path"))]; + + fail_unless!(pathify(strs, true) == paths); + fail_unless!(pathify(strs, false) == paths); + + fail_unless!(pathify([~"-"], true) == ~[None]); + fail_unless!(pathify([~"-"], false) == ~[Some(Path("-"))]); + } + + #[test] + fn test_input_vec() { + let mut all_lines = ~[]; + let filenames = pathify(vec::from_fn( + 3, + |i| fmt!("tmp/lib-fileinput-test-input-vec-%u.tmp", i)), true); + + for filenames.eachi |i, &filename| { + let contents = + vec::from_fn(3, |j| fmt!("%u %u", i, j)); + make_file(&filename.get(), contents); + all_lines.push_all(contents); + } + + let mut read_lines = ~[]; + for input_vec(filenames) |line| { + read_lines.push(line); + } + fail_unless!(read_lines == all_lines); + } + + #[test] + fn test_input_vec_state() { + let filenames = pathify(vec::from_fn( + 3, + |i| + fmt!("tmp/lib-fileinput-test-input-vec-state-%u.tmp", i)),true); + + for filenames.eachi |i, &filename| { + let contents = + vec::from_fn(3, |j| fmt!("%u %u", i, j + 1)); + make_file(&filename.get(), contents); + } + + for input_vec_state(filenames) |line, state| { + let nums = str::split_char(line, ' '); + + let file_num = uint::from_str(nums[0]).get(); + let line_num = uint::from_str(nums[1]).get(); + + fail_unless!(line_num == state.line_num_file); + fail_unless!(file_num * 3 + line_num == state.line_num); + } + } + + #[test] + fn test_next_file() { + let filenames = pathify(vec::from_fn( + 3, + |i| + fmt!("tmp/lib-fileinput-test-next-file-%u.tmp", i)),true); + + for filenames.eachi |i, &filename| { + let contents = + vec::from_fn(3, |j| fmt!("%u %u", i, j + 1)); + make_file(&filename.get(), contents); + } + + let mut in = FileInput::from_vec(filenames); + + // read once from 0 + fail_unless!(in.next_line() == Some(~"0 1")); + in.next_file(); // skip the rest of 1 + + // read all lines from 1 (but don't read any from 2), + for uint::range(1, 4) |i| { + fail_unless!(in.next_line() == Some(fmt!("1 %u", i))); + } + // 1 is finished, but 2 hasn't been started yet, so this will + // just "skip" to the beginning of 2 (Python's fileinput does + // the same) + in.next_file(); + + fail_unless!(in.next_line() == Some(~"2 1")); + } + + #[test] + #[should_fail] + fn test_input_vec_missing_file() { + for input_vec(pathify([~"this/file/doesnt/exist"], true)) |line| { + io::println(line); + } + } +} diff --git a/src/libstd/std.rc b/src/libstd/std.rc index 89bdc750c2277..74ef229a03353 100644 --- a/src/libstd/std.rc +++ b/src/libstd/std.rc @@ -98,6 +98,7 @@ pub mod workcache; pub mod bigint; pub mod stats; pub mod semver; +pub mod fileinput; #[cfg(unicode)] mod unicode; From 1e28d8fdb63a469ec9b1c8f2e79eae04f228b65e Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Mon, 25 Mar 2013 21:34:36 +1100 Subject: [PATCH 11/35] libstd: implement io::Reader for fileinput. --- src/libstd/fileinput.rs | 397 +++++++++++++++++++++++++++------------- 1 file changed, 271 insertions(+), 126 deletions(-) diff --git a/src/libstd/fileinput.rs b/src/libstd/fileinput.rs index 3f281150331d6..0056b34eccbca 100644 --- a/src/libstd/fileinput.rs +++ b/src/libstd/fileinput.rs @@ -9,7 +9,7 @@ // except according to those terms. /*! -A convience device for iterating through the lines in a series of +A library for iterating through the lines in a series of files. Very similar to [the Python module of the same name](http://docs.python.org/3.3/library/fileinput.html). @@ -47,8 +47,9 @@ or a program that numbers lines after concatenating two files line)); } -The 2 `_vec` functions take a vec of file names (and empty means -read from `stdin`), the other 2 use the command line arguments. +The two `input_vec*` functions take a vec of file names (where empty +means read from `stdin`), the other two functions use the command line +arguments. # Advanced @@ -56,22 +57,25 @@ For more complicated uses (e.g. if one needs to pause iteration and resume it later), a `FileInput` instance can be constructed via the `from_vec`, `from_vec_raw` and `from_args` functions. -Once created, the `lines_each` and `lines_each_state` methods -allow one to iterate on the lines (the latter provides more -information about the position within the iteration to the caller. +Once created, the `each_line` (from the `core::io::ReaderUtil` trait) +and `each_line_state` methods allow one to iterate on the lines; the +latter provides more information about the position within the +iteration to the caller. It is possible (and safe) to skip lines and files using the -`read_line` and `next_file` methods. +`read_line` and `next_file` methods. Also, `FileInput` implements +`core::io::Reader`, and the state will be updated correctly while +using any of those methods. -E.g. the following (pointless) program reads until an empty line, -pauses for user input, skips the current file and then numbers the -remaining lines (where the numbers are from the start of the file, -rather than the total line count). +E.g. the following program reads until an empty line, pauses for user +input, skips the current file and then numbers the remaining lines +(where the numbers are from the start of each file, rather than the +total line count). - let mut in = FileInput::from_vec(pathify([~"a.txt", ~"b.txt", ~"c.txt"], + let in = FileInput::from_vec(pathify([~"a.txt", ~"b.txt", ~"c.txt"], true)); - for in.lines_each |line| { + for in.each_line |line| { if line.is_empty() { break } @@ -83,20 +87,23 @@ rather than the total line count). if io::stdin().read_line() == ~"yes" { in.next_file(); // skip! - for in.lines_each_state |line, state| { + for in.each_line_state |line, state| { io::println(fmt!("%u: %s", state.line_num_file, line)) } } */ +#[allow(deprecated_mutable_fields)]; + use core::prelude::*; use core::io::ReaderUtil; /** -A summary of the internal state of a FileInput object. `line_num` and -`line_num_file` represent the number of lines read in total and in the -current file respectively. +A summary of the internal state of a `FileInput` object. `line_num` +and `line_num_file` represent the number of lines read in total and in +the current file respectively. `current_path` is `None` if the current +file is `stdin`. */ pub struct FileInputState { current_path: Option, @@ -114,18 +121,32 @@ impl FileInputState { } } -priv struct FileInput { +struct FileInput_ { /** `Some(path)` is the file represented by `path`, `None` is `stdin`. Consumed as the files are read. */ - files: ~[Option], + priv files: ~[Option], /** The current file: `Some(r)` for an open file, `None` before starting and after reading everything. */ - current_reader: Option<@io::Reader>, - state: FileInputState + priv current_reader: Option<@io::Reader>, + priv state: FileInputState, + + /** + Used to keep track of whether we need to insert the newline at the + end of a file that is missing it, which is needed to separate the + last and first lines. + */ + priv previous_was_newline: bool +} + +// XXX: remove this when Reader has &mut self. Should be removable via +// "self.fi." -> "self." and renaming FileInput_. Documentation above +// will likely have to be updated to use `let mut in = ...`. +pub struct FileInput { + priv mut fi: FileInput_ } impl FileInput { @@ -134,7 +155,7 @@ impl FileInput { vec means lines are read from `stdin` (use `from_vec_raw` to stop this behaviour). Any occurence of `None` represents `stdin`. */ - static pure fn from_vec(files: ~[Option]) -> FileInput { + pub fn from_vec(files: ~[Option]) -> FileInput { FileInput::from_vec_raw( if files.is_empty() { ~[None] @@ -147,31 +168,35 @@ impl FileInput { Identical to `from_vec`, but an empty `files` vec stays empty. (`None` is `stdin`.) */ - static pure fn from_vec_raw(files: ~[Option]) + pub fn from_vec_raw(files: ~[Option]) -> FileInput { - FileInput { - files: files, - current_reader: None, - state: FileInputState { - current_path: None, - line_num: 0, - line_num_file: 0 + FileInput{ + fi: FileInput_ { + files: files, + current_reader: None, + state: FileInputState { + current_path: None, + line_num: 0, + line_num_file: 0 + }, + // there was no previous unended line + previous_was_newline: true } } } /** Create a `FileInput` object from the command line - arguments. `-` represents `stdin`. + arguments. `"-"` represents `stdin`. */ - static fn from_args() -> FileInput { + pub fn from_args() -> FileInput { let args = os::args(), pathed = pathify(args.tail(), true); FileInput::from_vec(pathed) } priv fn current_file_eof(&self) -> bool { - match self.current_reader { + match self.fi.current_reader { None => false, Some(r) => r.eof() } @@ -180,110 +205,143 @@ impl FileInput { /** Skip to the next file in the queue. Can `fail` when opening a file. + + Returns `false` if there is no more files, and `true` when it + successfully opens the next file. */ - pub fn next_file(&mut self) { + + pub fn next_file(&self) -> bool { // No more files - if self.files.is_empty() { - self.current_reader = None; - return; + + // Compiler whines about "illegal borrow unless pure" for + // files.is_empty() + if unsafe { self.fi.files.is_empty() } { + self.fi.current_reader = None; + return false; } - let path_option = self.files.shift(), + let path_option = self.fi.files.shift(), file = match path_option { None => io::stdin(), Some(ref path) => io::file_reader(path).get() }; - self.current_reader = Some(file); - self.state.current_path = path_option; - self.state.line_num_file = 0; + self.fi.current_reader = Some(file); + self.fi.state.current_path = path_option; + self.fi.state.line_num_file = 0; + true } /** Attempt to open the next file if there is none currently open, or if the current one is EOF'd. + + Returns `true` if it had to move to the next file and did + so successfully. */ - priv fn next_file_if_eof(&mut self) { - match self.current_reader { + priv fn next_file_if_eof(&self) -> bool { + match self.fi.current_reader { None => self.next_file(), Some(r) => { if r.eof() { self.next_file() + } else { + false } } } } /** - Read a single line. Returns `None` if there are no remaining lines - in any remaining file. (Automatically opens files as required, see - `next_file` for details.) + Apply `f` to each line successively, along with some state + (line numbers and file names, see documentation for + `FileInputState`). Otherwise identical to `lines_each`. + */ + pub fn each_line_state(&self, + f: &fn(&str, FileInputState) -> bool) { + self.each_line(|line| f(line, copy self.fi.state)); + } - (Name to avoid conflicting with `core::io::ReaderUtil::read_line`.) + + /** + Retrieve the current `FileInputState` information. */ - pub fn next_line(&mut self) -> Option<~str> { + pub fn state(&self) -> FileInputState { + copy self.fi.state + } +} + +impl io::Reader for FileInput { + fn read_byte(&self) -> int { loop { - // iterate until there is a file that can be read from - self.next_file_if_eof(); - match self.current_reader { - None => { - // no file has any content - return None; - }, + let stepped = self.next_file_if_eof(); + + // if we moved to the next file, and the previous + // character wasn't \n, then there is an unfinished line + // from the previous file. This library models + // line-by-line processing and the trailing line of the + // previous file and the leading of the current file + // should be considered different, so we need to insert a + // fake line separator + if stepped && !self.fi.previous_was_newline { + self.fi.state.line_num += 1; + self.fi.state.line_num_file += 1; + self.fi.previous_was_newline = true; + return '\n' as int; + } + + match self.fi.current_reader { + None => return -1, Some(r) => { - let l = r.read_line(); + let b = r.read_byte(); - // at the end of this file, and we read nothing, so - // go to the next file - if r.eof() && l.is_empty() { + if b < 0 { loop; } - self.state.line_num += 1; - self.state.line_num_file += 1; - return Some(l); + + if b == '\n' as int { + self.fi.state.line_num += 1; + self.fi.state.line_num_file += 1; + self.fi.previous_was_newline = true; + } else { + self.fi.previous_was_newline = false; + } + + return b; } } } } + fn read(&self, buf: &mut [u8], len: uint) -> uint { + let mut count = 0; + while count < len { + let b = self.read_byte(); + if b < 0 { break } + + buf[count] = b as u8; + count += 1; + } - /** - Call `f` on the lines in the files in succession, stopping if - it ever returns `false`. + count + } + fn eof(&self) -> bool { + // we've run out of files, and current_reader is either None or eof. - State is preserved across calls. + // compiler whines about illegal borrows for files.is_empty() + (unsafe { self.fi.files.is_empty() }) && + match self.fi.current_reader { None => true, Some(r) => r.eof() } - (The name is to avoid conflict with - `core::io::ReaderUtil::each_line`.) - */ - pub fn lines_each(&mut self, f: &fn(~str) -> bool) { - loop { - match self.next_line() { - None => break, - Some(line) => { - if !f(line) { - break; - } - } - } + } + fn seek(&self, offset: int, whence: io::SeekStyle) { + match self.fi.current_reader { + None => {}, + Some(r) => r.seek(offset, whence) } } - - /** - Apply `f` to each line successively, along with some state - (line numbers and file names, see documentation for - `FileInputState`). Otherwise identical to `lines_each`. - */ - pub fn lines_each_state(&mut self, - f: &fn(~str, &FileInputState) -> bool) { - loop { - match self.next_line() { - None => break, - Some(line) => { - if !f(line, &self.state) { - break; - } - } - } + fn tell(&self) -> uint { + match self.fi.current_reader { + None => 0, + Some(r) => r.tell() } } } @@ -291,7 +349,7 @@ impl FileInput { /** Convert a list of strings to an appropriate form for a `FileInput` instance. `stdin_hyphen` controls whether `-` represents `stdin` or -not. +a literal `-`. */ // XXX: stupid, unclear name pub fn pathify(vec: &[~str], stdin_hyphen : bool) -> ~[Option] { @@ -310,9 +368,9 @@ reading from `stdin`). Fails when attempting to read from a file that can't be opened. */ -pub fn input(f: &fn(~str) -> bool) { +pub fn input(f: &fn(&str) -> bool) { let mut i = FileInput::from_args(); - i.lines_each(f); + i.each_line(f); } /** @@ -322,31 +380,31 @@ provided at each call. Fails when attempting to read from a file that can't be opened. */ -pub fn input_state(f: &fn(~str, &FileInputState) -> bool) { +pub fn input_state(f: &fn(&str, FileInputState) -> bool) { let mut i = FileInput::from_args(); - i.lines_each_state(f); + i.each_line_state(f); } /** -Iterate over a vec of files (an empty vec implies just `stdin`). +Iterate over a vector of files (an empty vector implies just `stdin`). Fails when attempting to read from a file that can't be opened. */ -pub fn input_vec(files: ~[Option], f: &fn(~str) -> bool) { +pub fn input_vec(files: ~[Option], f: &fn(&str) -> bool) { let mut i = FileInput::from_vec(files); - i.lines_each(f); + i.each_line(f); } /** -Iterate over a vec of files (an empty vec implies just `stdin`) with -the current state of the iteration provided at each call. +Iterate over a vector of files (an empty vector implies just `stdin`) +with the current state of the iteration provided at each call. Fails when attempting to read from a file that can't be opened. */ pub fn input_vec_state(files: ~[Option], - f: &fn(~str, &FileInputState) -> bool) { + f: &fn(&str, FileInputState) -> bool) { let mut i = FileInput::from_vec(files); - i.lines_each_state(f); + i.each_line_state(f); } #[cfg(test)] @@ -371,11 +429,61 @@ mod test { paths = ~[Some(Path("some/path")), Some(Path("some/other/path"))]; - fail_unless!(pathify(strs, true) == paths); - fail_unless!(pathify(strs, false) == paths); + assert_eq!(pathify(strs, true), copy paths); + assert_eq!(pathify(strs, false), paths); - fail_unless!(pathify([~"-"], true) == ~[None]); - fail_unless!(pathify([~"-"], false) == ~[Some(Path("-"))]); + assert_eq!(pathify([~"-"], true), ~[None]); + assert_eq!(pathify([~"-"], false), ~[Some(Path("-"))]); + } + + #[test] + fn test_fileinput_read_byte() { + let filenames = pathify(vec::from_fn( + 3, + |i| fmt!("tmp/lib-fileinput-test-fileinput-read-byte-%u.tmp", i)), true); + + // 3 files containing 0\n, 1\n, and 2\n respectively + for filenames.eachi |i, &filename| { + make_file(filename.get_ref(), ~[fmt!("%u", i)]); + } + + let fi = FileInput::from_vec(copy filenames); + + for "012".each_chari |line, c| { + assert_eq!(fi.read_byte(), c as int); + assert_eq!(fi.state().line_num, line); + assert_eq!(fi.state().line_num_file, 0); + assert_eq!(fi.read_byte(), '\n' as int); + assert_eq!(fi.state().line_num, line + 1); + assert_eq!(fi.state().line_num_file, 1); + + assert_eq!(copy fi.state().current_path, copy filenames[line]); + } + + assert_eq!(fi.read_byte(), -1); + fail_unless!(fi.eof()); + assert_eq!(fi.state().line_num, 3) + + } + + #[test] + fn test_fileinput_read() { + let filenames = pathify(vec::from_fn( + 3, + |i| fmt!("tmp/lib-fileinput-test-fileinput-read-%u.tmp", i)), true); + + // 3 files containing 1\n, 2\n, and 3\n respectively + for filenames.eachi |i, &filename| { + make_file(filename.get_ref(), ~[fmt!("%u", i)]); + } + + let fi = FileInput::from_vec(filenames); + let mut buf : ~[u8] = vec::from_elem(6, 0u8); + let count = fi.read(buf, 10); + assert_eq!(count, 6); + assert_eq!(buf, "0\n1\n2\n".to_bytes()); + fail_unless!(fi.eof()) + assert_eq!(fi.state().line_num, 3); } #[test] @@ -388,47 +496,84 @@ mod test { for filenames.eachi |i, &filename| { let contents = vec::from_fn(3, |j| fmt!("%u %u", i, j)); - make_file(&filename.get(), contents); + make_file(filename.get_ref(), contents); all_lines.push_all(contents); } let mut read_lines = ~[]; for input_vec(filenames) |line| { - read_lines.push(line); + read_lines.push(line.to_owned()); } - fail_unless!(read_lines == all_lines); + assert_eq!(read_lines, all_lines); } #[test] fn test_input_vec_state() { let filenames = pathify(vec::from_fn( 3, - |i| - fmt!("tmp/lib-fileinput-test-input-vec-state-%u.tmp", i)),true); + |i| fmt!("tmp/lib-fileinput-test-input-vec-state-%u.tmp", i)),true); for filenames.eachi |i, &filename| { let contents = vec::from_fn(3, |j| fmt!("%u %u", i, j + 1)); - make_file(&filename.get(), contents); + make_file(filename.get_ref(), contents); } for input_vec_state(filenames) |line, state| { let nums = str::split_char(line, ' '); - let file_num = uint::from_str(nums[0]).get(); let line_num = uint::from_str(nums[1]).get(); + assert_eq!(line_num, state.line_num_file); + assert_eq!(file_num * 3 + line_num, state.line_num); + } + } + + #[test] + fn test_empty_files() { + let filenames = pathify(vec::from_fn( + 3, + |i| fmt!("tmp/lib-fileinput-test-next-file-%u.tmp", i)),true); + + make_file(filenames[0].get_ref(), ~[~"1", ~"2"]); + make_file(filenames[1].get_ref(), ~[]); + make_file(filenames[2].get_ref(), ~[~"3", ~"4"]); + + let mut count = 0; + for input_vec_state(copy filenames) |line, state| { + let expected_path = match line { + "1" | "2" => copy filenames[0], + "3" | "4" => copy filenames[2], + _ => fail!(~"unexpected line") + }; + assert_eq!(copy state.current_path, expected_path); + count += 1; + } + assert_eq!(count, 4); + } - fail_unless!(line_num == state.line_num_file); - fail_unless!(file_num * 3 + line_num == state.line_num); + #[test] + fn test_no_trailing_newline() { + let f1 = Some(Path("tmp/lib-fileinput-test-no-trailing-newline-1.tmp")), + f2 = Some(Path("tmp/lib-fileinput-test-no-trailing-newline-2.tmp")); + + let wr = io::file_writer(f1.get_ref(), [io::Create, io::Truncate]).get(); + wr.write_str("1\n2"); + let wr = io::file_writer(f2.get_ref(), [io::Create, io::Truncate]).get(); + wr.write_str("3\n4"); + + let mut lines = ~[]; + for input_vec(~[f1, f2]) |line| { + lines.push(line.to_owned()); } + assert_eq!(lines, ~[~"1", ~"2", ~"3", ~"4"]); } + #[test] fn test_next_file() { let filenames = pathify(vec::from_fn( 3, - |i| - fmt!("tmp/lib-fileinput-test-next-file-%u.tmp", i)),true); + |i| fmt!("tmp/lib-fileinput-test-next-file-%u.tmp", i)),true); for filenames.eachi |i, &filename| { let contents = @@ -439,19 +584,19 @@ mod test { let mut in = FileInput::from_vec(filenames); // read once from 0 - fail_unless!(in.next_line() == Some(~"0 1")); + assert_eq!(in.read_line(), ~"0 1"); in.next_file(); // skip the rest of 1 // read all lines from 1 (but don't read any from 2), for uint::range(1, 4) |i| { - fail_unless!(in.next_line() == Some(fmt!("1 %u", i))); + assert_eq!(in.read_line(), fmt!("1 %u", i)); } // 1 is finished, but 2 hasn't been started yet, so this will // just "skip" to the beginning of 2 (Python's fileinput does // the same) in.next_file(); - fail_unless!(in.next_line() == Some(~"2 1")); + assert_eq!(in.read_line(), ~"2 1"); } #[test] From fea1380a9a0ca94738132db4d51ec4bd86bac3dd Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 3 Apr 2013 12:38:14 +1100 Subject: [PATCH 12/35] libstd: make fileinput tests pass. --- src/libstd/fileinput.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/libstd/fileinput.rs b/src/libstd/fileinput.rs index 0056b34eccbca..df733425f3ef0 100644 --- a/src/libstd/fileinput.rs +++ b/src/libstd/fileinput.rs @@ -461,7 +461,7 @@ mod test { } assert_eq!(fi.read_byte(), -1); - fail_unless!(fi.eof()); + assert!(fi.eof()); assert_eq!(fi.state().line_num, 3) } @@ -482,7 +482,7 @@ mod test { let count = fi.read(buf, 10); assert_eq!(count, 6); assert_eq!(buf, "0\n1\n2\n".to_bytes()); - fail_unless!(fi.eof()) + assert!(fi.eof()) assert_eq!(fi.state().line_num, 3); } @@ -520,7 +520,9 @@ mod test { } for input_vec_state(filenames) |line, state| { - let nums = str::split_char(line, ' '); + let nums = do vec::build |p| { + for str::each_split_char(line, ' ') |s| { p(s.to_owned()); } + }; let file_num = uint::from_str(nums[0]).get(); let line_num = uint::from_str(nums[1]).get(); assert_eq!(line_num, state.line_num_file); From e2bffb79717f7622e97870c3194435b06e3e56bc Mon Sep 17 00:00:00 2001 From: James Miller Date: Wed, 3 Apr 2013 19:40:27 +1300 Subject: [PATCH 13/35] Implement Clone for tuples --- src/libcore/tuple.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index a5c86d592c636..35b8496f6c57e 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -10,6 +10,7 @@ //! Operations on tuples +use clone::Clone; use kinds::Copy; use vec; @@ -46,6 +47,15 @@ impl CopyableTuple for (T, U) { } +impl Clone for (T, U) { + fn clone(&self) -> (T, U) { + let (a, b) = match *self { + (ref a, ref b) => (a, b) + }; + (a.clone(), b.clone()) + } +} + pub trait ImmutableTuple { fn first_ref(&self) -> &'self T; fn second_ref(&self) -> &'self U; @@ -252,3 +262,10 @@ fn test_tuple() { assert!(('a', 2).swap() == (2, 'a')); } +#[test] +fn test_clone() { + let a = (1, ~"2"); + let b = a.clone(); + assert!(a.first() == b.first()); + assert!(a.second() == b.second()); +} From 84e503346672dfc5d237e90e49ed42a2ae3641b4 Mon Sep 17 00:00:00 2001 From: Ben Striegel Date: Wed, 3 Apr 2013 06:54:14 -0400 Subject: [PATCH 14/35] Make bench/noise.rs more idiomatic and 20x faster --- src/test/bench/noise.rs | 61 +++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/src/test/bench/noise.rs b/src/test/bench/noise.rs index d28382abaa386..4397dcd5247f5 100644 --- a/src/test/bench/noise.rs +++ b/src/test/bench/noise.rs @@ -1,25 +1,28 @@ // Perlin noise benchmark from https://gist.github.com/1170424 -use core::rand::RngUtil; +use core::rand::{Rng, RngUtil}; struct Vec2 { x: f32, y: f32, } -fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v } -fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) } +#[inline(always)] +fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v } -fn random_gradient(r: @rand::Rng) -> Vec2 { +#[inline(always)] +fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) } + +fn random_gradient(r: @Rng) -> Vec2 { let v = r.gen_float() * float::consts::pi * 2.0; - Vec2{ + Vec2 { x: float::cos(v) as f32, y: float::sin(v) as f32, } } fn gradient(orig: Vec2, grad: Vec2, p: Vec2) -> f32 { - let sp = Vec2{x: p.x - orig.x, y: p.y - orig.y}; + let sp = Vec2 {x: p.x - orig.x, y: p.y - orig.y}; grad.x * sp.x + grad.y + sp.y } @@ -28,28 +31,28 @@ struct Noise2DContext { permutations: [int, ..256], } -fn Noise2DContext() -> ~Noise2DContext { - let r = rand::Rng(); - let mut rgradients = [ Vec2 { x: 0.0, y: 0.0 }, ..256 ]; - for int::range(0, 256) |i| { rgradients[i] = random_gradient(r); } - let mut permutations = [ 0, ..256 ]; - for int::range(0, 256) |i| { permutations[i] = i; } - r.shuffle_mut(permutations); - - ~Noise2DContext{ - rgradients: rgradients, - permutations: permutations, +pub impl Noise2DContext { + fn new() -> Noise2DContext { + let r = rand::Rng(); + let mut rgradients = [ Vec2 { x: 0.0, y: 0.0 }, ..256 ]; + for int::range(0, 256) |i| { rgradients[i] = random_gradient(r); } + let mut permutations = [ 0, ..256 ]; + for int::range(0, 256) |i| { permutations[i] = i; } + r.shuffle_mut(permutations); + + Noise2DContext { + rgradients: rgradients, + permutations: permutations, + } } -} -pub impl Noise2DContext { #[inline(always)] fn get_gradient(&self, x: int, y: int) -> Vec2 { let idx = self.permutations[x & 255] + self.permutations[y & 255]; self.rgradients[idx & 255] } - #[inline(always)] + #[inline] fn get_gradients(&self, gradients: &mut [Vec2, ..4], origins: &mut [Vec2, ..4], x: f32, y: f32) { let x0f = f32::floor(x); let y0f = f32::floor(y); @@ -63,14 +66,15 @@ pub impl Noise2DContext { gradients[2] = self.get_gradient(x0, y1); gradients[3] = self.get_gradient(x1, y1); - origins[0] = Vec2{x: x0f + 0.0, y: y0f + 0.0}; - origins[1] = Vec2{x: x0f + 1.0, y: y0f + 0.0}; - origins[2] = Vec2{x: x0f + 0.0, y: y0f + 1.0}; - origins[3] = Vec2{x: x0f + 1.0, y: y0f + 1.0}; + origins[0] = Vec2 {x: x0f + 0.0, y: y0f + 0.0}; + origins[1] = Vec2 {x: x0f + 1.0, y: y0f + 0.0}; + origins[2] = Vec2 {x: x0f + 0.0, y: y0f + 1.0}; + origins[3] = Vec2 {x: x0f + 1.0, y: y0f + 1.0}; } + #[inline] fn get(&self, x: f32, y: f32) -> f32 { - let p = Vec2{x: x, y: y}; + let p = Vec2 {x: x, y: y}; let mut gradients = [ Vec2 { x: 0.0, y: 0.0 }, ..4 ]; let mut origins = [ Vec2 { x: 0.0, y: 0.0 }, ..4 ]; self.get_gradients(&mut gradients, &mut origins, x, y); @@ -88,9 +92,9 @@ pub impl Noise2DContext { fn main() { let symbols = [" ", "░", "▒", "▓", "█", "█"]; - let mut pixels = vec::from_elem(256*256, 0f32); - let n2d = Noise2DContext(); - for int::range(0, 100) |_| { + let mut pixels = [0f32, ..256*256]; + let n2d = ~Noise2DContext::new(); + for 100.times { for int::range(0, 256) |y| { for int::range(0, 256) |x| { let v = n2d.get( @@ -109,4 +113,3 @@ fn main() { io::println(""); }*/ } - From 44029a5bbc4812f7144ee8d0d4ee95d52aeca6cf Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Wed, 3 Apr 2013 08:45:14 -0400 Subject: [PATCH 15/35] hashmap: rm linear namespace --- doc/rust.md | 2 +- doc/tutorial.md | 2 +- src/libcore/gc.rs | 2 +- src/libcore/hashmap.rs | 1700 ++++++++--------- src/libcore/task/spawn.rs | 2 +- src/libcore/unstable/global.rs | 2 +- src/libcore/unstable/weak_task.rs | 2 +- src/librustc/back/rpath.rs | 2 +- src/librustc/lib/llvm.rs | 2 +- src/librustc/metadata/creader.rs | 2 +- src/librustc/metadata/cstore.rs | 2 +- src/librustc/metadata/encoder.rs | 2 +- src/librustc/metadata/tyencode.rs | 2 +- src/librustc/middle/borrowck/check_loans.rs | 2 +- src/librustc/middle/borrowck/gather_loans.rs | 2 +- src/librustc/middle/borrowck/mod.rs | 2 +- src/librustc/middle/const_eval.rs | 2 +- src/librustc/middle/freevars.rs | 2 +- src/librustc/middle/lang_items.rs | 2 +- src/librustc/middle/lint.rs | 2 +- src/librustc/middle/liveness.rs | 2 +- src/librustc/middle/moves.rs | 2 +- src/librustc/middle/pat_util.rs | 2 +- src/librustc/middle/region.rs | 2 +- src/librustc/middle/resolve.rs | 2 +- src/librustc/middle/trans/_match.rs | 2 +- src/librustc/middle/trans/base.rs | 2 +- src/librustc/middle/trans/build.rs | 2 +- src/librustc/middle/trans/common.rs | 2 +- src/librustc/middle/trans/debuginfo.rs | 2 +- src/librustc/middle/trans/expr.rs | 2 +- src/librustc/middle/trans/reachable.rs | 2 +- src/librustc/middle/ty.rs | 2 +- src/librustc/middle/typeck/check/_match.rs | 2 +- src/librustc/middle/typeck/check/method.rs | 2 +- src/librustc/middle/typeck/check/mod.rs | 2 +- src/librustc/middle/typeck/check/vtable.rs | 2 +- src/librustc/middle/typeck/coherence.rs | 2 +- .../middle/typeck/infer/region_inference.rs | 2 +- src/librustc/middle/typeck/mod.rs | 2 +- src/librustc/util/common.rs | 2 +- src/librustpkg/rustpkg.rc | 2 +- src/librustpkg/util.rs | 2 +- src/libstd/json.rs | 4 +- src/libstd/net_url.rs | 4 +- src/libstd/serialize.rs | 2 +- src/libstd/workcache.rs | 2 +- src/libsyntax/ast_map.rs | 2 +- src/libsyntax/attr.rs | 2 +- src/libsyntax/ext/base.rs | 4 +- src/libsyntax/ext/tt/macro_parser.rs | 2 +- src/libsyntax/ext/tt/transcribe.rs | 2 +- src/libsyntax/parse/parser.rs | 2 +- src/libsyntax/parse/token.rs | 2 +- src/libsyntax/util/interner.rs | 2 +- src/test/auxiliary/issue-2631-a.rs | 2 +- src/test/bench/core-map.rs | 2 +- src/test/bench/core-set.rs | 2 +- src/test/bench/graph500-bfs.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 2 +- src/test/bench/shootout-mandelbrot.rs | 2 +- .../borrowck-borrowed-uniq-rvalue.rs | 2 +- .../borrowck-insert-during-each.rs | 2 +- src/test/compile-fail/for-loop-decl.rs | 2 +- src/test/compile-fail/map-types.rs | 2 +- src/test/run-fail/unwind-misc-1.rs | 2 +- src/test/run-pass/hashmap-memory.rs | 2 +- src/test/run-pass/issue-1696.rs | 2 +- src/test/run-pass/issue-2631-b.rs | 2 +- src/test/run-pass/issue-2804-2.rs | 2 +- src/test/run-pass/issue-2804.rs | 2 +- src/test/run-pass/issue-3026.rs | 2 +- src/test/run-pass/issue-3559.rs | 2 +- src/test/run-pass/issue-4016.rs | 2 +- src/test/run-pass/issue-4092.rs | 2 +- 75 files changed, 925 insertions(+), 929 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index c6dba96267679..64f0dc93e7867 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -441,7 +441,7 @@ expression context, the final namespace qualifier is omitted. Two examples of paths with type arguments: ~~~~ -# use core::hashmap::linear::LinearMap; +# use core::hashmap::LinearMap; # fn f() { # fn id(t: T) -> T { t } type t = LinearMap; // Type arguments used in a type expression diff --git a/doc/tutorial.md b/doc/tutorial.md index 42b0d5a585aee..8c5294767c26a 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1888,7 +1888,7 @@ illegal to copy and pass by value. Generic `type`, `struct`, and `enum` declarations follow the same pattern: ~~~~ -# use core::hashmap::linear::LinearMap; +# use core::hashmap::LinearMap; type Set = LinearMap; struct Stack { diff --git a/src/libcore/gc.rs b/src/libcore/gc.rs index 2f35c1e0bb15e..46f2ad76d0792 100644 --- a/src/libcore/gc.rs +++ b/src/libcore/gc.rs @@ -43,7 +43,7 @@ use io; use libc::{size_t, uintptr_t}; use option::{None, Option, Some}; use ptr; -use hashmap::linear::LinearSet; +use hashmap::LinearSet; use stackwalk; use sys; diff --git a/src/libcore/hashmap.rs b/src/libcore/hashmap.rs index 9387ec4f43209..67942abba4633 100644 --- a/src/libcore/hashmap.rs +++ b/src/libcore/hashmap.rs @@ -13,1013 +13,1009 @@ //! The tables use a keyed hash with new random keys generated for each container, so the ordering //! of a set of keys in a hash table is randomized. -/// Open addressing with linear probing. -pub mod linear { - use container::{Container, Mutable, Map, Set}; - use cmp::{Eq, Equiv}; - use hash::Hash; - use to_bytes::IterBytes; - use iter::BaseIter; - use hash::Hash; - use iter; - use option::{None, Option, Some}; - use rand::RngUtil; - use rand; - use uint; - use vec; - use util::unreachable; +use container::{Container, Mutable, Map, Set}; +use cmp::{Eq, Equiv}; +use hash::Hash; +use to_bytes::IterBytes; +use iter::BaseIter; +use hash::Hash; +use iter; +use option::{None, Option, Some}; +use rand::RngUtil; +use rand; +use uint; +use vec; +use util::unreachable; + +static INITIAL_CAPACITY: uint = 32u; // 2^5 + +struct Bucket { + hash: uint, + key: K, + value: V, +} - static INITIAL_CAPACITY: uint = 32u; // 2^5 +pub struct LinearMap { + priv k0: u64, + priv k1: u64, + priv resize_at: uint, + priv size: uint, + priv buckets: ~[Option>], +} - struct Bucket { - hash: uint, - key: K, - value: V, - } +// We could rewrite FoundEntry to have type Option<&Bucket> +// which would be nifty +enum SearchResult { + FoundEntry(uint), FoundHole(uint), TableFull +} - pub struct LinearMap { - priv k0: u64, - priv k1: u64, - priv resize_at: uint, - priv size: uint, - priv buckets: ~[Option>], - } +#[inline(always)] +fn resize_at(capacity: uint) -> uint { + ((capacity as float) * 3. / 4.) as uint +} - // We could rewrite FoundEntry to have type Option<&Bucket> - // which would be nifty - enum SearchResult { - FoundEntry(uint), FoundHole(uint), TableFull +pub fn linear_map_with_capacity( + initial_capacity: uint) -> LinearMap { + let r = rand::task_rng(); + linear_map_with_capacity_and_keys(r.gen_u64(), r.gen_u64(), + initial_capacity) +} + +fn linear_map_with_capacity_and_keys( + k0: u64, k1: u64, + initial_capacity: uint) -> LinearMap { + LinearMap { + k0: k0, k1: k1, + resize_at: resize_at(initial_capacity), + size: 0, + buckets: vec::from_fn(initial_capacity, |_| None) } +} +priv impl LinearMap { #[inline(always)] - fn resize_at(capacity: uint) -> uint { - ((capacity as float) * 3. / 4.) as uint + fn to_bucket(&self, h: uint) -> uint { + // A good hash function with entropy spread over all of the + // bits is assumed. SipHash is more than good enough. + h % self.buckets.len() } - pub fn linear_map_with_capacity( - initial_capacity: uint) -> LinearMap { - let r = rand::task_rng(); - linear_map_with_capacity_and_keys(r.gen_u64(), r.gen_u64(), - initial_capacity) + #[inline(always)] + fn next_bucket(&self, idx: uint, len_buckets: uint) -> uint { + let n = (idx + 1) % len_buckets; + debug!("next_bucket(%?, %?) = %?", idx, len_buckets, n); + n } - fn linear_map_with_capacity_and_keys( - k0: u64, k1: u64, - initial_capacity: uint) -> LinearMap { - LinearMap { - k0: k0, k1: k1, - resize_at: resize_at(initial_capacity), - size: 0, - buckets: vec::from_fn(initial_capacity, |_| None) + #[inline(always)] + fn bucket_sequence(&self, hash: uint, + op: &fn(uint) -> bool) -> uint { + let start_idx = self.to_bucket(hash); + let len_buckets = self.buckets.len(); + let mut idx = start_idx; + loop { + if !op(idx) { + return idx; + } + idx = self.next_bucket(idx, len_buckets); + if idx == start_idx { + return start_idx; + } } } - priv impl LinearMap { - #[inline(always)] - fn to_bucket(&self, h: uint) -> uint { - // A good hash function with entropy spread over all of the - // bits is assumed. SipHash is more than good enough. - h % self.buckets.len() - } + #[inline(always)] + fn bucket_for_key(&self, k: &K) -> SearchResult { + let hash = k.hash_keyed(self.k0, self.k1) as uint; + self.bucket_for_key_with_hash(hash, k) + } - #[inline(always)] - fn next_bucket(&self, idx: uint, len_buckets: uint) -> uint { - let n = (idx + 1) % len_buckets; - debug!("next_bucket(%?, %?) = %?", idx, len_buckets, n); - n - } + #[inline(always)] + fn bucket_for_key_equiv>(&self, + k: &Q) + -> SearchResult { + let hash = k.hash_keyed(self.k0, self.k1) as uint; + self.bucket_for_key_with_hash_equiv(hash, k) + } - #[inline(always)] - fn bucket_sequence(&self, hash: uint, - op: &fn(uint) -> bool) -> uint { - let start_idx = self.to_bucket(hash); - let len_buckets = self.buckets.len(); - let mut idx = start_idx; - loop { - if !op(idx) { - return idx; - } - idx = self.next_bucket(idx, len_buckets); - if idx == start_idx { - return start_idx; - } + #[inline(always)] + fn bucket_for_key_with_hash(&self, + hash: uint, + k: &K) + -> SearchResult { + let _ = for self.bucket_sequence(hash) |i| { + match self.buckets[i] { + Some(ref bkt) => if bkt.hash == hash && *k == bkt.key { + return FoundEntry(i); + }, + None => return FoundHole(i) } - } - - #[inline(always)] - fn bucket_for_key(&self, k: &K) -> SearchResult { - let hash = k.hash_keyed(self.k0, self.k1) as uint; - self.bucket_for_key_with_hash(hash, k) - } - - #[inline(always)] - fn bucket_for_key_equiv>(&self, - k: &Q) - -> SearchResult { - let hash = k.hash_keyed(self.k0, self.k1) as uint; - self.bucket_for_key_with_hash_equiv(hash, k) - } + }; + TableFull + } - #[inline(always)] - fn bucket_for_key_with_hash(&self, - hash: uint, - k: &K) - -> SearchResult { - let _ = for self.bucket_sequence(hash) |i| { - match self.buckets[i] { - Some(ref bkt) => if bkt.hash == hash && *k == bkt.key { + #[inline(always)] + fn bucket_for_key_with_hash_equiv>(&self, + hash: uint, + k: &Q) + -> SearchResult { + let _ = for self.bucket_sequence(hash) |i| { + match self.buckets[i] { + Some(ref bkt) => { + if bkt.hash == hash && k.equiv(&bkt.key) { return FoundEntry(i); - }, - None => return FoundHole(i) - } - }; - TableFull - } - - #[inline(always)] - fn bucket_for_key_with_hash_equiv>(&self, - hash: uint, - k: &Q) - -> SearchResult { - let _ = for self.bucket_sequence(hash) |i| { - match self.buckets[i] { - Some(ref bkt) => { - if bkt.hash == hash && k.equiv(&bkt.key) { - return FoundEntry(i); - } - }, - None => return FoundHole(i) - } - }; - TableFull - } + } + }, + None => return FoundHole(i) + } + }; + TableFull + } - /// Expand the capacity of the array to the next power of two - /// and re-insert each of the existing buckets. - #[inline(always)] - fn expand(&mut self) { - let new_capacity = self.buckets.len() * 2; - self.resize(new_capacity); - } + /// Expand the capacity of the array to the next power of two + /// and re-insert each of the existing buckets. + #[inline(always)] + fn expand(&mut self) { + let new_capacity = self.buckets.len() * 2; + self.resize(new_capacity); + } - /// Expands the capacity of the array and re-insert each of the - /// existing buckets. - fn resize(&mut self, new_capacity: uint) { - let old_capacity = self.buckets.len(); - self.resize_at = resize_at(new_capacity); + /// Expands the capacity of the array and re-insert each of the + /// existing buckets. + fn resize(&mut self, new_capacity: uint) { + let old_capacity = self.buckets.len(); + self.resize_at = resize_at(new_capacity); - let mut old_buckets = vec::from_fn(new_capacity, |_| None); - self.buckets <-> old_buckets; + let mut old_buckets = vec::from_fn(new_capacity, |_| None); + self.buckets <-> old_buckets; - self.size = 0; - for uint::range(0, old_capacity) |i| { - let mut bucket = None; - bucket <-> old_buckets[i]; - self.insert_opt_bucket(bucket); - } + self.size = 0; + for uint::range(0, old_capacity) |i| { + let mut bucket = None; + bucket <-> old_buckets[i]; + self.insert_opt_bucket(bucket); } + } - fn insert_opt_bucket(&mut self, bucket: Option>) { - match bucket { - Some(Bucket{hash: hash, key: key, value: value}) => { - self.insert_internal(hash, key, value); - } - None => {} + fn insert_opt_bucket(&mut self, bucket: Option>) { + match bucket { + Some(Bucket{hash: hash, key: key, value: value}) => { + self.insert_internal(hash, key, value); } + None => {} } + } - #[inline(always)] - fn value_for_bucket(&self, idx: uint) -> &'self V { - match self.buckets[idx] { - Some(ref bkt) => &bkt.value, - None => fail!(~"LinearMap::find: internal logic error"), - } + #[inline(always)] + fn value_for_bucket(&self, idx: uint) -> &'self V { + match self.buckets[idx] { + Some(ref bkt) => &bkt.value, + None => fail!(~"LinearMap::find: internal logic error"), } + } - #[inline(always)] - fn mut_value_for_bucket(&mut self, idx: uint) -> &'self mut V { - match self.buckets[idx] { - Some(ref mut bkt) => &mut bkt.value, - None => unreachable() - } + #[inline(always)] + fn mut_value_for_bucket(&mut self, idx: uint) -> &'self mut V { + match self.buckets[idx] { + Some(ref mut bkt) => &mut bkt.value, + None => unreachable() } + } - /// Inserts the key value pair into the buckets. - /// Assumes that there will be a bucket. - /// True if there was no previous entry with that key - fn insert_internal(&mut self, hash: uint, k: K, v: V) -> bool { - match self.bucket_for_key_with_hash(hash, &k) { - TableFull => { fail!(~"Internal logic error"); } - FoundHole(idx) => { - debug!("insert fresh (%?->%?) at idx %?, hash %?", - k, v, idx, hash); - self.buckets[idx] = Some(Bucket{hash: hash, key: k, - value: v}); - self.size += 1; - true - } - FoundEntry(idx) => { - debug!("insert overwrite (%?->%?) at idx %?, hash %?", - k, v, idx, hash); - self.buckets[idx] = Some(Bucket{hash: hash, key: k, - value: v}); - false - } + /// Inserts the key value pair into the buckets. + /// Assumes that there will be a bucket. + /// True if there was no previous entry with that key + fn insert_internal(&mut self, hash: uint, k: K, v: V) -> bool { + match self.bucket_for_key_with_hash(hash, &k) { + TableFull => { fail!(~"Internal logic error"); } + FoundHole(idx) => { + debug!("insert fresh (%?->%?) at idx %?, hash %?", + k, v, idx, hash); + self.buckets[idx] = Some(Bucket{hash: hash, key: k, + value: v}); + self.size += 1; + true + } + FoundEntry(idx) => { + debug!("insert overwrite (%?->%?) at idx %?, hash %?", + k, v, idx, hash); + self.buckets[idx] = Some(Bucket{hash: hash, key: k, + value: v}); + false } } + } - fn pop_internal(&mut self, hash: uint, k: &K) -> Option { - // Removing from an open-addressed hashtable - // is, well, painful. The problem is that - // the entry may lie on the probe path for other - // entries, so removing it would make you think that - // those probe paths are empty. - // - // To address this we basically have to keep walking, - // re-inserting entries we find until we reach an empty - // bucket. We know we will eventually reach one because - // we insert one ourselves at the beginning (the removed - // entry). - // - // I found this explanation elucidating: - // http://www.maths.lse.ac.uk/Courses/MA407/del-hash.pdf - let mut idx = match self.bucket_for_key_with_hash(hash, k) { - TableFull | FoundHole(_) => return None, - FoundEntry(idx) => idx - }; - - let len_buckets = self.buckets.len(); + fn pop_internal(&mut self, hash: uint, k: &K) -> Option { + // Removing from an open-addressed hashtable + // is, well, painful. The problem is that + // the entry may lie on the probe path for other + // entries, so removing it would make you think that + // those probe paths are empty. + // + // To address this we basically have to keep walking, + // re-inserting entries we find until we reach an empty + // bucket. We know we will eventually reach one because + // we insert one ourselves at the beginning (the removed + // entry). + // + // I found this explanation elucidating: + // http://www.maths.lse.ac.uk/Courses/MA407/del-hash.pdf + let mut idx = match self.bucket_for_key_with_hash(hash, k) { + TableFull | FoundHole(_) => return None, + FoundEntry(idx) => idx + }; + + let len_buckets = self.buckets.len(); + let mut bucket = None; + self.buckets[idx] <-> bucket; + + let value = match bucket { + None => None, + Some(bucket) => { + let Bucket{value: value, _} = bucket; + Some(value) + }, + }; + + /* re-inserting buckets may cause changes in size, so remember + what our new size is ahead of time before we start insertions */ + let size = self.size - 1; + idx = self.next_bucket(idx, len_buckets); + while self.buckets[idx].is_some() { let mut bucket = None; - self.buckets[idx] <-> bucket; - - let value = match bucket { - None => None, - Some(bucket) => { - let Bucket{value: value, _} = bucket; - Some(value) - }, - }; - - /* re-inserting buckets may cause changes in size, so remember - what our new size is ahead of time before we start insertions */ - let size = self.size - 1; + bucket <-> self.buckets[idx]; + self.insert_opt_bucket(bucket); idx = self.next_bucket(idx, len_buckets); - while self.buckets[idx].is_some() { - let mut bucket = None; - bucket <-> self.buckets[idx]; - self.insert_opt_bucket(bucket); - idx = self.next_bucket(idx, len_buckets); - } - self.size = size; - - value } + self.size = size; - fn search(&self, hash: uint, - op: &fn(x: &Option>) -> bool) { - let _ = self.bucket_sequence(hash, |i| op(&self.buckets[i])); - } + value } - impl<'self,K:Hash + IterBytes + Eq,V> - BaseIter<(&'self K, &'self V)> for LinearMap { - /// Visit all key-value pairs - fn each(&self, blk: &fn(&(&'self K, &'self V)) -> bool) { - for uint::range(0, self.buckets.len()) |i| { - let mut broke = false; - do self.buckets[i].map |bucket| { - if !blk(&(&bucket.key, &bucket.value)) { - broke = true; // FIXME(#3064) just write "break;" - } - }; - if broke { break; } - } + fn search(&self, hash: uint, + op: &fn(x: &Option>) -> bool) { + let _ = self.bucket_sequence(hash, |i| op(&self.buckets[i])); + } +} + +impl<'self,K:Hash + IterBytes + Eq,V> + BaseIter<(&'self K, &'self V)> for LinearMap { + /// Visit all key-value pairs + fn each(&self, blk: &fn(&(&'self K, &'self V)) -> bool) { + for uint::range(0, self.buckets.len()) |i| { + let mut broke = false; + do self.buckets[i].map |bucket| { + if !blk(&(&bucket.key, &bucket.value)) { + broke = true; // FIXME(#3064) just write "break;" + } + }; + if broke { break; } } - fn size_hint(&self) -> Option { Some(self.len()) } } + fn size_hint(&self) -> Option { Some(self.len()) } +} - impl Container for LinearMap { - /// Return the number of elements in the map - fn len(&const self) -> uint { self.size } +impl Container for LinearMap { + /// Return the number of elements in the map + fn len(&const self) -> uint { self.size } - /// Return true if the map contains no elements - fn is_empty(&const self) -> bool { self.len() == 0 } - } + /// Return true if the map contains no elements + fn is_empty(&const self) -> bool { self.len() == 0 } +} - impl Mutable for LinearMap { - /// Clear the map, removing all key-value pairs. - fn clear(&mut self) { - for uint::range(0, self.buckets.len()) |idx| { - self.buckets[idx] = None; - } - self.size = 0; +impl Mutable for LinearMap { + /// Clear the map, removing all key-value pairs. + fn clear(&mut self) { + for uint::range(0, self.buckets.len()) |idx| { + self.buckets[idx] = None; } + self.size = 0; } +} - impl<'self,K:Hash + IterBytes + Eq,V> Map for LinearMap { - /// Return true if the map contains a value for the specified key - fn contains_key(&self, k: &K) -> bool { - match self.bucket_for_key(k) { - FoundEntry(_) => {true} - TableFull | FoundHole(_) => {false} - } - } - - /// Visit all keys - fn each_key(&self, blk: &fn(k: &K) -> bool) { - self.each(|&(k, _)| blk(k)) +impl<'self,K:Hash + IterBytes + Eq,V> Map for LinearMap { + /// Return true if the map contains a value for the specified key + fn contains_key(&self, k: &K) -> bool { + match self.bucket_for_key(k) { + FoundEntry(_) => {true} + TableFull | FoundHole(_) => {false} } + } - /// Visit all values - fn each_value(&self, blk: &fn(v: &V) -> bool) { - self.each(|&(_, v)| blk(v)) - } + /// Visit all keys + fn each_key(&self, blk: &fn(k: &K) -> bool) { + self.each(|&(k, _)| blk(k)) + } - /// Iterate over the map and mutate the contained values - fn mutate_values(&mut self, blk: &fn(&'self K, - &'self mut V) -> bool) { - for uint::range(0, self.buckets.len()) |i| { - match self.buckets[i] { - Some(Bucket{key: ref key, value: ref mut value, _}) => { - if !blk(key, value) { return } - } - None => () - } - } - } + /// Visit all values + fn each_value(&self, blk: &fn(v: &V) -> bool) { + self.each(|&(_, v)| blk(v)) + } - /// Return a reference to the value corresponding to the key - fn find(&self, k: &K) -> Option<&'self V> { - match self.bucket_for_key(k) { - FoundEntry(idx) => Some(self.value_for_bucket(idx)), - TableFull | FoundHole(_) => None, + /// Iterate over the map and mutate the contained values + fn mutate_values(&mut self, blk: &fn(&'self K, + &'self mut V) -> bool) { + for uint::range(0, self.buckets.len()) |i| { + match self.buckets[i] { + Some(Bucket{key: ref key, value: ref mut value, _}) => { + if !blk(key, value) { return } + } + None => () } } + } - /// Return a mutable reference to the value corresponding to the key - fn find_mut(&mut self, k: &K) -> Option<&'self mut V> { - let idx = match self.bucket_for_key(k) { - FoundEntry(idx) => idx, - TableFull | FoundHole(_) => return None - }; - unsafe { // FIXME(#4903)---requires flow-sensitive borrow checker - Some(::cast::transmute_mut_region(self.mut_value_for_bucket(idx))) - } + /// Return a reference to the value corresponding to the key + fn find(&self, k: &K) -> Option<&'self V> { + match self.bucket_for_key(k) { + FoundEntry(idx) => Some(self.value_for_bucket(idx)), + TableFull | FoundHole(_) => None, } + } - /// Insert a key-value pair into the map. An existing value for a - /// key is replaced by the new value. Return true if the key did - /// not already exist in the map. - fn insert(&mut self, k: K, v: V) -> bool { - if self.size >= self.resize_at { - // n.b.: We could also do this after searching, so - // that we do not resize if this call to insert is - // simply going to update a key in place. My sense - // though is that it's worse to have to search through - // buckets to find the right spot twice than to just - // resize in this corner case. - self.expand(); - } - - let hash = k.hash_keyed(self.k0, self.k1) as uint; - self.insert_internal(hash, k, v) + /// Return a mutable reference to the value corresponding to the key + fn find_mut(&mut self, k: &K) -> Option<&'self mut V> { + let idx = match self.bucket_for_key(k) { + FoundEntry(idx) => idx, + TableFull | FoundHole(_) => return None + }; + unsafe { // FIXME(#4903)---requires flow-sensitive borrow checker + Some(::cast::transmute_mut_region(self.mut_value_for_bucket(idx))) } + } - /// Remove a key-value pair from the map. Return true if the key - /// was present in the map, otherwise false. - fn remove(&mut self, k: &K) -> bool { - self.pop(k).is_some() - } + /// Insert a key-value pair into the map. An existing value for a + /// key is replaced by the new value. Return true if the key did + /// not already exist in the map. + fn insert(&mut self, k: K, v: V) -> bool { + if self.size >= self.resize_at { + // n.b.: We could also do this after searching, so + // that we do not resize if this call to insert is + // simply going to update a key in place. My sense + // though is that it's worse to have to search through + // buckets to find the right spot twice than to just + // resize in this corner case. + self.expand(); + } + + let hash = k.hash_keyed(self.k0, self.k1) as uint; + self.insert_internal(hash, k, v) } - pub impl LinearMap { - /// Create an empty LinearMap - fn new() -> LinearMap { - LinearMap::with_capacity(INITIAL_CAPACITY) - } + /// Remove a key-value pair from the map. Return true if the key + /// was present in the map, otherwise false. + fn remove(&mut self, k: &K) -> bool { + self.pop(k).is_some() + } +} - /// Create an empty LinearMap with space for at least `n` elements in - /// the hash table. - fn with_capacity(capacity: uint) -> LinearMap { - linear_map_with_capacity(capacity) - } +pub impl LinearMap { + /// Create an empty LinearMap + fn new() -> LinearMap { + LinearMap::with_capacity(INITIAL_CAPACITY) + } - /// Reserve space for at least `n` elements in the hash table. - fn reserve_at_least(&mut self, n: uint) { - if n > self.buckets.len() { - let buckets = n * 4 / 3 + 1; - self.resize(uint::next_power_of_two(buckets)); - } - } + /// Create an empty LinearMap with space for at least `n` elements in + /// the hash table. + fn with_capacity(capacity: uint) -> LinearMap { + linear_map_with_capacity(capacity) + } - fn pop(&mut self, k: &K) -> Option { - let hash = k.hash_keyed(self.k0, self.k1) as uint; - self.pop_internal(hash, k) + /// Reserve space for at least `n` elements in the hash table. + fn reserve_at_least(&mut self, n: uint) { + if n > self.buckets.len() { + let buckets = n * 4 / 3 + 1; + self.resize(uint::next_power_of_two(buckets)); } + } - fn swap(&mut self, k: K, v: V) -> Option { - // this could be faster. - let hash = k.hash_keyed(self.k0, self.k1) as uint; - let old_value = self.pop_internal(hash, &k); - - if self.size >= self.resize_at { - // n.b.: We could also do this after searching, so - // that we do not resize if this call to insert is - // simply going to update a key in place. My sense - // though is that it's worse to have to search through - // buckets to find the right spot twice than to just - // resize in this corner case. - self.expand(); - } + fn pop(&mut self, k: &K) -> Option { + let hash = k.hash_keyed(self.k0, self.k1) as uint; + self.pop_internal(hash, k) + } - self.insert_internal(hash, k, v); + fn swap(&mut self, k: K, v: V) -> Option { + // this could be faster. + let hash = k.hash_keyed(self.k0, self.k1) as uint; + let old_value = self.pop_internal(hash, &k); - old_value + if self.size >= self.resize_at { + // n.b.: We could also do this after searching, so + // that we do not resize if this call to insert is + // simply going to update a key in place. My sense + // though is that it's worse to have to search through + // buckets to find the right spot twice than to just + // resize in this corner case. + self.expand(); } - /// Return the value corresponding to the key in the map, or insert - /// and return the value if it doesn't exist. - fn find_or_insert(&mut self, k: K, v: V) -> &'self V { - if self.size >= self.resize_at { - // n.b.: We could also do this after searching, so - // that we do not resize if this call to insert is - // simply going to update a key in place. My sense - // though is that it's worse to have to search through - // buckets to find the right spot twice than to just - // resize in this corner case. - self.expand(); - } + self.insert_internal(hash, k, v); - let hash = k.hash_keyed(self.k0, self.k1) as uint; - let idx = match self.bucket_for_key_with_hash(hash, &k) { - TableFull => fail!(~"Internal logic error"), - FoundEntry(idx) => idx, - FoundHole(idx) => { - self.buckets[idx] = Some(Bucket{hash: hash, key: k, - value: v}); - self.size += 1; - idx - }, - }; + old_value + } - unsafe { // FIXME(#4903)---requires flow-sensitive borrow checker - ::cast::transmute_region(self.value_for_bucket(idx)) - } + /// Return the value corresponding to the key in the map, or insert + /// and return the value if it doesn't exist. + fn find_or_insert(&mut self, k: K, v: V) -> &'self V { + if self.size >= self.resize_at { + // n.b.: We could also do this after searching, so + // that we do not resize if this call to insert is + // simply going to update a key in place. My sense + // though is that it's worse to have to search through + // buckets to find the right spot twice than to just + // resize in this corner case. + self.expand(); + } + + let hash = k.hash_keyed(self.k0, self.k1) as uint; + let idx = match self.bucket_for_key_with_hash(hash, &k) { + TableFull => fail!(~"Internal logic error"), + FoundEntry(idx) => idx, + FoundHole(idx) => { + self.buckets[idx] = Some(Bucket{hash: hash, key: k, + value: v}); + self.size += 1; + idx + }, + }; + + unsafe { // FIXME(#4903)---requires flow-sensitive borrow checker + ::cast::transmute_region(self.value_for_bucket(idx)) } + } - /// Return the value corresponding to the key in the map, or create, - /// insert, and return a new value if it doesn't exist. - fn find_or_insert_with(&mut self, k: K, f: &fn(&K) -> V) -> &'self V { - if self.size >= self.resize_at { - // n.b.: We could also do this after searching, so - // that we do not resize if this call to insert is - // simply going to update a key in place. My sense - // though is that it's worse to have to search through - // buckets to find the right spot twice than to just - // resize in this corner case. - self.expand(); - } - - let hash = k.hash_keyed(self.k0, self.k1) as uint; - let idx = match self.bucket_for_key_with_hash(hash, &k) { - TableFull => fail!(~"Internal logic error"), - FoundEntry(idx) => idx, - FoundHole(idx) => { - let v = f(&k); - self.buckets[idx] = Some(Bucket{hash: hash, key: k, - value: v}); - self.size += 1; - idx - }, - }; - - unsafe { // FIXME(#4903)---requires flow-sensitive borrow checker - ::cast::transmute_region(self.value_for_bucket(idx)) - } + /// Return the value corresponding to the key in the map, or create, + /// insert, and return a new value if it doesn't exist. + fn find_or_insert_with(&mut self, k: K, f: &fn(&K) -> V) -> &'self V { + if self.size >= self.resize_at { + // n.b.: We could also do this after searching, so + // that we do not resize if this call to insert is + // simply going to update a key in place. My sense + // though is that it's worse to have to search through + // buckets to find the right spot twice than to just + // resize in this corner case. + self.expand(); + } + + let hash = k.hash_keyed(self.k0, self.k1) as uint; + let idx = match self.bucket_for_key_with_hash(hash, &k) { + TableFull => fail!(~"Internal logic error"), + FoundEntry(idx) => idx, + FoundHole(idx) => { + let v = f(&k); + self.buckets[idx] = Some(Bucket{hash: hash, key: k, + value: v}); + self.size += 1; + idx + }, + }; + + unsafe { // FIXME(#4903)---requires flow-sensitive borrow checker + ::cast::transmute_region(self.value_for_bucket(idx)) } + } - fn consume(&mut self, f: &fn(K, V)) { - let mut buckets = ~[]; - self.buckets <-> buckets; - self.size = 0; - - do vec::consume(buckets) |_, bucket| { - match bucket { - None => {}, - Some(bucket) => { - let Bucket{key: key, value: value, _} = bucket; - f(key, value) - } + fn consume(&mut self, f: &fn(K, V)) { + let mut buckets = ~[]; + self.buckets <-> buckets; + self.size = 0; + + do vec::consume(buckets) |_, bucket| { + match bucket { + None => {}, + Some(bucket) => { + let Bucket{key: key, value: value, _} = bucket; + f(key, value) } } } + } - fn get(&self, k: &K) -> &'self V { - match self.find(k) { - Some(v) => v, - None => fail!(fmt!("No entry found for key: %?", k)), - } + fn get(&self, k: &K) -> &'self V { + match self.find(k) { + Some(v) => v, + None => fail!(fmt!("No entry found for key: %?", k)), } + } - /// Return true if the map contains a value for the specified key, - /// using equivalence - fn contains_key_equiv>(&self, key: &Q) - -> bool { - match self.bucket_for_key_equiv(key) { - FoundEntry(_) => {true} - TableFull | FoundHole(_) => {false} - } + /// Return true if the map contains a value for the specified key, + /// using equivalence + fn contains_key_equiv>(&self, key: &Q) + -> bool { + match self.bucket_for_key_equiv(key) { + FoundEntry(_) => {true} + TableFull | FoundHole(_) => {false} } + } - /// Return the value corresponding to the key in the map, using - /// equivalence - fn find_equiv>(&self, k: &Q) - -> Option<&'self V> { - match self.bucket_for_key_equiv(k) { - FoundEntry(idx) => Some(self.value_for_bucket(idx)), - TableFull | FoundHole(_) => None, - } + /// Return the value corresponding to the key in the map, using + /// equivalence + fn find_equiv>(&self, k: &Q) + -> Option<&'self V> { + match self.bucket_for_key_equiv(k) { + FoundEntry(idx) => Some(self.value_for_bucket(idx)), + TableFull | FoundHole(_) => None, } } +} - impl Eq for LinearMap { - fn eq(&self, other: &LinearMap) -> bool { - if self.len() != other.len() { return false; } +impl Eq for LinearMap { + fn eq(&self, other: &LinearMap) -> bool { + if self.len() != other.len() { return false; } - for self.each |&(key, value)| { - match other.find(key) { - None => return false, - Some(v) => if value != v { return false }, - } + for self.each |&(key, value)| { + match other.find(key) { + None => return false, + Some(v) => if value != v { return false }, } - - true } - fn ne(&self, other: &LinearMap) -> bool { !self.eq(other) } + true } - pub struct LinearSet { - priv map: LinearMap - } + fn ne(&self, other: &LinearMap) -> bool { !self.eq(other) } +} - impl BaseIter for LinearSet { - /// Visit all values in order - fn each(&self, f: &fn(&T) -> bool) { self.map.each_key(f) } - fn size_hint(&self) -> Option { Some(self.len()) } - } +pub struct LinearSet { + priv map: LinearMap +} - impl Eq for LinearSet { - fn eq(&self, other: &LinearSet) -> bool { self.map == other.map } - fn ne(&self, other: &LinearSet) -> bool { self.map != other.map } - } +impl BaseIter for LinearSet { + /// Visit all values in order + fn each(&self, f: &fn(&T) -> bool) { self.map.each_key(f) } + fn size_hint(&self) -> Option { Some(self.len()) } +} - impl Container for LinearSet { - /// Return the number of elements in the set - fn len(&const self) -> uint { self.map.len() } +impl Eq for LinearSet { + fn eq(&self, other: &LinearSet) -> bool { self.map == other.map } + fn ne(&self, other: &LinearSet) -> bool { self.map != other.map } +} - /// Return true if the set contains no elements - fn is_empty(&const self) -> bool { self.map.is_empty() } - } +impl Container for LinearSet { + /// Return the number of elements in the set + fn len(&const self) -> uint { self.map.len() } - impl Mutable for LinearSet { - /// Clear the set, removing all values. - fn clear(&mut self) { self.map.clear() } - } + /// Return true if the set contains no elements + fn is_empty(&const self) -> bool { self.map.is_empty() } +} - impl Set for LinearSet { - /// Return true if the set contains a value - fn contains(&self, value: &T) -> bool { self.map.contains_key(value) } +impl Mutable for LinearSet { + /// Clear the set, removing all values. + fn clear(&mut self) { self.map.clear() } +} - /// Add a value to the set. Return true if the value was not already - /// present in the set. - fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) } +impl Set for LinearSet { + /// Return true if the set contains a value + fn contains(&self, value: &T) -> bool { self.map.contains_key(value) } - /// Remove a value from the set. Return true if the value was - /// present in the set. - fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } + /// Add a value to the set. Return true if the value was not already + /// present in the set. + fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) } - /// Return true if the set has no elements in common with `other`. - /// This is equivalent to checking for an empty intersection. - fn is_disjoint(&self, other: &LinearSet) -> bool { - iter::all(self, |v| !other.contains(v)) - } + /// Remove a value from the set. Return true if the value was + /// present in the set. + fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } - /// Return true if the set is a subset of another - fn is_subset(&self, other: &LinearSet) -> bool { - iter::all(self, |v| other.contains(v)) - } + /// Return true if the set has no elements in common with `other`. + /// This is equivalent to checking for an empty intersection. + fn is_disjoint(&self, other: &LinearSet) -> bool { + iter::all(self, |v| !other.contains(v)) + } - /// Return true if the set is a superset of another - fn is_superset(&self, other: &LinearSet) -> bool { - other.is_subset(self) - } + /// Return true if the set is a subset of another + fn is_subset(&self, other: &LinearSet) -> bool { + iter::all(self, |v| other.contains(v)) + } - /// Visit the values representing the difference - fn difference(&self, other: &LinearSet, f: &fn(&T) -> bool) { - for self.each |v| { - if !other.contains(v) { - if !f(v) { return } - } + /// Return true if the set is a superset of another + fn is_superset(&self, other: &LinearSet) -> bool { + other.is_subset(self) + } + + /// Visit the values representing the difference + fn difference(&self, other: &LinearSet, f: &fn(&T) -> bool) { + for self.each |v| { + if !other.contains(v) { + if !f(v) { return } } } + } - /// Visit the values representing the symmetric difference - fn symmetric_difference(&self, - other: &LinearSet, - f: &fn(&T) -> bool) { - self.difference(other, f); - other.difference(self, f); - } + /// Visit the values representing the symmetric difference + fn symmetric_difference(&self, + other: &LinearSet, + f: &fn(&T) -> bool) { + self.difference(other, f); + other.difference(self, f); + } - /// Visit the values representing the intersection - fn intersection(&self, other: &LinearSet, f: &fn(&T) -> bool) { - for self.each |v| { - if other.contains(v) { - if !f(v) { return } - } + /// Visit the values representing the intersection + fn intersection(&self, other: &LinearSet, f: &fn(&T) -> bool) { + for self.each |v| { + if other.contains(v) { + if !f(v) { return } } } + } - /// Visit the values representing the union - fn union(&self, other: &LinearSet, f: &fn(&T) -> bool) { - for self.each |v| { - if !f(v) { return } - } + /// Visit the values representing the union + fn union(&self, other: &LinearSet, f: &fn(&T) -> bool) { + for self.each |v| { + if !f(v) { return } + } - for other.each |v| { - if !self.contains(v) { - if !f(v) { return } - } + for other.each |v| { + if !self.contains(v) { + if !f(v) { return } } } } +} - pub impl LinearSet { - /// Create an empty LinearSet - fn new() -> LinearSet { - LinearSet::with_capacity(INITIAL_CAPACITY) - } +pub impl LinearSet { + /// Create an empty LinearSet + fn new() -> LinearSet { + LinearSet::with_capacity(INITIAL_CAPACITY) + } - /// Create an empty LinearSet with space for at least `n` elements in - /// the hash table. - fn with_capacity(capacity: uint) -> LinearSet { - LinearSet { map: LinearMap::with_capacity(capacity) } - } + /// Create an empty LinearSet with space for at least `n` elements in + /// the hash table. + fn with_capacity(capacity: uint) -> LinearSet { + LinearSet { map: LinearMap::with_capacity(capacity) } + } - /// Reserve space for at least `n` elements in the hash table. - fn reserve_at_least(&mut self, n: uint) { - self.map.reserve_at_least(n) - } + /// Reserve space for at least `n` elements in the hash table. + fn reserve_at_least(&mut self, n: uint) { + self.map.reserve_at_least(n) + } - /// Consumes all of the elements in the set, emptying it out - fn consume(&mut self, f: &fn(T)) { - self.map.consume(|k, _| f(k)) - } + /// Consumes all of the elements in the set, emptying it out + fn consume(&mut self, f: &fn(T)) { + self.map.consume(|k, _| f(k)) } +} + +#[test] +mod test_map { + use container::{Container, Map, Set}; + use option::{None, Some}; + use super::*; + use uint; #[test] - mod test_map { - use container::{Container, Map, Set}; - use option::{None, Some}; - use hashmap::linear::LinearMap; - use hashmap::linear; - use uint; - - #[test] - pub fn test_insert() { - let mut m = LinearMap::new(); - assert!(m.insert(1, 2)); - assert!(m.insert(2, 4)); - assert!(*m.get(&1) == 2); - assert!(*m.get(&2) == 4); - } + pub fn test_insert() { + let mut m = LinearMap::new(); + assert!(m.insert(1, 2)); + assert!(m.insert(2, 4)); + assert!(*m.get(&1) == 2); + assert!(*m.get(&2) == 4); + } - #[test] - fn test_find_mut() { - let mut m = LinearMap::new(); - assert!(m.insert(1, 12)); - assert!(m.insert(2, 8)); - assert!(m.insert(5, 14)); - let new = 100; - match m.find_mut(&5) { - None => fail!(), Some(x) => *x = new - } - assert_eq!(m.find(&5), Some(&new)); - } + #[test] + fn test_find_mut() { + let mut m = LinearMap::new(); + assert!(m.insert(1, 12)); + assert!(m.insert(2, 8)); + assert!(m.insert(5, 14)); + let new = 100; + match m.find_mut(&5) { + None => fail!(), Some(x) => *x = new + } + assert_eq!(m.find(&5), Some(&new)); + } - #[test] - pub fn test_insert_overwrite() { - let mut m = LinearMap::new(); - assert!(m.insert(1, 2)); - assert!(*m.get(&1) == 2); - assert!(!m.insert(1, 3)); - assert!(*m.get(&1) == 3); - } + #[test] + pub fn test_insert_overwrite() { + let mut m = LinearMap::new(); + assert!(m.insert(1, 2)); + assert!(*m.get(&1) == 2); + assert!(!m.insert(1, 3)); + assert!(*m.get(&1) == 3); + } - #[test] - pub fn test_insert_conflicts() { - let mut m = linear::linear_map_with_capacity(4); - assert!(m.insert(1, 2)); - assert!(m.insert(5, 3)); - assert!(m.insert(9, 4)); - assert!(*m.get(&9) == 4); - assert!(*m.get(&5) == 3); - assert!(*m.get(&1) == 2); - } + #[test] + pub fn test_insert_conflicts() { + let mut m = linear_map_with_capacity(4); + assert!(m.insert(1, 2)); + assert!(m.insert(5, 3)); + assert!(m.insert(9, 4)); + assert!(*m.get(&9) == 4); + assert!(*m.get(&5) == 3); + assert!(*m.get(&1) == 2); + } - #[test] - pub fn test_conflict_remove() { - let mut m = linear::linear_map_with_capacity(4); - assert!(m.insert(1, 2)); - assert!(m.insert(5, 3)); - assert!(m.insert(9, 4)); - assert!(m.remove(&1)); - assert!(*m.get(&9) == 4); - assert!(*m.get(&5) == 3); - } + #[test] + pub fn test_conflict_remove() { + let mut m = linear_map_with_capacity(4); + assert!(m.insert(1, 2)); + assert!(m.insert(5, 3)); + assert!(m.insert(9, 4)); + assert!(m.remove(&1)); + assert!(*m.get(&9) == 4); + assert!(*m.get(&5) == 3); + } - #[test] - pub fn test_is_empty() { - let mut m = linear::linear_map_with_capacity(4); - assert!(m.insert(1, 2)); - assert!(!m.is_empty()); - assert!(m.remove(&1)); - assert!(m.is_empty()); - } + #[test] + pub fn test_is_empty() { + let mut m = linear_map_with_capacity(4); + assert!(m.insert(1, 2)); + assert!(!m.is_empty()); + assert!(m.remove(&1)); + assert!(m.is_empty()); + } - #[test] - pub fn test_pop() { - let mut m = LinearMap::new(); - m.insert(1, 2); - assert!(m.pop(&1) == Some(2)); - assert!(m.pop(&1) == None); - } + #[test] + pub fn test_pop() { + let mut m = LinearMap::new(); + m.insert(1, 2); + assert!(m.pop(&1) == Some(2)); + assert!(m.pop(&1) == None); + } - #[test] - pub fn test_swap() { - let mut m = LinearMap::new(); - assert!(m.swap(1, 2) == None); - assert!(m.swap(1, 3) == Some(2)); - assert!(m.swap(1, 4) == Some(3)); - } + #[test] + pub fn test_swap() { + let mut m = LinearMap::new(); + assert!(m.swap(1, 2) == None); + assert!(m.swap(1, 3) == Some(2)); + assert!(m.swap(1, 4) == Some(3)); + } - #[test] - pub fn test_find_or_insert() { - let mut m = LinearMap::new::(); - assert!(m.find_or_insert(1, 2) == &2); - assert!(m.find_or_insert(1, 3) == &2); - } + #[test] + pub fn test_find_or_insert() { + let mut m = LinearMap::new::(); + assert!(m.find_or_insert(1, 2) == &2); + assert!(m.find_or_insert(1, 3) == &2); + } - #[test] - pub fn test_find_or_insert_with() { - let mut m = LinearMap::new::(); - assert!(m.find_or_insert_with(1, |_| 2) == &2); - assert!(m.find_or_insert_with(1, |_| 3) == &2); - } + #[test] + pub fn test_find_or_insert_with() { + let mut m = LinearMap::new::(); + assert!(m.find_or_insert_with(1, |_| 2) == &2); + assert!(m.find_or_insert_with(1, |_| 3) == &2); + } - #[test] - pub fn test_consume() { - let mut m = LinearMap::new(); - assert!(m.insert(1, 2)); - assert!(m.insert(2, 3)); - let mut m2 = LinearMap::new(); - do m.consume |k, v| { - m2.insert(k, v); - } - assert!(m.len() == 0); - assert!(m2.len() == 2); - assert!(m2.get(&1) == &2); - assert!(m2.get(&2) == &3); - } + #[test] + pub fn test_consume() { + let mut m = LinearMap::new(); + assert!(m.insert(1, 2)); + assert!(m.insert(2, 3)); + let mut m2 = LinearMap::new(); + do m.consume |k, v| { + m2.insert(k, v); + } + assert!(m.len() == 0); + assert!(m2.len() == 2); + assert!(m2.get(&1) == &2); + assert!(m2.get(&2) == &3); + } - #[test] - pub fn test_iterate() { - let mut m = linear::linear_map_with_capacity(4); - for uint::range(0, 32) |i| { - assert!(m.insert(i, i*2)); - } - let mut observed = 0; - for m.each |&(k, v)| { - assert!(*v == *k * 2); - observed |= (1 << *k); - } - assert!(observed == 0xFFFF_FFFF); + #[test] + pub fn test_iterate() { + let mut m = linear_map_with_capacity(4); + for uint::range(0, 32) |i| { + assert!(m.insert(i, i*2)); } - - #[test] - pub fn test_find() { - let mut m = LinearMap::new(); - assert!(m.find(&1).is_none()); - m.insert(1, 2); - match m.find(&1) { - None => fail!(), - Some(v) => assert!(*v == 2) - } + let mut observed = 0; + for m.each |&(k, v)| { + assert!(*v == *k * 2); + observed |= (1 << *k); } + assert!(observed == 0xFFFF_FFFF); + } - #[test] - pub fn test_eq() { - let mut m1 = LinearMap::new(); - m1.insert(1, 2); - m1.insert(2, 3); - m1.insert(3, 4); + #[test] + pub fn test_find() { + let mut m = LinearMap::new(); + assert!(m.find(&1).is_none()); + m.insert(1, 2); + match m.find(&1) { + None => fail!(), + Some(v) => assert!(*v == 2) + } + } - let mut m2 = LinearMap::new(); - m2.insert(1, 2); - m2.insert(2, 3); + #[test] + pub fn test_eq() { + let mut m1 = LinearMap::new(); + m1.insert(1, 2); + m1.insert(2, 3); + m1.insert(3, 4); - assert!(m1 != m2); + let mut m2 = LinearMap::new(); + m2.insert(1, 2); + m2.insert(2, 3); - m2.insert(3, 4); + assert!(m1 != m2); - assert!(m1 == m2); - } + m2.insert(3, 4); - #[test] - pub fn test_expand() { - let mut m = LinearMap::new(); + assert!(m1 == m2); + } - assert!(m.len() == 0); - assert!(m.is_empty()); + #[test] + pub fn test_expand() { + let mut m = LinearMap::new(); - let mut i = 0u; - let old_resize_at = m.resize_at; - while old_resize_at == m.resize_at { - m.insert(i, i); - i += 1; - } + assert!(m.len() == 0); + assert!(m.is_empty()); - assert!(m.len() == i); - assert!(!m.is_empty()); + let mut i = 0u; + let old_resize_at = m.resize_at; + while old_resize_at == m.resize_at { + m.insert(i, i); + i += 1; } + + assert!(m.len() == i); + assert!(!m.is_empty()); } +} #[test] - mod test_set { - use hashmap::linear; - use container::{Container, Map, Set}; - use vec; - - #[test] - fn test_disjoint() { - let mut xs = linear::LinearSet::new(); - let mut ys = linear::LinearSet::new(); - assert!(xs.is_disjoint(&ys)); - assert!(ys.is_disjoint(&xs)); - assert!(xs.insert(5)); - assert!(ys.insert(11)); - assert!(xs.is_disjoint(&ys)); - assert!(ys.is_disjoint(&xs)); - assert!(xs.insert(7)); - assert!(xs.insert(19)); - assert!(xs.insert(4)); - assert!(ys.insert(2)); - assert!(ys.insert(-11)); - assert!(xs.is_disjoint(&ys)); - assert!(ys.is_disjoint(&xs)); - assert!(ys.insert(7)); - assert!(!xs.is_disjoint(&ys)); - assert!(!ys.is_disjoint(&xs)); - } +mod test_set { + use super::*; + use container::{Container, Map, Set}; + use vec; - #[test] - fn test_subset_and_superset() { - let mut a = linear::LinearSet::new(); - assert!(a.insert(0)); - assert!(a.insert(5)); - assert!(a.insert(11)); - assert!(a.insert(7)); - - let mut b = linear::LinearSet::new(); - assert!(b.insert(0)); - assert!(b.insert(7)); - assert!(b.insert(19)); - assert!(b.insert(250)); - assert!(b.insert(11)); - assert!(b.insert(200)); - - assert!(!a.is_subset(&b)); - assert!(!a.is_superset(&b)); - assert!(!b.is_subset(&a)); - assert!(!b.is_superset(&a)); - - assert!(b.insert(5)); - - assert!(a.is_subset(&b)); - assert!(!a.is_superset(&b)); - assert!(!b.is_subset(&a)); - assert!(b.is_superset(&a)); - } + #[test] + fn test_disjoint() { + let mut xs = LinearSet::new(); + let mut ys = LinearSet::new(); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(5)); + assert!(ys.insert(11)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(7)); + assert!(xs.insert(19)); + assert!(xs.insert(4)); + assert!(ys.insert(2)); + assert!(ys.insert(-11)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(ys.insert(7)); + assert!(!xs.is_disjoint(&ys)); + assert!(!ys.is_disjoint(&xs)); + } - #[test] - fn test_intersection() { - let mut a = linear::LinearSet::new(); - let mut b = linear::LinearSet::new(); - - assert!(a.insert(11)); - assert!(a.insert(1)); - assert!(a.insert(3)); - assert!(a.insert(77)); - assert!(a.insert(103)); - assert!(a.insert(5)); - assert!(a.insert(-5)); - - assert!(b.insert(2)); - assert!(b.insert(11)); - assert!(b.insert(77)); - assert!(b.insert(-9)); - assert!(b.insert(-42)); - assert!(b.insert(5)); - assert!(b.insert(3)); - - let mut i = 0; - let expected = [3, 5, 11, 77]; - for a.intersection(&b) |x| { - assert!(vec::contains(expected, x)); - i += 1 - } - assert!(i == expected.len()); - } + #[test] + fn test_subset_and_superset() { + let mut a = LinearSet::new(); + assert!(a.insert(0)); + assert!(a.insert(5)); + assert!(a.insert(11)); + assert!(a.insert(7)); + + let mut b = LinearSet::new(); + assert!(b.insert(0)); + assert!(b.insert(7)); + assert!(b.insert(19)); + assert!(b.insert(250)); + assert!(b.insert(11)); + assert!(b.insert(200)); + + assert!(!a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(!b.is_superset(&a)); + + assert!(b.insert(5)); + + assert!(a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(b.is_superset(&a)); + } - #[test] - fn test_difference() { - let mut a = linear::LinearSet::new(); - let mut b = linear::LinearSet::new(); - - assert!(a.insert(1)); - assert!(a.insert(3)); - assert!(a.insert(5)); - assert!(a.insert(9)); - assert!(a.insert(11)); - - assert!(b.insert(3)); - assert!(b.insert(9)); - - let mut i = 0; - let expected = [1, 5, 11]; - for a.difference(&b) |x| { - assert!(vec::contains(expected, x)); - i += 1 - } - assert!(i == expected.len()); - } + #[test] + fn test_intersection() { + let mut a = LinearSet::new(); + let mut b = LinearSet::new(); + + assert!(a.insert(11)); + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(77)); + assert!(a.insert(103)); + assert!(a.insert(5)); + assert!(a.insert(-5)); + + assert!(b.insert(2)); + assert!(b.insert(11)); + assert!(b.insert(77)); + assert!(b.insert(-9)); + assert!(b.insert(-42)); + assert!(b.insert(5)); + assert!(b.insert(3)); + + let mut i = 0; + let expected = [3, 5, 11, 77]; + for a.intersection(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert!(i == expected.len()); + } - #[test] - fn test_symmetric_difference() { - let mut a = linear::LinearSet::new(); - let mut b = linear::LinearSet::new(); - - assert!(a.insert(1)); - assert!(a.insert(3)); - assert!(a.insert(5)); - assert!(a.insert(9)); - assert!(a.insert(11)); - - assert!(b.insert(-2)); - assert!(b.insert(3)); - assert!(b.insert(9)); - assert!(b.insert(14)); - assert!(b.insert(22)); - - let mut i = 0; - let expected = [-2, 1, 5, 11, 14, 22]; - for a.symmetric_difference(&b) |x| { - assert!(vec::contains(expected, x)); - i += 1 - } - assert!(i == expected.len()); - } + #[test] + fn test_difference() { + let mut a = LinearSet::new(); + let mut b = LinearSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(3)); + assert!(b.insert(9)); + + let mut i = 0; + let expected = [1, 5, 11]; + for a.difference(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert!(i == expected.len()); + } - #[test] - fn test_union() { - let mut a = linear::LinearSet::new(); - let mut b = linear::LinearSet::new(); - - assert!(a.insert(1)); - assert!(a.insert(3)); - assert!(a.insert(5)); - assert!(a.insert(9)); - assert!(a.insert(11)); - assert!(a.insert(16)); - assert!(a.insert(19)); - assert!(a.insert(24)); - - assert!(b.insert(-2)); - assert!(b.insert(1)); - assert!(b.insert(5)); - assert!(b.insert(9)); - assert!(b.insert(13)); - assert!(b.insert(19)); - - let mut i = 0; - let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]; - for a.union(&b) |x| { - assert!(vec::contains(expected, x)); - i += 1 - } - assert!(i == expected.len()); - } + #[test] + fn test_symmetric_difference() { + let mut a = LinearSet::new(); + let mut b = LinearSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(-2)); + assert!(b.insert(3)); + assert!(b.insert(9)); + assert!(b.insert(14)); + assert!(b.insert(22)); + + let mut i = 0; + let expected = [-2, 1, 5, 11, 14, 22]; + for a.symmetric_difference(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert!(i == expected.len()); + } + + #[test] + fn test_union() { + let mut a = LinearSet::new(); + let mut b = LinearSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + assert!(a.insert(16)); + assert!(a.insert(19)); + assert!(a.insert(24)); + + assert!(b.insert(-2)); + assert!(b.insert(1)); + assert!(b.insert(5)); + assert!(b.insert(9)); + assert!(b.insert(13)); + assert!(b.insert(19)); + + let mut i = 0; + let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]; + for a.union(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert!(i == expected.len()); } } diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index 39e43ba6fc5e8..ac6775eb81fec 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -79,7 +79,7 @@ use comm::{Chan, GenericChan}; use prelude::*; use unstable; use ptr; -use hashmap::linear::LinearSet; +use hashmap::LinearSet; use task::local_data_priv::{local_get, local_set}; use task::rt::rust_task; use task::rt; diff --git a/src/libcore/unstable/global.rs b/src/libcore/unstable/global.rs index ef5970658a192..3187012e2a983 100644 --- a/src/libcore/unstable/global.rs +++ b/src/libcore/unstable/global.rs @@ -34,7 +34,7 @@ use ops::Drop; use unstable::{Exclusive, exclusive}; use unstable::at_exit::at_exit; use unstable::intrinsics::atomic_cxchg; -use hashmap::linear::LinearMap; +use hashmap::LinearMap; use sys::Closure; #[cfg(test)] use unstable::{SharedMutableState, shared_mutable_state}; diff --git a/src/libcore/unstable/weak_task.rs b/src/libcore/unstable/weak_task.rs index 8b24c2fa6f622..5556792c22543 100644 --- a/src/libcore/unstable/weak_task.rs +++ b/src/libcore/unstable/weak_task.rs @@ -21,7 +21,7 @@ is trying to shut down. use cell::Cell; use comm::{GenericSmartChan, stream}; use comm::{Port, Chan, SharedChan, GenericChan, GenericPort}; -use hashmap::linear::LinearMap; +use hashmap::LinearMap; use option::{Some, None}; use unstable::at_exit::at_exit; use unstable::finally::Finally; diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 6c485df84b484..89d1eb53c8201 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -18,7 +18,7 @@ use core::os; use core::uint; use core::util; use core::vec; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; fn not_win32(os: session::os) -> bool { match os { diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index 34678d1803c17..c50eecd448976 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -10,7 +10,7 @@ use core::prelude::*; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::libc::c_uint; use core::option; use core::ptr; diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 086c6a33b3ec8..eb01964f6d692 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -18,7 +18,7 @@ use metadata::decoder; use metadata::filesearch::FileSearch; use metadata::loader; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::vec; use syntax::attr; use syntax::codemap::{span, dummy_sp}; diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index c836538e1e6c8..13447d09736e4 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -17,7 +17,7 @@ use core::prelude::*; use metadata::cstore; use metadata::decoder; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::vec; use std; use syntax::ast; diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 340ad443b5888..b7ad62ee4ed2c 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -25,7 +25,7 @@ use util::ppaux::ty_to_str; use core::flate; use core::hash::HashUtil; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::int; use core::io::{Writer, WriterUtil}; use core::io; diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 9b777332c27c3..05f5f302f5379 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -16,7 +16,7 @@ use core::prelude::*; use middle::ty::param_ty; use middle::ty; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::io::WriterUtil; use core::io; use core::uint; diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index ac74dc25fd0d7..2bf89903e1c8b 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -31,7 +31,7 @@ use middle::mem_categorization::{lp_comp, lp_deref, lp_local}; use middle::ty; use util::ppaux::ty_to_str; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use core::uint; use syntax::ast::m_mutbl; use syntax::ast; diff --git a/src/librustc/middle/borrowck/gather_loans.rs b/src/librustc/middle/borrowck/gather_loans.rs index 925659984d4bd..2965921b05a81 100644 --- a/src/librustc/middle/borrowck/gather_loans.rs +++ b/src/librustc/middle/borrowck/gather_loans.rs @@ -31,7 +31,7 @@ use middle::ty; use util::common::indenter; use util::ppaux::{expr_repr, region_to_str}; -use core::hashmap::linear::{LinearSet, LinearMap}; +use core::hashmap::{LinearSet, LinearMap}; use core::vec; use syntax::ast::{m_const, m_imm, m_mutbl}; use syntax::ast; diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 3f4f7469832f5..ca3365bbcabc4 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -234,7 +234,7 @@ use middle::moves; use util::common::stmt_set; use util::ppaux::note_and_explain_region; -use core::hashmap::linear::{LinearSet, LinearMap}; +use core::hashmap::{LinearSet, LinearMap}; use core::io; use core::result::{Result, Ok, Err}; use core::to_bytes; diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index d610b007f3503..788d8f6de89cd 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -20,7 +20,7 @@ use core::vec; use syntax::{ast, ast_map, ast_util, visit}; use syntax::ast::*; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; // // This pass classifies expressions by their constant-ness. diff --git a/src/librustc/middle/freevars.rs b/src/librustc/middle/freevars.rs index 19d3e1f431db2..d680d1547351a 100644 --- a/src/librustc/middle/freevars.rs +++ b/src/librustc/middle/freevars.rs @@ -17,7 +17,7 @@ use core::prelude::*; use middle::resolve; use middle::ty; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use syntax::codemap::span; use syntax::{ast, ast_util, visit}; diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 566a52c3894d1..7c399bf2ece68 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -31,7 +31,7 @@ use syntax::ast_util::local_def; use syntax::visit::{default_simple_visitor, mk_simple_visitor, SimpleVisitor}; use syntax::visit::visit_crate; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::ptr; pub enum LangItem { diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index ba232f55f74f6..d4cd500f04c48 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -15,7 +15,7 @@ use driver::session; use middle::ty; use util::ppaux::{ty_to_str}; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::char; use core::cmp; use core::i8; diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index e9e226d36d1f5..a91404fb47a2a 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,7 +111,7 @@ use middle::typeck; use middle::moves; use util::ppaux::ty_to_str; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::io::WriterUtil; use core::io; use core::ptr; diff --git a/src/librustc/middle/moves.rs b/src/librustc/middle/moves.rs index a93618b66246f..de52d3e6878e9 100644 --- a/src/librustc/middle/moves.rs +++ b/src/librustc/middle/moves.rs @@ -215,7 +215,7 @@ use middle::typeck::method_map; use util::ppaux; use util::common::indenter; -use core::hashmap::linear::{LinearSet, LinearMap}; +use core::hashmap::{LinearSet, LinearMap}; use core::vec; use syntax::ast::*; use syntax::ast_util; diff --git a/src/librustc/middle/pat_util.rs b/src/librustc/middle/pat_util.rs index 0e47dabcce900..db3f5acf9d590 100644 --- a/src/librustc/middle/pat_util.rs +++ b/src/librustc/middle/pat_util.rs @@ -12,7 +12,7 @@ use core::prelude::*; use middle::resolve; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use syntax::ast::*; use syntax::ast_util::{path_to_ident, walk_pat}; use syntax::codemap::span; diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index f6025548d71c0..e6e1990717254 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -26,7 +26,7 @@ use middle::ty::{region_variance, rv_covariant, rv_invariant}; use middle::ty::{rv_contravariant}; use middle::ty; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::vec; use syntax::ast_map; use syntax::codemap::span; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 70d9dfacb6940..c4a6584dd66a3 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -77,7 +77,7 @@ use syntax::opt_vec::OptVec; use core::option::Some; use core::str::each_split_str; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; // Definition mapping pub type DefMap = @mut LinearMap; diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index 12eaeb77d1103..1b5273dd3d7d3 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -167,7 +167,7 @@ use middle::trans::type_of; use middle::ty; use util::common::indenter; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use syntax::ast; use syntax::ast::ident; use syntax::ast_util::path_to_ident; diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 15238f168944d..588690b055444 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -67,7 +67,7 @@ use util::ppaux::ty_to_str; use util::ppaux; use core::hash; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::int; use core::io; use core::libc::{c_uint, c_ulonglong}; diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index ab0e2f38a0b94..234812e66d9db 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -18,7 +18,7 @@ use syntax::codemap::span; use core::prelude::*; use core::cast; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::libc::{c_uint, c_ulonglong, c_char}; use core::libc; use core::option::Some; diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 6bb30a5d5b51b..04aca7b9dcdc4 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -45,7 +45,7 @@ use util::ppaux::{expr_repr, ty_to_str}; use core::cast; use core::hash; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::libc::{c_uint, c_longlong, c_ulonglong}; use core::ptr; use core::str; diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index d290a8ffa5c94..69a70c5a2fd51 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -20,7 +20,7 @@ use middle::trans; use middle::ty; use util::ppaux::ty_to_str; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::libc; use core::option; use core::sys; diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index dc910f9f178e3..616a25d3c164f 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -153,7 +153,7 @@ use util::common::indenter; use util::ppaux::ty_to_str; use core::cast::transmute; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use syntax::print::pprust::{expr_to_str}; use syntax::ast; use syntax::codemap; diff --git a/src/librustc/middle/trans/reachable.rs b/src/librustc/middle/trans/reachable.rs index 8824e0b782909..fd0eb9667098b 100644 --- a/src/librustc/middle/trans/reachable.rs +++ b/src/librustc/middle/trans/reachable.rs @@ -21,7 +21,7 @@ use middle::ty; use middle::typeck; use core::prelude::*; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use syntax::ast; use syntax::ast::*; use syntax::ast_util::def_id_of_def; diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index fddcce523f447..2b00bd0c71246 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -36,7 +36,7 @@ use core::result; use core::to_bytes; use core::uint; use core::vec; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use std::smallintmap::SmallIntMap; use syntax::ast::*; use syntax::ast_util::{is_local, local_def}; diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index cc2cf7a23c598..dd1dcbe67b94a 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -18,7 +18,7 @@ use middle::typeck::check::{instantiate_path, lookup_def}; use middle::typeck::check::{structure_of, valid_range_bounds}; use middle::typeck::require_same_types; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::vec; use syntax::ast; use syntax::ast_util; diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 320f0206fb871..8f7e8478f8adb 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -95,7 +95,7 @@ use middle::typeck::{method_self, method_static, method_trait, method_super}; use util::common::indenter; use util::ppaux::expr_repr; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use core::result; use core::uint; use core::vec; diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 056ccf185995b..1c144b294d219 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -110,7 +110,7 @@ use util::common::{block_query, indenter, loop_query}; use util::ppaux::{bound_region_to_str, expr_repr, pat_repr}; use util::ppaux; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::ptr; use core::result::{Result, Ok, Err}; use core::result; diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index a1eaa1f6a3394..ddce274c54207 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -28,7 +28,7 @@ use core::result::{Ok, Err}; use core::result; use core::uint; use core::vec; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use syntax::ast; use syntax::ast_util; use syntax::codemap::span; diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index 4fc9e8d19ae1f..9f4984e02a603 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -53,7 +53,7 @@ use syntax::visit::{visit_mod}; use util::ppaux::ty_to_str; use core::result::Ok; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::uint; pub struct UniversalQuantificationResult { diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index d9f00451dd57e..b190a98f8cd08 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -548,7 +548,7 @@ use util::common::indenter; use util::ppaux::note_and_explain_region; use core::cell::{Cell, empty_cell}; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::result::{Err, Ok}; use core::to_bytes; use core::uint; diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 2b5a47c18c6d9..1a0a1fceb52a8 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -55,7 +55,7 @@ use middle::ty; use util::common::time; use util::ppaux; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::result; use core::vec; use std::list::List; diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 2a2d921ba8636..98eff8b50d14d 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -14,7 +14,7 @@ use syntax::ast; use syntax::codemap::{span}; use syntax::visit; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use core::str; use std; diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index ff549ad2c2261..2f1d25425ec2b 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -28,7 +28,7 @@ extern mod syntax(vers = "0.6"); use core::*; use core::container::Map; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::io::WriterUtil; use rustc::driver::{driver, session}; use rustc::metadata::filesearch; diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index cd64061af0392..15546e96653d8 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -10,7 +10,7 @@ use core::*; use core::hash::Streaming; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use rustc::driver::{driver, session}; use rustc::metadata::filesearch; use std::getopts::groups::getopts; diff --git a/src/libstd/json.rs b/src/libstd/json.rs index e090d6bc036d8..1b79708e59017 100644 --- a/src/libstd/json.rs +++ b/src/libstd/json.rs @@ -16,7 +16,7 @@ use core::prelude::*; use core::io::{WriterUtil, ReaderUtil}; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use serialize::Encodable; use serialize; @@ -1161,7 +1161,7 @@ mod tests { use super::*; use core::prelude::*; - use core::hashmap::linear::LinearMap; + use core::hashmap::LinearMap; use std::serialize::Decodable; diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index d23784953ef99..b32a9841ac6c1 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -17,7 +17,7 @@ use core::from_str::FromStr; use core::io::{Reader, ReaderUtil}; use core::io; use core::prelude::*; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::str; use core::to_bytes::IterBytes; use core::to_bytes; @@ -818,7 +818,7 @@ mod tests { use net_url::*; - use core::hashmap::linear::LinearMap; + use core::hashmap::LinearMap; #[test] pub fn test_url_parse() { diff --git a/src/libstd/serialize.rs b/src/libstd/serialize.rs index ddc84e07a3584..88ae58ee01b4c 100644 --- a/src/libstd/serialize.rs +++ b/src/libstd/serialize.rs @@ -17,7 +17,7 @@ Core encoding and decoding interfaces. #[forbid(non_camel_case_types)]; use core::prelude::*; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::trie::{TrieMap, TrieSet}; use deque::Deque; use dlist::DList; diff --git a/src/libstd/workcache.rs b/src/libstd/workcache.rs index 6ed1364d7fcb2..6886d5d630e19 100644 --- a/src/libstd/workcache.rs +++ b/src/libstd/workcache.rs @@ -24,7 +24,7 @@ use core::pipes::recv; use core::prelude::*; use core::result; use core::run; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::task; use core::to_bytes; diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index f22b466efebda..04d7cbdca0c3d 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -23,7 +23,7 @@ use print::pprust; use visit; use core::cmp; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::str; use core::vec; diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 9f8dbef9b967b..71e2faa93f569 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -20,7 +20,7 @@ use diagnostic::span_handler; use parse::comments::{doc_comment_style, strip_doc_comment_decoration}; use core::vec; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use std; /* Constructors */ diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 93e2ad64c8c23..cae56267f5eb3 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -20,7 +20,7 @@ use parse; use parse::token; use core::vec; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; // new-style macro! tt code: // @@ -509,7 +509,7 @@ impl MapChain{ #[cfg(test)] mod test { use super::MapChain; - use core::hashmap::linear::LinearMap; + use core::hashmap::LinearMap; #[test] fn testenv () { let mut a = LinearMap::new(); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index f74fbbc3c03f7..fcb0c76a2c78a 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -20,7 +20,7 @@ use parse::token::{Token, EOF, to_str, nonterminal}; use parse::token; use core::prelude::*; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; /* This is an Earley-like parser, without support for in-grammar nonterminals, only by calling out to the main rust parser for named nonterminals (which it diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 67c2f438269d8..de0b4c0799fba 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -18,7 +18,7 @@ use ext::tt::macro_parser::{named_match, matched_seq, matched_nonterminal}; use parse::token::{EOF, INTERPOLATED, IDENT, Token, nt_ident, ident_interner}; use parse::lexer::TokenAndSpan; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::option; use core::vec; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ceafecde3a0b1..1b845ad1dd9d4 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -94,7 +94,7 @@ use opt_vec::OptVec; use core::either::Either; use core::either; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use core::vec; #[deriving(Eq)] diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 5fdf6f7620cc1..ff10b6070e66d 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -18,7 +18,7 @@ use util::interner; use core::cast; use core::char; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use core::str; use core::task; diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 159a205637b59..dd4044036ef84 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -13,7 +13,7 @@ // type, and vice versa. use core::prelude::*; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; pub struct Interner { priv map: @mut LinearMap, diff --git a/src/test/auxiliary/issue-2631-a.rs b/src/test/auxiliary/issue-2631-a.rs index fad72ee4eb360..eded285eef117 100644 --- a/src/test/auxiliary/issue-2631-a.rs +++ b/src/test/auxiliary/issue-2631-a.rs @@ -13,7 +13,7 @@ extern mod std; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; pub type header_map = LinearMap<~str, @mut ~[@~str]>; diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index d6ebf4d346bcc..c30c38e92f724 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -13,7 +13,7 @@ extern mod std; use core::io; use std::time; use std::treemap::TreeMap; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::trie::TrieMap; fn timed(label: &str, f: &fn()) { diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index a3210108dcc17..2fcd82eefe61b 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -9,7 +9,7 @@ // except according to those terms. extern mod std; -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; use std::bitv::BitvSet; use std::treemap::TreeSet; use core::io::WriterUtil; diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index a156f915faca7..397c08228995c 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -24,7 +24,7 @@ use std::arc; use std::time; use std::deque::Deque; use std::par; -use core::hashmap::linear::{LinearMap, LinearSet}; +use core::hashmap::{LinearMap, LinearSet}; use core::io::WriterUtil; use core::int::abs; use core::rand::RngUtil; diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 3bc40a46cfb2c..f608c71000b29 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -15,7 +15,7 @@ extern mod std; use std::sort; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use core::io::ReaderUtil; use core::comm::{stream, Port, Chan}; use core::cmp::Ord; diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 1764ef48412cc..65d99858d1d36 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -25,7 +25,7 @@ // writes pbm image to output path use core::io::WriterUtil; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; struct cmplx { re: f64, diff --git a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs index 6dbfa5dd53847..b3cf314edd001 100644 --- a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs +++ b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs @@ -10,7 +10,7 @@ //buggy.rs -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; fn main() { let mut buggy_map :LinearMap = diff --git a/src/test/compile-fail/borrowck-insert-during-each.rs b/src/test/compile-fail/borrowck-insert-during-each.rs index 788c5397e35d0..1420a67556cad 100644 --- a/src/test/compile-fail/borrowck-insert-during-each.rs +++ b/src/test/compile-fail/borrowck-insert-during-each.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::linear::LinearSet; +use core::hashmap::LinearSet; struct Foo { n: LinearSet, diff --git a/src/test/compile-fail/for-loop-decl.rs b/src/test/compile-fail/for-loop-decl.rs index 918d8f00d7842..c7c1ea4821307 100644 --- a/src/test/compile-fail/for-loop-decl.rs +++ b/src/test/compile-fail/for-loop-decl.rs @@ -11,7 +11,7 @@ // error-pattern: mismatched types extern mod std; use std::bitv; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; struct FnInfo { vars: LinearMap diff --git a/src/test/compile-fail/map-types.rs b/src/test/compile-fail/map-types.rs index 6f71bd40affe5..00efdbbf75acc 100644 --- a/src/test/compile-fail/map-types.rs +++ b/src/test/compile-fail/map-types.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::container::Map; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; // Test that trait types printed in error msgs include the type arguments. diff --git a/src/test/run-fail/unwind-misc-1.rs b/src/test/run-fail/unwind-misc-1.rs index 06a3f0113b01c..5ec4beb364d89 100644 --- a/src/test/run-fail/unwind-misc-1.rs +++ b/src/test/run-fail/unwind-misc-1.rs @@ -14,7 +14,7 @@ fn main() { let count = @mut 0u; - let mut map = core::hashmap::linear::LinearMap::new(); + let mut map = core::hashmap::LinearMap::new(); let mut arr = ~[]; for uint::range(0u, 10u) |i| { arr += ~[@~"key stuff"]; diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index 4234c064e8d38..415f753a562e2 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -19,7 +19,7 @@ pub fn map(filename: ~str, emit: map_reduce::putter) { emit(filename, ~"1"); } mod map_reduce { - use core::hashmap::linear::LinearMap; + use core::hashmap::LinearMap; use core::comm::*; pub type putter = @fn(~str, ~str); diff --git a/src/test/run-pass/issue-1696.rs b/src/test/run-pass/issue-1696.rs index 5f8b8d2983072..401920789c098 100644 --- a/src/test/run-pass/issue-1696.rs +++ b/src/test/run-pass/issue-1696.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; pub fn main() { let mut m = LinearMap::new(); diff --git a/src/test/run-pass/issue-2631-b.rs b/src/test/run-pass/issue-2631-b.rs index b22c423ed0412..42452d3a2bb0f 100644 --- a/src/test/run-pass/issue-2631-b.rs +++ b/src/test/run-pass/issue-2631-b.rs @@ -14,7 +14,7 @@ extern mod req; use req::*; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; pub fn main() { let v = ~[@~"hi"]; diff --git a/src/test/run-pass/issue-2804-2.rs b/src/test/run-pass/issue-2804-2.rs index 8934c3935c087..4f0930deaaef1 100644 --- a/src/test/run-pass/issue-2804-2.rs +++ b/src/test/run-pass/issue-2804-2.rs @@ -13,7 +13,7 @@ // Minimized version of issue-2804.rs. Both check that callee IDs don't // clobber the previous node ID in a macro expr -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; fn add_interfaces(managed_ip: ~str, device: LinearMap<~str, int>) { error!("%s, %?", managed_ip, device.get(&~"interfaces")); diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index 3d1a2c3df5d3b..a1c5f4a6757dc 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -11,7 +11,7 @@ // except according to those terms. extern mod std; -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; use std::json; enum object { diff --git a/src/test/run-pass/issue-3026.rs b/src/test/run-pass/issue-3026.rs index 022d3f6fceb05..9665113bc0cee 100644 --- a/src/test/run-pass/issue-3026.rs +++ b/src/test/run-pass/issue-3026.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; pub fn main() { let mut buggy_map: LinearMap = LinearMap::new::(); diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index f7b7605523c25..a73f130e88981 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -29,7 +29,7 @@ fn check_strs(actual: &str, expected: &str) -> bool #[test] fn tester() { - let mut table = core::hashmap::linear::LinearMap(); + let mut table = core::hashmap::LinearMap(); table.insert(@~"one", 1); table.insert(@~"two", 2); assert!(check_strs(table.to_str(), ~"xxx")); // not sure what expected should be diff --git a/src/test/run-pass/issue-4016.rs b/src/test/run-pass/issue-4016.rs index 69cd1a2a19d86..2384b0e859393 100644 --- a/src/test/run-pass/issue-4016.rs +++ b/src/test/run-pass/issue-4016.rs @@ -11,7 +11,7 @@ // xfail-test extern mod std; -use hashmap::linear; +use hashmap; use std::json; use std::serialization::{Deserializable, deserialize}; diff --git a/src/test/run-pass/issue-4092.rs b/src/test/run-pass/issue-4092.rs index 85cb3e3207ee7..8cda78840b341 100644 --- a/src/test/run-pass/issue-4092.rs +++ b/src/test/run-pass/issue-4092.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::linear::LinearMap; +use core::hashmap::LinearMap; pub fn main() { let mut x = LinearMap::new(); From cc148b58ff7a4eb6861701be61396d1a685f6657 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Wed, 3 Apr 2013 09:28:36 -0400 Subject: [PATCH 16/35] rename Linear{Map,Set} => Hash{Map,Set} --- doc/rust.md | 4 +- doc/tutorial.md | 4 +- src/libcore/gc.rs | 4 +- src/libcore/hashmap.rs | 134 +++++++++--------- src/libcore/task/spawn.rs | 6 +- src/libcore/unstable/global.rs | 6 +- src/libcore/unstable/weak_task.rs | 4 +- src/librustc/back/rpath.rs | 4 +- src/librustc/lib/llvm.rs | 10 +- src/librustc/metadata/creader.rs | 4 +- src/librustc/metadata/cstore.rs | 12 +- src/librustc/metadata/encoder.rs | 14 +- src/librustc/metadata/tyencode.rs | 4 +- src/librustc/middle/borrowck/check_loans.rs | 6 +- src/librustc/middle/borrowck/gather_loans.rs | 10 +- src/librustc/middle/borrowck/mod.rs | 20 +-- src/librustc/middle/const_eval.rs | 18 +-- src/librustc/middle/freevars.rs | 8 +- src/librustc/middle/lang_items.rs | 6 +- src/librustc/middle/lint.rs | 10 +- src/librustc/middle/liveness.rs | 24 ++-- src/librustc/middle/moves.rs | 14 +- src/librustc/middle/pat_util.rs | 6 +- src/librustc/middle/region.rs | 18 +-- src/librustc/middle/resolve.rs | 66 ++++----- src/librustc/middle/trans/_match.rs | 6 +- src/librustc/middle/trans/base.rs | 62 ++++---- src/librustc/middle/trans/build.rs | 4 +- src/librustc/middle/trans/common.rs | 58 ++++---- src/librustc/middle/trans/debuginfo.rs | 6 +- src/librustc/middle/trans/expr.rs | 4 +- src/librustc/middle/trans/reachable.rs | 12 +- src/librustc/middle/ty.rs | 102 ++++++------- src/librustc/middle/typeck/check/_match.rs | 8 +- src/librustc/middle/typeck/check/method.rs | 6 +- src/librustc/middle/typeck/check/mod.rs | 26 ++-- src/librustc/middle/typeck/check/vtable.rs | 4 +- src/librustc/middle/typeck/coherence.rs | 24 ++-- .../middle/typeck/infer/region_inference.rs | 18 +-- src/librustc/middle/typeck/mod.rs | 10 +- src/librustc/util/common.rs | 4 +- src/librustpkg/rustpkg.rc | 10 +- src/librustpkg/util.rs | 4 +- src/libstd/json.rs | 16 +-- src/libstd/net_url.rs | 16 +-- src/libstd/serialize.rs | 18 +-- src/libstd/workcache.rs | 16 +-- src/libsyntax/ast_map.rs | 6 +- src/libsyntax/attr.rs | 4 +- src/libsyntax/ext/base.rs | 18 +-- src/libsyntax/ext/tt/macro_parser.rs | 12 +- src/libsyntax/ext/tt/transcribe.rs | 8 +- src/libsyntax/parse/parser.rs | 12 +- src/libsyntax/parse/token.rs | 18 +-- src/libsyntax/util/interner.rs | 6 +- src/test/auxiliary/issue-2631-a.rs | 4 +- src/test/bench/core-map.rs | 12 +- src/test/bench/core-set.rs | 8 +- src/test/bench/graph500-bfs.rs | 6 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 10 +- src/test/bench/shootout-mandelbrot.rs | 4 +- .../borrowck-borrowed-uniq-rvalue.rs | 6 +- .../borrowck-insert-during-each.rs | 6 +- src/test/compile-fail/for-loop-decl.rs | 4 +- src/test/compile-fail/map-types.rs | 4 +- src/test/run-fail/unwind-misc-1.rs | 2 +- src/test/run-pass/explicit-self-generic.rs | 10 +- src/test/run-pass/hashmap-memory.rs | 10 +- src/test/run-pass/issue-1696.rs | 4 +- src/test/run-pass/issue-2631-b.rs | 4 +- src/test/run-pass/issue-2804-2.rs | 4 +- src/test/run-pass/issue-2804.rs | 4 +- src/test/run-pass/issue-3026.rs | 4 +- src/test/run-pass/issue-3559.rs | 2 +- src/test/run-pass/issue-4092.rs | 4 +- 75 files changed, 523 insertions(+), 523 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index 64f0dc93e7867..66280b1b9723e 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -441,10 +441,10 @@ expression context, the final namespace qualifier is omitted. Two examples of paths with type arguments: ~~~~ -# use core::hashmap::LinearMap; +# use core::hashmap::HashMap; # fn f() { # fn id(t: T) -> T { t } -type t = LinearMap; // Type arguments used in a type expression +type t = HashMap; // Type arguments used in a type expression let x = id::(10); // Type arguments used in a call expression # } ~~~~ diff --git a/doc/tutorial.md b/doc/tutorial.md index 8c5294767c26a..42c3a7a8d664f 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1888,8 +1888,8 @@ illegal to copy and pass by value. Generic `type`, `struct`, and `enum` declarations follow the same pattern: ~~~~ -# use core::hashmap::LinearMap; -type Set = LinearMap; +# use core::hashmap::HashMap; +type Set = HashMap; struct Stack { elements: ~[T] diff --git a/src/libcore/gc.rs b/src/libcore/gc.rs index 46f2ad76d0792..9fd9ac3a8c8ec 100644 --- a/src/libcore/gc.rs +++ b/src/libcore/gc.rs @@ -43,7 +43,7 @@ use io; use libc::{size_t, uintptr_t}; use option::{None, Option, Some}; use ptr; -use hashmap::LinearSet; +use hashmap::HashSet; use stackwalk; use sys; @@ -344,7 +344,7 @@ pub fn cleanup_stack_for_failure() { ptr::null() }; - let mut roots = LinearSet::new(); + let mut roots = HashSet::new(); for walk_gc_roots(need_cleanup, sentinel) |root, tydesc| { // Track roots to avoid double frees. if roots.contains(&*root) { diff --git a/src/libcore/hashmap.rs b/src/libcore/hashmap.rs index 67942abba4633..5dbf085f09719 100644 --- a/src/libcore/hashmap.rs +++ b/src/libcore/hashmap.rs @@ -35,7 +35,7 @@ struct Bucket { value: V, } -pub struct LinearMap { +pub struct HashMap { priv k0: u64, priv k1: u64, priv resize_at: uint, @@ -55,7 +55,7 @@ fn resize_at(capacity: uint) -> uint { } pub fn linear_map_with_capacity( - initial_capacity: uint) -> LinearMap { + initial_capacity: uint) -> HashMap { let r = rand::task_rng(); linear_map_with_capacity_and_keys(r.gen_u64(), r.gen_u64(), initial_capacity) @@ -63,8 +63,8 @@ pub fn linear_map_with_capacity( fn linear_map_with_capacity_and_keys( k0: u64, k1: u64, - initial_capacity: uint) -> LinearMap { - LinearMap { + initial_capacity: uint) -> HashMap { + HashMap { k0: k0, k1: k1, resize_at: resize_at(initial_capacity), size: 0, @@ -72,7 +72,7 @@ fn linear_map_with_capacity_and_keys( } } -priv impl LinearMap { +priv impl HashMap { #[inline(always)] fn to_bucket(&self, h: uint) -> uint { // A good hash function with entropy spread over all of the @@ -190,7 +190,7 @@ priv impl LinearMap { fn value_for_bucket(&self, idx: uint) -> &'self V { match self.buckets[idx] { Some(ref bkt) => &bkt.value, - None => fail!(~"LinearMap::find: internal logic error"), + None => fail!(~"HashMap::find: internal logic error"), } } @@ -280,7 +280,7 @@ priv impl LinearMap { } impl<'self,K:Hash + IterBytes + Eq,V> - BaseIter<(&'self K, &'self V)> for LinearMap { + BaseIter<(&'self K, &'self V)> for HashMap { /// Visit all key-value pairs fn each(&self, blk: &fn(&(&'self K, &'self V)) -> bool) { for uint::range(0, self.buckets.len()) |i| { @@ -297,7 +297,7 @@ impl<'self,K:Hash + IterBytes + Eq,V> } -impl Container for LinearMap { +impl Container for HashMap { /// Return the number of elements in the map fn len(&const self) -> uint { self.size } @@ -305,7 +305,7 @@ impl Container for LinearMap { fn is_empty(&const self) -> bool { self.len() == 0 } } -impl Mutable for LinearMap { +impl Mutable for HashMap { /// Clear the map, removing all key-value pairs. fn clear(&mut self) { for uint::range(0, self.buckets.len()) |idx| { @@ -315,7 +315,7 @@ impl Mutable for LinearMap { } } -impl<'self,K:Hash + IterBytes + Eq,V> Map for LinearMap { +impl<'self,K:Hash + IterBytes + Eq,V> Map for HashMap { /// Return true if the map contains a value for the specified key fn contains_key(&self, k: &K) -> bool { match self.bucket_for_key(k) { @@ -391,15 +391,15 @@ impl<'self,K:Hash + IterBytes + Eq,V> Map for LinearMap { } } -pub impl LinearMap { - /// Create an empty LinearMap - fn new() -> LinearMap { - LinearMap::with_capacity(INITIAL_CAPACITY) +pub impl HashMap { + /// Create an empty HashMap + fn new() -> HashMap { + HashMap::with_capacity(INITIAL_CAPACITY) } - /// Create an empty LinearMap with space for at least `n` elements in + /// Create an empty HashMap with space for at least `n` elements in /// the hash table. - fn with_capacity(capacity: uint) -> LinearMap { + fn with_capacity(capacity: uint) -> HashMap { linear_map_with_capacity(capacity) } @@ -541,8 +541,8 @@ pub impl LinearMap { } } -impl Eq for LinearMap { - fn eq(&self, other: &LinearMap) -> bool { +impl Eq for HashMap { + fn eq(&self, other: &HashMap) -> bool { if self.len() != other.len() { return false; } for self.each |&(key, value)| { @@ -555,25 +555,25 @@ impl Eq for LinearMap { true } - fn ne(&self, other: &LinearMap) -> bool { !self.eq(other) } + fn ne(&self, other: &HashMap) -> bool { !self.eq(other) } } -pub struct LinearSet { - priv map: LinearMap +pub struct HashSet { + priv map: HashMap } -impl BaseIter for LinearSet { +impl BaseIter for HashSet { /// Visit all values in order fn each(&self, f: &fn(&T) -> bool) { self.map.each_key(f) } fn size_hint(&self) -> Option { Some(self.len()) } } -impl Eq for LinearSet { - fn eq(&self, other: &LinearSet) -> bool { self.map == other.map } - fn ne(&self, other: &LinearSet) -> bool { self.map != other.map } +impl Eq for HashSet { + fn eq(&self, other: &HashSet) -> bool { self.map == other.map } + fn ne(&self, other: &HashSet) -> bool { self.map != other.map } } -impl Container for LinearSet { +impl Container for HashSet { /// Return the number of elements in the set fn len(&const self) -> uint { self.map.len() } @@ -581,12 +581,12 @@ impl Container for LinearSet { fn is_empty(&const self) -> bool { self.map.is_empty() } } -impl Mutable for LinearSet { +impl Mutable for HashSet { /// Clear the set, removing all values. fn clear(&mut self) { self.map.clear() } } -impl Set for LinearSet { +impl Set for HashSet { /// Return true if the set contains a value fn contains(&self, value: &T) -> bool { self.map.contains_key(value) } @@ -600,22 +600,22 @@ impl Set for LinearSet { /// Return true if the set has no elements in common with `other`. /// This is equivalent to checking for an empty intersection. - fn is_disjoint(&self, other: &LinearSet) -> bool { + fn is_disjoint(&self, other: &HashSet) -> bool { iter::all(self, |v| !other.contains(v)) } /// Return true if the set is a subset of another - fn is_subset(&self, other: &LinearSet) -> bool { + fn is_subset(&self, other: &HashSet) -> bool { iter::all(self, |v| other.contains(v)) } /// Return true if the set is a superset of another - fn is_superset(&self, other: &LinearSet) -> bool { + fn is_superset(&self, other: &HashSet) -> bool { other.is_subset(self) } /// Visit the values representing the difference - fn difference(&self, other: &LinearSet, f: &fn(&T) -> bool) { + fn difference(&self, other: &HashSet, f: &fn(&T) -> bool) { for self.each |v| { if !other.contains(v) { if !f(v) { return } @@ -625,14 +625,14 @@ impl Set for LinearSet { /// Visit the values representing the symmetric difference fn symmetric_difference(&self, - other: &LinearSet, + other: &HashSet, f: &fn(&T) -> bool) { self.difference(other, f); other.difference(self, f); } /// Visit the values representing the intersection - fn intersection(&self, other: &LinearSet, f: &fn(&T) -> bool) { + fn intersection(&self, other: &HashSet, f: &fn(&T) -> bool) { for self.each |v| { if other.contains(v) { if !f(v) { return } @@ -641,7 +641,7 @@ impl Set for LinearSet { } /// Visit the values representing the union - fn union(&self, other: &LinearSet, f: &fn(&T) -> bool) { + fn union(&self, other: &HashSet, f: &fn(&T) -> bool) { for self.each |v| { if !f(v) { return } } @@ -654,16 +654,16 @@ impl Set for LinearSet { } } -pub impl LinearSet { - /// Create an empty LinearSet - fn new() -> LinearSet { - LinearSet::with_capacity(INITIAL_CAPACITY) +pub impl HashSet { + /// Create an empty HashSet + fn new() -> HashSet { + HashSet::with_capacity(INITIAL_CAPACITY) } - /// Create an empty LinearSet with space for at least `n` elements in + /// Create an empty HashSet with space for at least `n` elements in /// the hash table. - fn with_capacity(capacity: uint) -> LinearSet { - LinearSet { map: LinearMap::with_capacity(capacity) } + fn with_capacity(capacity: uint) -> HashSet { + HashSet { map: HashMap::with_capacity(capacity) } } /// Reserve space for at least `n` elements in the hash table. @@ -686,7 +686,7 @@ mod test_map { #[test] pub fn test_insert() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.insert(1, 2)); assert!(m.insert(2, 4)); assert!(*m.get(&1) == 2); @@ -695,7 +695,7 @@ mod test_map { #[test] fn test_find_mut() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.insert(1, 12)); assert!(m.insert(2, 8)); assert!(m.insert(5, 14)); @@ -708,7 +708,7 @@ mod test_map { #[test] pub fn test_insert_overwrite() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.insert(1, 2)); assert!(*m.get(&1) == 2); assert!(!m.insert(1, 3)); @@ -748,7 +748,7 @@ mod test_map { #[test] pub fn test_pop() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); m.insert(1, 2); assert!(m.pop(&1) == Some(2)); assert!(m.pop(&1) == None); @@ -756,7 +756,7 @@ mod test_map { #[test] pub fn test_swap() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.swap(1, 2) == None); assert!(m.swap(1, 3) == Some(2)); assert!(m.swap(1, 4) == Some(3)); @@ -764,24 +764,24 @@ mod test_map { #[test] pub fn test_find_or_insert() { - let mut m = LinearMap::new::(); + let mut m = HashMap::new::(); assert!(m.find_or_insert(1, 2) == &2); assert!(m.find_or_insert(1, 3) == &2); } #[test] pub fn test_find_or_insert_with() { - let mut m = LinearMap::new::(); + let mut m = HashMap::new::(); assert!(m.find_or_insert_with(1, |_| 2) == &2); assert!(m.find_or_insert_with(1, |_| 3) == &2); } #[test] pub fn test_consume() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.insert(1, 2)); assert!(m.insert(2, 3)); - let mut m2 = LinearMap::new(); + let mut m2 = HashMap::new(); do m.consume |k, v| { m2.insert(k, v); } @@ -807,7 +807,7 @@ mod test_map { #[test] pub fn test_find() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.find(&1).is_none()); m.insert(1, 2); match m.find(&1) { @@ -818,12 +818,12 @@ mod test_map { #[test] pub fn test_eq() { - let mut m1 = LinearMap::new(); + let mut m1 = HashMap::new(); m1.insert(1, 2); m1.insert(2, 3); m1.insert(3, 4); - let mut m2 = LinearMap::new(); + let mut m2 = HashMap::new(); m2.insert(1, 2); m2.insert(2, 3); @@ -836,7 +836,7 @@ mod test_map { #[test] pub fn test_expand() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(m.len() == 0); assert!(m.is_empty()); @@ -861,8 +861,8 @@ mod test_set { #[test] fn test_disjoint() { - let mut xs = LinearSet::new(); - let mut ys = LinearSet::new(); + let mut xs = HashSet::new(); + let mut ys = HashSet::new(); assert!(xs.is_disjoint(&ys)); assert!(ys.is_disjoint(&xs)); assert!(xs.insert(5)); @@ -883,13 +883,13 @@ mod test_set { #[test] fn test_subset_and_superset() { - let mut a = LinearSet::new(); + let mut a = HashSet::new(); assert!(a.insert(0)); assert!(a.insert(5)); assert!(a.insert(11)); assert!(a.insert(7)); - let mut b = LinearSet::new(); + let mut b = HashSet::new(); assert!(b.insert(0)); assert!(b.insert(7)); assert!(b.insert(19)); @@ -912,8 +912,8 @@ mod test_set { #[test] fn test_intersection() { - let mut a = LinearSet::new(); - let mut b = LinearSet::new(); + let mut a = HashSet::new(); + let mut b = HashSet::new(); assert!(a.insert(11)); assert!(a.insert(1)); @@ -942,8 +942,8 @@ mod test_set { #[test] fn test_difference() { - let mut a = LinearSet::new(); - let mut b = LinearSet::new(); + let mut a = HashSet::new(); + let mut b = HashSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); @@ -965,8 +965,8 @@ mod test_set { #[test] fn test_symmetric_difference() { - let mut a = LinearSet::new(); - let mut b = LinearSet::new(); + let mut a = HashSet::new(); + let mut b = HashSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); @@ -991,8 +991,8 @@ mod test_set { #[test] fn test_union() { - let mut a = LinearSet::new(); - let mut b = LinearSet::new(); + let mut a = HashSet::new(); + let mut b = HashSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index ac6775eb81fec..e1b645cd56272 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -79,7 +79,7 @@ use comm::{Chan, GenericChan}; use prelude::*; use unstable; use ptr; -use hashmap::LinearSet; +use hashmap::HashSet; use task::local_data_priv::{local_get, local_set}; use task::rt::rust_task; use task::rt; @@ -96,10 +96,10 @@ macro_rules! move_it ( { $x:expr } => ( unsafe { let y = *ptr::addr_of(&($x)); y } ) ) -type TaskSet = LinearSet<*rust_task>; +type TaskSet = HashSet<*rust_task>; fn new_taskset() -> TaskSet { - LinearSet::new() + HashSet::new() } fn taskset_insert(tasks: &mut TaskSet, task: *rust_task) { let didnt_overwrite = tasks.insert(task); diff --git a/src/libcore/unstable/global.rs b/src/libcore/unstable/global.rs index 3187012e2a983..41d0842002f67 100644 --- a/src/libcore/unstable/global.rs +++ b/src/libcore/unstable/global.rs @@ -34,7 +34,7 @@ use ops::Drop; use unstable::{Exclusive, exclusive}; use unstable::at_exit::at_exit; use unstable::intrinsics::atomic_cxchg; -use hashmap::LinearMap; +use hashmap::HashMap; use sys::Closure; #[cfg(test)] use unstable::{SharedMutableState, shared_mutable_state}; @@ -144,7 +144,7 @@ pub unsafe fn global_data_clone( // destructor. Keys are pointers derived from the type of the // global value. There is a single GlobalState instance per runtime. struct GlobalState { - map: LinearMap + map: HashMap } impl Drop for GlobalState { @@ -171,7 +171,7 @@ fn get_global_state() -> Exclusive { // The global state object let state = GlobalState { - map: LinearMap::new() + map: HashMap::new() }; // It's under a reference-counted mutex diff --git a/src/libcore/unstable/weak_task.rs b/src/libcore/unstable/weak_task.rs index 5556792c22543..6eabb0629d1fc 100644 --- a/src/libcore/unstable/weak_task.rs +++ b/src/libcore/unstable/weak_task.rs @@ -21,7 +21,7 @@ is trying to shut down. use cell::Cell; use comm::{GenericSmartChan, stream}; use comm::{Port, Chan, SharedChan, GenericChan, GenericPort}; -use hashmap::LinearMap; +use hashmap::HashMap; use option::{Some, None}; use unstable::at_exit::at_exit; use unstable::finally::Finally; @@ -97,7 +97,7 @@ fn create_global_service() -> ~WeakTaskService { fn run_weak_task_service(port: Port) { - let mut shutdown_map = LinearMap::new(); + let mut shutdown_map = HashMap::new(); loop { match port.recv() { diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 89d1eb53c8201..cc1168bd79ddd 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -18,7 +18,7 @@ use core::os; use core::uint; use core::util; use core::vec; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; fn not_win32(os: session::os) -> bool { match os { @@ -186,7 +186,7 @@ pub fn get_install_prefix_rpath(target_triple: &str) -> Path { } pub fn minimize_rpaths(rpaths: &[Path]) -> ~[Path] { - let mut set = LinearSet::new(); + let mut set = HashSet::new(); let mut minimized = ~[]; for rpaths.each |rpath| { if set.insert(rpath.to_str()) { diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index c50eecd448976..b6d3fce7e7546 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -10,7 +10,7 @@ use core::prelude::*; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::libc::c_uint; use core::option; use core::ptr; @@ -1467,8 +1467,8 @@ pub fn SetLinkage(Global: ValueRef, Link: Linkage) { /* Memory-managed object interface to type handles. */ pub struct TypeNames { - type_names: @mut LinearMap, - named_types: @mut LinearMap<@str, TypeRef> + type_names: @mut HashMap, + named_types: @mut HashMap<@str, TypeRef> } pub fn associate_type(tn: @TypeNames, s: @str, t: TypeRef) { @@ -1486,8 +1486,8 @@ pub fn name_has_type(tn: @TypeNames, s: @str) -> Option { pub fn mk_type_names() -> @TypeNames { @TypeNames { - type_names: @mut LinearMap::new(), - named_types: @mut LinearMap::new() + type_names: @mut HashMap::new(), + named_types: @mut HashMap::new() } } diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index eb01964f6d692..8609434e6df29 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -18,7 +18,7 @@ use metadata::decoder; use metadata::filesearch::FileSearch; use metadata::loader; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::vec; use syntax::attr; use syntax::codemap::{span, dummy_sp}; @@ -302,7 +302,7 @@ fn resolve_crate_deps(e: @mut Env, cdata: @~[u8]) -> cstore::cnum_map { debug!("resolving deps of external crate"); // The map from crate numbers in the crate we're resolving to local crate // numbers - let mut cnum_map = LinearMap::new(); + let mut cnum_map = HashMap::new(); for decoder::get_crate_deps(e.intr, cdata).each |dep| { let extrn_cnum = dep.cnum; let cname = dep.name; diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 13447d09736e4..65bd37236b714 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -17,7 +17,7 @@ use core::prelude::*; use metadata::cstore; use metadata::decoder; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::vec; use std; use syntax::ast; @@ -27,7 +27,7 @@ use syntax::parse::token::ident_interner; // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. -pub type cnum_map = @mut LinearMap; +pub type cnum_map = @mut HashMap; pub struct crate_metadata { name: @~str, @@ -37,7 +37,7 @@ pub struct crate_metadata { } pub struct CStore { - priv metas: LinearMap , + priv metas: HashMap , priv extern_mod_crate_map: extern_mod_crate_map, priv used_crate_files: ~[Path], priv used_libraries: ~[~str], @@ -46,12 +46,12 @@ pub struct CStore { } // Map from node_id's of local extern mod statements to crate numbers -type extern_mod_crate_map = LinearMap; +type extern_mod_crate_map = HashMap; pub fn mk_cstore(intr: @ident_interner) -> CStore { return CStore { - metas: LinearMap::new(), - extern_mod_crate_map: LinearMap::new(), + metas: HashMap::new(), + extern_mod_crate_map: HashMap::new(), used_crate_files: ~[], used_libraries: ~[], used_link_args: ~[], diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index b7ad62ee4ed2c..6000e559554f3 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -25,7 +25,7 @@ use util::ppaux::ty_to_str; use core::flate; use core::hash::HashUtil; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::int; use core::io::{Writer, WriterUtil}; use core::io; @@ -50,7 +50,7 @@ use syntax; use writer = std::ebml::writer; // used by astencode: -type abbrev_map = @mut LinearMap; +type abbrev_map = @mut HashMap; pub type encode_inlined_item = @fn(ecx: @EncodeContext, ebml_w: writer::Encoder, @@ -62,8 +62,8 @@ pub struct EncodeParams { tcx: ty::ctxt, reachable: reachable::map, reexports2: middle::resolve::ExportMap2, - item_symbols: @mut LinearMap, - discrim_symbols: @mut LinearMap, + item_symbols: @mut HashMap, + discrim_symbols: @mut HashMap, link_meta: LinkMeta, cstore: @mut cstore::CStore, encode_inlined_item: encode_inlined_item @@ -89,8 +89,8 @@ pub struct EncodeContext { stats: @mut Stats, reachable: reachable::map, reexports2: middle::resolve::ExportMap2, - item_symbols: @mut LinearMap, - discrim_symbols: @mut LinearMap, + item_symbols: @mut HashMap, + discrim_symbols: @mut HashMap, link_meta: LinkMeta, cstore: @mut cstore::CStore, encode_inlined_item: encode_inlined_item, @@ -1345,7 +1345,7 @@ pub fn encode_metadata(+parms: EncodeParams, crate: &crate) -> ~[u8] { link_meta: link_meta, cstore: cstore, encode_inlined_item: encode_inlined_item, - type_abbrevs: @mut LinearMap::new() + type_abbrevs: @mut HashMap::new() }; let ebml_w = writer::Encoder(wr as @io::Writer); diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 05f5f302f5379..251ba9b35cbd9 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -16,7 +16,7 @@ use core::prelude::*; use middle::ty::param_ty; use middle::ty; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::io::WriterUtil; use core::io; use core::uint; @@ -47,7 +47,7 @@ pub struct ty_abbrev { pub enum abbrev_ctxt { ac_no_abbrevs, - ac_use_abbrevs(@mut LinearMap), + ac_use_abbrevs(@mut HashMap), } fn cx_uses_abbrevs(cx: @ctxt) -> bool { diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index 2bf89903e1c8b..160356567421d 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -31,7 +31,7 @@ use middle::mem_categorization::{lp_comp, lp_deref, lp_local}; use middle::ty; use util::ppaux::ty_to_str; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use core::uint; use syntax::ast::m_mutbl; use syntax::ast; @@ -44,7 +44,7 @@ struct CheckLoanCtxt { bccx: @BorrowckCtxt, req_maps: ReqMaps, - reported: LinearSet, + reported: HashSet, declared_purity: @mut ast::purity, fn_args: @mut @~[ast::node_id] @@ -68,7 +68,7 @@ pub fn check_loans(bccx: @BorrowckCtxt, let clcx = @mut CheckLoanCtxt { bccx: bccx, req_maps: req_maps, - reported: LinearSet::new(), + reported: HashSet::new(), declared_purity: @mut ast::impure_fn, fn_args: @mut @~[] }; diff --git a/src/librustc/middle/borrowck/gather_loans.rs b/src/librustc/middle/borrowck/gather_loans.rs index 2965921b05a81..122e2c64b2133 100644 --- a/src/librustc/middle/borrowck/gather_loans.rs +++ b/src/librustc/middle/borrowck/gather_loans.rs @@ -31,7 +31,7 @@ use middle::ty; use util::common::indenter; use util::ppaux::{expr_repr, region_to_str}; -use core::hashmap::{LinearSet, LinearMap}; +use core::hashmap::{HashSet, HashMap}; use core::vec; use syntax::ast::{m_const, m_imm, m_mutbl}; use syntax::ast; @@ -72,17 +72,17 @@ struct GatherLoanCtxt { req_maps: ReqMaps, item_ub: ast::node_id, root_ub: ast::node_id, - ignore_adjustments: LinearSet + ignore_adjustments: HashSet } pub fn gather_loans(bccx: @BorrowckCtxt, crate: @ast::crate) -> ReqMaps { let glcx = @mut GatherLoanCtxt { bccx: bccx, - req_maps: ReqMaps { req_loan_map: LinearMap::new(), - pure_map: LinearMap::new() }, + req_maps: ReqMaps { req_loan_map: HashMap::new(), + pure_map: HashMap::new() }, item_ub: 0, root_ub: 0, - ignore_adjustments: LinearSet::new() + ignore_adjustments: HashSet::new() }; let v = visit::mk_vt(@visit::Visitor {visit_expr: req_loans_in_expr, visit_fn: req_loans_in_fn, diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index ca3365bbcabc4..5e7903f66102f 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -234,7 +234,7 @@ use middle::moves; use util::common::stmt_set; use util::ppaux::note_and_explain_region; -use core::hashmap::{LinearSet, LinearMap}; +use core::hashmap::{HashSet, HashMap}; use core::io; use core::result::{Result, Ok, Err}; use core::to_bytes; @@ -260,9 +260,9 @@ pub fn check_crate( moves_map: moves_map, capture_map: capture_map, root_map: root_map(), - mutbl_map: @mut LinearSet::new(), - write_guard_map: @mut LinearSet::new(), - stmt_map: @mut LinearSet::new(), + mutbl_map: @mut HashSet::new(), + write_guard_map: @mut HashSet::new(), + stmt_map: @mut HashSet::new(), stats: @mut BorrowStats { loaned_paths_same: 0, loaned_paths_imm: 0, @@ -333,7 +333,7 @@ pub struct RootInfo { // a map mapping id's of expressions of gc'd type (@T, @[], etc) where // the box needs to be kept live to the id of the scope for which they // must stay live. -pub type root_map = @mut LinearMap; +pub type root_map = @mut HashMap; // the keys to the root map combine the `id` of the expression with // the number of types that it is autodereferenced. So, for example, @@ -348,11 +348,11 @@ pub struct root_map_key { // set of ids of local vars / formal arguments that are modified / moved. // this is used in trans for optimization purposes. -pub type mutbl_map = @mut LinearSet; +pub type mutbl_map = @mut HashSet; // A set containing IDs of expressions of gc'd type that need to have a write // guard. -pub type write_guard_map = @mut LinearSet; +pub type write_guard_map = @mut HashSet; // Errors that can occur #[deriving(Eq)] @@ -405,8 +405,8 @@ pub struct Loan { /// - `pure_map`: map from block/expr that must be pure to the error message /// that should be reported if they are not pure pub struct ReqMaps { - req_loan_map: LinearMap, - pure_map: LinearMap + req_loan_map: HashMap, + pure_map: HashMap } pub fn save_and_restore(save_and_restore_t: &mut T, @@ -450,7 +450,7 @@ impl to_bytes::IterBytes for root_map_key { } pub fn root_map() -> root_map { - return @mut LinearMap::new(); + return @mut HashMap::new(); } // ___________________________________________________________________________ diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 788d8f6de89cd..d6434e469b2d1 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -20,7 +20,7 @@ use core::vec; use syntax::{ast, ast_map, ast_util, visit}; use syntax::ast::*; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; // // This pass classifies expressions by their constant-ness. @@ -189,14 +189,14 @@ pub fn lookup_const_by_id(tcx: ty::ctxt, } } else { let maps = astencode::Maps { - mutbl_map: @mut LinearSet::new(), - root_map: @mut LinearMap::new(), - last_use_map: @mut LinearMap::new(), - method_map: @mut LinearMap::new(), - vtable_map: @mut LinearMap::new(), - write_guard_map: @mut LinearSet::new(), - moves_map: @mut LinearSet::new(), - capture_map: @mut LinearMap::new() + mutbl_map: @mut HashSet::new(), + root_map: @mut HashMap::new(), + last_use_map: @mut HashMap::new(), + method_map: @mut HashMap::new(), + vtable_map: @mut HashMap::new(), + write_guard_map: @mut HashSet::new(), + moves_map: @mut HashSet::new(), + capture_map: @mut HashMap::new() }; match csearch::maybe_get_item_ast(tcx, def_id, |a, b, c, d| astencode::decode_inlined_item(a, b, maps, /*bar*/ copy c, d)) { diff --git a/src/librustc/middle/freevars.rs b/src/librustc/middle/freevars.rs index d680d1547351a..e6e9f3be85d21 100644 --- a/src/librustc/middle/freevars.rs +++ b/src/librustc/middle/freevars.rs @@ -17,7 +17,7 @@ use core::prelude::*; use middle::resolve; use middle::ty; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use syntax::codemap::span; use syntax::{ast, ast_util, visit}; @@ -30,7 +30,7 @@ pub struct freevar_entry { span: span //< First span where it is accessed (there can be multiple) } pub type freevar_info = @~[@freevar_entry]; -pub type freevar_map = @mut LinearMap; +pub type freevar_map = @mut HashMap; // Searches through part of the AST for all references to locals or // upvars in this frame and returns the list of definition IDs thus found. @@ -39,7 +39,7 @@ pub type freevar_map = @mut LinearMap; // in order to start the search. fn collect_freevars(def_map: resolve::DefMap, blk: &ast::blk) -> freevar_info { - let seen = @mut LinearMap::new(); + let seen = @mut HashMap::new(); let refs = @mut ~[]; fn ignore_item(_i: @ast::item, &&_depth: int, _v: visit::vt) { } @@ -92,7 +92,7 @@ fn collect_freevars(def_map: resolve::DefMap, blk: &ast::blk) // one pass. This could be improved upon if it turns out to matter. pub fn annotate_freevars(def_map: resolve::DefMap, crate: @ast::crate) -> freevar_map { - let freevars = @mut LinearMap::new(); + let freevars = @mut HashMap::new(); let walk_fn: @fn(&visit::fn_kind, &ast::fn_decl, diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 7c399bf2ece68..ab9b8ca0db624 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -31,7 +31,7 @@ use syntax::ast_util::local_def; use syntax::visit::{default_simple_visitor, mk_simple_visitor, SimpleVisitor}; use syntax::visit::visit_crate; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::ptr; pub enum LangItem { @@ -259,7 +259,7 @@ fn LanguageItemCollector<'r>(crate: @crate, session: Session, items: &'r mut LanguageItems) -> LanguageItemCollector<'r> { - let mut item_refs = LinearMap::new(); + let mut item_refs = HashMap::new(); item_refs.insert(@~"const", ConstTraitLangItem as uint); item_refs.insert(@~"copy", CopyTraitLangItem as uint); @@ -317,7 +317,7 @@ struct LanguageItemCollector<'self> { crate: @crate, session: Session, - item_refs: LinearMap<@~str, uint>, + item_refs: HashMap<@~str, uint>, } pub impl<'self> LanguageItemCollector<'self> { diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index d4cd500f04c48..a21cc26bd9124 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -15,7 +15,7 @@ use driver::session; use middle::ty; use util::ppaux::{ty_to_str}; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::char; use core::cmp; use core::i8; @@ -108,7 +108,7 @@ struct LintSpec { default: level } -pub type LintDict = @LinearMap<~str, LintSpec>; +pub type LintDict = @HashMap<~str, LintSpec>; /* Pass names should not contain a '-', as the compiler normalizes @@ -273,7 +273,7 @@ pub fn get_lint_dict() -> LintDict { }), */ ]; - let mut map = LinearMap::new(); + let mut map = HashMap::new(); do vec::consume(v) |_, (k, v)| { map.insert(k, v); } @@ -282,7 +282,7 @@ pub fn get_lint_dict() -> LintDict { // This is a highly not-optimal set of data structure decisions. type LintModes = @mut SmallIntMap; -type LintModeMap = @mut LinearMap; +type LintModeMap = @mut HashMap; // settings_map maps node ids of items with non-default lint settings // to their settings; default_settings contains the settings for everything @@ -295,7 +295,7 @@ pub struct LintSettings { pub fn mk_lint_settings() -> LintSettings { LintSettings { default_settings: @mut SmallIntMap::new(), - settings_map: @mut LinearMap::new() + settings_map: @mut HashMap::new() } } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index a91404fb47a2a..01598b118518d 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,7 +111,7 @@ use middle::typeck; use middle::moves; use util::ppaux::ty_to_str; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::io::WriterUtil; use core::io; use core::ptr; @@ -134,7 +134,7 @@ use syntax::{visit, ast_util}; // // Very subtle (#2633): borrowck will remove entries from this table // if it detects an outstanding loan (that is, the addr is taken). -pub type last_use_map = @mut LinearMap; +pub type last_use_map = @mut HashMap; #[deriving(Eq)] struct Variable(uint); @@ -172,7 +172,7 @@ pub fn check_crate(tcx: ty::ctxt, .. *visit::default_visitor() }); - let last_use_map = @mut LinearMap::new(); + let last_use_map = @mut HashMap::new(); let initial_maps = @mut IrMaps(tcx, method_map, variable_moves_map, @@ -264,9 +264,9 @@ struct IrMaps { num_live_nodes: uint, num_vars: uint, - live_node_map: LinearMap, - variable_map: LinearMap, - capture_info_map: LinearMap, + live_node_map: HashMap, + variable_map: HashMap, + capture_info_map: HashMap, var_kinds: ~[VarKind], lnks: ~[LiveNodeKind], } @@ -285,9 +285,9 @@ fn IrMaps(tcx: ty::ctxt, last_use_map: last_use_map, num_live_nodes: 0, num_vars: 0, - live_node_map: LinearMap::new(), - variable_map: LinearMap::new(), - capture_info_map: LinearMap::new(), + live_node_map: HashMap::new(), + variable_map: HashMap::new(), + capture_info_map: HashMap::new(), var_kinds: ~[], lnks: ~[] } @@ -612,7 +612,7 @@ static ACC_READ: uint = 1u; static ACC_WRITE: uint = 2u; static ACC_USE: uint = 4u; -type LiveNodeMap = @mut LinearMap; +type LiveNodeMap = @mut HashMap; struct Liveness { tcx: ty::ctxt, @@ -639,8 +639,8 @@ fn Liveness(ir: @mut IrMaps, specials: Specials) -> Liveness { users: @mut vec::from_elem(ir.num_live_nodes * ir.num_vars, invalid_users()), loop_scope: @mut ~[], - break_ln: @mut LinearMap::new(), - cont_ln: @mut LinearMap::new() + break_ln: @mut HashMap::new(), + cont_ln: @mut HashMap::new() } } diff --git a/src/librustc/middle/moves.rs b/src/librustc/middle/moves.rs index de52d3e6878e9..2f379ece5d374 100644 --- a/src/librustc/middle/moves.rs +++ b/src/librustc/middle/moves.rs @@ -215,7 +215,7 @@ use middle::typeck::method_map; use util::ppaux; use util::common::indenter; -use core::hashmap::{LinearSet, LinearMap}; +use core::hashmap::{HashSet, HashMap}; use core::vec; use syntax::ast::*; use syntax::ast_util; @@ -240,14 +240,14 @@ pub struct CaptureVar { mode: CaptureMode // How variable is being accessed } -pub type CaptureMap = @mut LinearMap; +pub type CaptureMap = @mut HashMap; -pub type MovesMap = @mut LinearSet; +pub type MovesMap = @mut HashSet; /** * For each variable which will be moved, links to the * expression */ -pub type VariableMovesMap = @mut LinearMap; +pub type VariableMovesMap = @mut HashMap; /** See the section Output on the module comment for explanation. */ pub struct MoveMaps { @@ -280,9 +280,9 @@ pub fn compute_moves(tcx: ty::ctxt, tcx: tcx, method_map: method_map, move_maps: MoveMaps { - moves_map: @mut LinearSet::new(), - variable_moves_map: @mut LinearMap::new(), - capture_map: @mut LinearMap::new() + moves_map: @mut HashSet::new(), + variable_moves_map: @mut HashMap::new(), + capture_map: @mut HashMap::new() } }; visit::visit_crate(*crate, visit_cx, visitor); diff --git a/src/librustc/middle/pat_util.rs b/src/librustc/middle/pat_util.rs index db3f5acf9d590..2e2048b7ae4cd 100644 --- a/src/librustc/middle/pat_util.rs +++ b/src/librustc/middle/pat_util.rs @@ -12,17 +12,17 @@ use core::prelude::*; use middle::resolve; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use syntax::ast::*; use syntax::ast_util::{path_to_ident, walk_pat}; use syntax::codemap::span; -pub type PatIdMap = LinearMap; +pub type PatIdMap = HashMap; // This is used because same-named variables in alternative patterns need to // use the node_id of their namesake in the first pattern. pub fn pat_id_map(dm: resolve::DefMap, pat: @pat) -> PatIdMap { - let mut map = LinearMap::new(); + let mut map = HashMap::new(); do pat_bindings(dm, pat) |_bm, p_id, _s, n| { map.insert(path_to_ident(n), p_id); }; diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index e6e1990717254..75eb8ef1a8580 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -26,7 +26,7 @@ use middle::ty::{region_variance, rv_covariant, rv_invariant}; use middle::ty::{rv_contravariant}; use middle::ty; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::vec; use syntax::ast_map; use syntax::codemap::span; @@ -46,7 +46,7 @@ Encodes the bounding lifetime for a given AST node: - Variables and bindings are mapped to the block in which they are declared. */ -pub type region_map = @mut LinearMap; +pub type region_map = @mut HashMap; pub struct ctxt { sess: Session, @@ -62,7 +62,7 @@ pub struct ctxt { // the condition in a while loop is always a parent. In those // cases, we add the node id of such an expression to this set so // that when we visit it we can view it as a parent. - root_exprs: @mut LinearSet, + root_exprs: @mut HashSet, // The parent scope is the innermost block, statement, call, or match // expression during the execution of which the current expression @@ -350,8 +350,8 @@ pub fn resolve_crate(sess: Session, -> region_map { let cx: ctxt = ctxt {sess: sess, def_map: def_map, - region_map: @mut LinearMap::new(), - root_exprs: @mut LinearSet::new(), + region_map: @mut HashMap::new(), + root_exprs: @mut HashSet::new(), parent: None}; let visitor = visit::mk_vt(@visit::Visitor { visit_block: resolve_block, @@ -387,7 +387,7 @@ pub fn resolve_crate(sess: Session, // a worklist. We can then process the worklist, propagating indirect // dependencies until a fixed point is reached. -pub type region_paramd_items = @mut LinearMap; +pub type region_paramd_items = @mut HashMap; #[deriving(Eq)] pub struct region_dep { @@ -395,7 +395,7 @@ pub struct region_dep { id: ast::node_id } -pub type dep_map = @mut LinearMap; +pub type dep_map = @mut HashMap; pub struct DetermineRpCtxt { sess: Session, @@ -790,8 +790,8 @@ pub fn determine_rp_in_crate(sess: Session, sess: sess, ast_map: ast_map, def_map: def_map, - region_paramd_items: @mut LinearMap::new(), - dep_map: @mut LinearMap::new(), + region_paramd_items: @mut HashMap::new(), + dep_map: @mut HashMap::new(), worklist: ~[], item_id: 0, anon_implies_rp: false, diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index c4a6584dd66a3..08542301e238f 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -77,10 +77,10 @@ use syntax::opt_vec::OptVec; use core::option::Some; use core::str::each_split_str; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; // Definition mapping -pub type DefMap = @mut LinearMap; +pub type DefMap = @mut HashMap; pub struct binding_info { span: span, @@ -88,7 +88,7 @@ pub struct binding_info { } // Map from the name in a pattern to its binding mode. -pub type BindingMap = LinearMap; +pub type BindingMap = HashMap; // Implementation resolution // @@ -109,11 +109,11 @@ pub struct Impl { } // Trait method resolution -pub type TraitMap = LinearMap; +pub type TraitMap = HashMap; // This is the replacement export map. It maps a module to all of the exports // within. -pub type ExportMap2 = @mut LinearMap; +pub type ExportMap2 = @mut HashMap; pub struct Export2 { name: @~str, // The name of the target. @@ -328,13 +328,13 @@ pub fn namespace_for_duplicate_checking_mode(mode: DuplicateCheckingMode) /// One local scope. pub struct Rib { - bindings: @mut LinearMap, + bindings: @mut HashMap, kind: RibKind, } pub fn Rib(kind: RibKind) -> Rib { Rib { - bindings: @mut LinearMap::new(), + bindings: @mut HashMap::new(), kind: kind } } @@ -450,12 +450,12 @@ pub struct Module { def_id: Option, kind: ModuleKind, - children: @mut LinearMap, + children: @mut HashMap, imports: @mut ~[@ImportDirective], // The external module children of this node that were declared with // `extern mod`. - external_module_children: @mut LinearMap, + external_module_children: @mut HashMap, // The anonymous children of this node. Anonymous children are pseudo- // modules that are implicitly created around items contained within @@ -472,10 +472,10 @@ pub struct Module { // There will be an anonymous module created around `g` with the ID of the // entry block for `f`. - anonymous_children: @mut LinearMap, + anonymous_children: @mut HashMap, // The status of resolving each import in this module. - import_resolutions: @mut LinearMap, + import_resolutions: @mut HashMap, // The number of unresolved globs that this module exports. glob_count: uint, @@ -492,11 +492,11 @@ pub fn Module(parent_link: ParentLink, parent_link: parent_link, def_id: def_id, kind: kind, - children: @mut LinearMap::new(), + children: @mut HashMap::new(), imports: @mut ~[], - external_module_children: @mut LinearMap::new(), - anonymous_children: @mut LinearMap::new(), - import_resolutions: @mut LinearMap::new(), + external_module_children: @mut HashMap::new(), + anonymous_children: @mut HashMap::new(), + import_resolutions: @mut HashMap::new(), glob_count: 0, resolved_import_count: 0 } @@ -707,7 +707,7 @@ pub fn NameBindings() -> NameBindings { /// Interns the names of the primitive types. pub struct PrimitiveTypeTable { - primitive_types: LinearMap, + primitive_types: HashMap, } pub impl PrimitiveTypeTable { @@ -720,7 +720,7 @@ pub impl PrimitiveTypeTable { pub fn PrimitiveTypeTable(intr: @ident_interner) -> PrimitiveTypeTable { let mut table = PrimitiveTypeTable { - primitive_types: LinearMap::new() + primitive_types: HashMap::new() }; table.intern(intr, @~"bool", ty_bool); @@ -775,8 +775,8 @@ pub fn Resolver(session: Session, graph_root: graph_root, - trait_info: LinearMap::new(), - structs: LinearSet::new(), + trait_info: HashMap::new(), + structs: HashSet::new(), unresolved_imports: 0, @@ -799,9 +799,9 @@ pub fn Resolver(session: Session, attr_main_fn: None, main_fns: ~[], - def_map: @mut LinearMap::new(), - export_map2: @mut LinearMap::new(), - trait_map: LinearMap::new(), + def_map: @mut HashMap::new(), + export_map2: @mut HashMap::new(), + trait_map: HashMap::new(), intr: session.intr() }; @@ -819,8 +819,8 @@ pub struct Resolver { graph_root: @mut NameBindings, - trait_info: LinearMap>, - structs: LinearSet, + trait_info: HashMap>, + structs: HashSet, // The number of imports that are currently unresolved. unresolved_imports: uint, @@ -1309,7 +1309,7 @@ pub impl Resolver { } // Add the names of all the methods to the trait info. - let mut method_names = LinearSet::new(); + let mut method_names = HashSet::new(); for methods.each |method| { let ty_m = trait_method_to_ty_method(method); @@ -1543,7 +1543,7 @@ pub impl Resolver { fn handle_external_def(@mut self, def: def, - modules: &mut LinearMap, + modules: &mut HashMap, child_name_bindings: @mut NameBindings, final_ident: &str, ident: ident, @@ -1623,7 +1623,7 @@ pub impl Resolver { // Nothing to do. } Some(method_names) => { - let mut interned_method_names = LinearSet::new(); + let mut interned_method_names = HashSet::new(); for method_names.each |method_data| { let (method_name, self_ty) = *method_data; debug!("(building reduced graph for \ @@ -1663,7 +1663,7 @@ pub impl Resolver { * crate. */ fn build_reduced_graph_for_external_crate(@mut self, root: @mut Module) { - let mut modules = LinearMap::new(); + let mut modules = HashMap::new(); // Create all the items reachable by paths. for each_path(self.session.cstore, root.def_id.get().crate) @@ -3906,7 +3906,7 @@ pub impl Resolver { } fn binding_mode_map(@mut self, pat: @pat) -> BindingMap { - let mut result = LinearMap::new(); + let mut result = HashMap::new(); do pat_bindings(self.def_map, pat) |binding_mode, _id, sp, path| { let ident = path_to_ident(path); result.insert(ident, @@ -3958,7 +3958,7 @@ pub impl Resolver { fn resolve_arm(@mut self, arm: &arm, visitor: ResolveVisitor) { self.value_ribs.push(@Rib(NormalRibKind)); - let bindings_list = @mut LinearMap::new(); + let bindings_list = @mut HashMap::new(); for arm.pats.each |pattern| { self.resolve_pattern(*pattern, RefutableMode, Immutable, Some(bindings_list), visitor); @@ -4078,7 +4078,7 @@ pub impl Resolver { mutability: Mutability, // Maps idents to the node ID for the (outermost) // pattern that binds them - bindings_list: Option<@mut LinearMap>, + bindings_list: Option<@mut HashMap>, visitor: ResolveVisitor) { let pat_id = pattern.id; do walk_pat(pattern) |pattern| { @@ -4282,7 +4282,7 @@ pub impl Resolver { } pat_struct(path, _, _) => { - let structs: &mut LinearSet = &mut self.structs; + let structs: &mut HashSet = &mut self.structs; match self.resolve_path(path, TypeNS, false, visitor) { Some(def_ty(class_id)) if structs.contains(&class_id) => { @@ -4791,7 +4791,7 @@ pub impl Resolver { expr_struct(path, _, _) => { // Resolve the path to the structure it goes to. - let structs: &mut LinearSet = &mut self.structs; + let structs: &mut HashSet = &mut self.structs; match self.resolve_path(path, TypeNS, false, visitor) { Some(def_ty(class_id)) | Some(def_struct(class_id)) if structs.contains(&class_id) => { diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index 1b5273dd3d7d3..32c9189ad2d7d 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -167,7 +167,7 @@ use middle::trans::type_of; use middle::ty; use util::common::indenter; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use syntax::ast; use syntax::ast::ident; use syntax::ast_util::path_to_ident; @@ -323,7 +323,7 @@ pub struct BindingInfo { ty: ty::t, } -pub type BindingsMap = LinearMap; +pub type BindingsMap = HashMap; pub struct ArmData<'self> { bodycx: block, @@ -1620,7 +1620,7 @@ pub fn trans_match_inner(scope_cx: block, // to an alloca() that will be the value for that local variable. // Note that we use the names because each binding will have many ids // from the various alternatives. - let mut bindings_map = LinearMap::new(); + let mut bindings_map = HashMap::new(); do pat_bindings(tcx.def_map, arm.pats[0]) |bm, p_id, _s, path| { let ident = path_to_ident(path); let variable_ty = node_id_type(bcx, p_id); diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 588690b055444..aa97c287b4c05 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -67,7 +67,7 @@ use util::ppaux::ty_to_str; use util::ppaux; use core::hash; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::int; use core::io; use core::libc::{c_uint, c_ulonglong}; @@ -1609,9 +1609,9 @@ pub fn new_fn_ctxt_w_id(ccx: @CrateContext, llself: None, personality: None, loop_ret: None, - llargs: @mut LinearMap::new(), - lllocals: @mut LinearMap::new(), - llupvars: @mut LinearMap::new(), + llargs: @mut HashMap::new(), + lllocals: @mut HashMap::new(), + llupvars: @mut HashMap::new(), id: id, impl_id: impl_id, param_substs: param_substs, @@ -2610,7 +2610,7 @@ pub fn p2i(ccx: @CrateContext, v: ValueRef) -> ValueRef { } } -pub fn declare_intrinsics(llmod: ModuleRef) -> LinearMap<~str, ValueRef> { +pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<~str, ValueRef> { let T_memcpy32_args: ~[TypeRef] = ~[T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()]; let T_memcpy64_args: ~[TypeRef] = @@ -2743,7 +2743,7 @@ pub fn declare_intrinsics(llmod: ModuleRef) -> LinearMap<~str, ValueRef> { let bswap64 = decl_cdecl_fn(llmod, ~"llvm.bswap.i64", T_fn(~[T_i64()], T_i64())); - let mut intrinsics = LinearMap::new(); + let mut intrinsics = HashMap::new(); intrinsics.insert(~"llvm.gcroot", gcroot); intrinsics.insert(~"llvm.gcread", gcread); intrinsics.insert(~"llvm.memcpy.p0i8.p0i8.i32", memcpy32); @@ -2804,7 +2804,7 @@ pub fn declare_intrinsics(llmod: ModuleRef) -> LinearMap<~str, ValueRef> { } pub fn declare_dbg_intrinsics(llmod: ModuleRef, - intrinsics: &mut LinearMap<~str, ValueRef>) { + intrinsics: &mut HashMap<~str, ValueRef>) { let declare = decl_cdecl_fn(llmod, ~"llvm.dbg.declare", T_fn(~[T_metadata(), T_metadata()], T_void())); @@ -3052,37 +3052,37 @@ pub fn trans_crate(sess: session::Session, llmod: llmod, td: td, tn: tn, - externs: @mut LinearMap::new(), + externs: @mut HashMap::new(), intrinsics: intrinsics, - item_vals: @mut LinearMap::new(), + item_vals: @mut HashMap::new(), exp_map2: emap2, reachable: reachable, - item_symbols: @mut LinearMap::new(), + item_symbols: @mut HashMap::new(), link_meta: link_meta, - enum_sizes: @mut LinearMap::new(), - discrims: @mut LinearMap::new(), - discrim_symbols: @mut LinearMap::new(), - tydescs: @mut LinearMap::new(), + enum_sizes: @mut HashMap::new(), + discrims: @mut HashMap::new(), + discrim_symbols: @mut HashMap::new(), + tydescs: @mut HashMap::new(), finished_tydescs: @mut false, - external: @mut LinearMap::new(), - monomorphized: @mut LinearMap::new(), - monomorphizing: @mut LinearMap::new(), - type_use_cache: @mut LinearMap::new(), - vtables: @mut LinearMap::new(), - const_cstr_cache: @mut LinearMap::new(), - const_globals: @mut LinearMap::new(), - const_values: @mut LinearMap::new(), - extern_const_values: @mut LinearMap::new(), - module_data: @mut LinearMap::new(), - lltypes: @mut LinearMap::new(), - llsizingtypes: @mut LinearMap::new(), - adt_reprs: @mut LinearMap::new(), + external: @mut HashMap::new(), + monomorphized: @mut HashMap::new(), + monomorphizing: @mut HashMap::new(), + type_use_cache: @mut HashMap::new(), + vtables: @mut HashMap::new(), + const_cstr_cache: @mut HashMap::new(), + const_globals: @mut HashMap::new(), + const_values: @mut HashMap::new(), + extern_const_values: @mut HashMap::new(), + module_data: @mut HashMap::new(), + lltypes: @mut HashMap::new(), + llsizingtypes: @mut HashMap::new(), + adt_reprs: @mut HashMap::new(), names: new_namegen(sess.parse_sess.interner), next_addrspace: new_addrspace_gen(), symbol_hasher: symbol_hasher, - type_hashcodes: @mut LinearMap::new(), - type_short_names: @mut LinearMap::new(), - all_llvm_symbols: @mut LinearSet::new(), + type_hashcodes: @mut HashMap::new(), + type_short_names: @mut HashMap::new(), + all_llvm_symbols: @mut HashSet::new(), tcx: tcx, maps: maps, stats: @mut Stats { @@ -3095,7 +3095,7 @@ pub fn trans_crate(sess: session::Session, n_inlines: 0u, n_closures: 0u, llvm_insn_ctxt: @mut ~[], - llvm_insns: @mut LinearMap::new(), + llvm_insns: @mut HashMap::new(), fn_times: @mut ~[] }, upcalls: upcall::declare_upcalls(targ_cfg, llmod), diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index 234812e66d9db..fa2be2f415f95 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -18,7 +18,7 @@ use syntax::codemap::span; use core::prelude::*; use core::cast; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::libc::{c_uint, c_ulonglong, c_char}; use core::libc; use core::option::Some; @@ -55,7 +55,7 @@ pub fn count_insn(cx: block, category: &str) { // Build version of path with cycles removed. // Pass 1: scan table mapping str -> rightmost pos. - let mut mm = LinearMap::new(); + let mut mm = HashMap::new(); let len = vec::len(*v); let mut i = 0u; while i < len { diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 04aca7b9dcdc4..f0c17a6f80d7b 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -45,7 +45,7 @@ use util::ppaux::{expr_repr, ty_to_str}; use core::cast; use core::hash; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::libc::{c_uint, c_longlong, c_ulonglong}; use core::ptr; use core::str; @@ -134,7 +134,7 @@ pub struct Stats { n_inlines: uint, n_closures: uint, llvm_insn_ctxt: @mut ~[~str], - llvm_insns: @mut LinearMap<~str, uint>, + llvm_insns: @mut HashMap<~str, uint>, fn_times: @mut ~[(~str, int)] // (ident, time) } @@ -156,7 +156,7 @@ pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res { } } -pub type ExternMap = @mut LinearMap<@str, ValueRef>; +pub type ExternMap = @mut HashMap<@str, ValueRef>; // Crate context. Every crate we compile has one of these. pub struct CrateContext { @@ -165,30 +165,30 @@ pub struct CrateContext { td: TargetData, tn: @TypeNames, externs: ExternMap, - intrinsics: LinearMap<~str, ValueRef>, - item_vals: @mut LinearMap, + intrinsics: HashMap<~str, ValueRef>, + item_vals: @mut HashMap, exp_map2: resolve::ExportMap2, reachable: reachable::map, - item_symbols: @mut LinearMap, + item_symbols: @mut HashMap, link_meta: LinkMeta, - enum_sizes: @mut LinearMap, - discrims: @mut LinearMap, - discrim_symbols: @mut LinearMap, - tydescs: @mut LinearMap, + enum_sizes: @mut HashMap, + discrims: @mut HashMap, + discrim_symbols: @mut HashMap, + tydescs: @mut HashMap, // Set when running emit_tydescs to enforce that no more tydescs are // created. finished_tydescs: @mut bool, // Track mapping of external ids to local items imported for inlining - external: @mut LinearMap>, + external: @mut HashMap>, // Cache instances of monomorphized functions - monomorphized: @mut LinearMap, - monomorphizing: @mut LinearMap, + monomorphized: @mut HashMap, + monomorphizing: @mut HashMap, // Cache computed type parameter uses (see type_use.rs) - type_use_cache: @mut LinearMap, + type_use_cache: @mut HashMap, // Cache generated vtables - vtables: @mut LinearMap, + vtables: @mut HashMap, // Cache of constant strings, - const_cstr_cache: @mut LinearMap<@~str, ValueRef>, + const_cstr_cache: @mut HashMap<@~str, ValueRef>, // Reverse-direction for const ptrs cast from globals. // Key is an int, cast from a ValueRef holding a *T, @@ -198,24 +198,24 @@ pub struct CrateContext { // when we ptrcast, and we have to ptrcast during translation // of a [T] const because we form a slice, a [*T,int] pair, not // a pointer to an LLVM array type. - const_globals: @mut LinearMap, + const_globals: @mut HashMap, // Cache of emitted const values - const_values: @mut LinearMap, + const_values: @mut HashMap, // Cache of external const values - extern_const_values: @mut LinearMap, + extern_const_values: @mut HashMap, - module_data: @mut LinearMap<~str, ValueRef>, - lltypes: @mut LinearMap, - llsizingtypes: @mut LinearMap, - adt_reprs: @mut LinearMap, + module_data: @mut HashMap<~str, ValueRef>, + lltypes: @mut HashMap, + llsizingtypes: @mut HashMap, + adt_reprs: @mut HashMap, names: namegen, next_addrspace: addrspace_gen, symbol_hasher: @hash::State, - type_hashcodes: @mut LinearMap, - type_short_names: @mut LinearMap, - all_llvm_symbols: @mut LinearSet<~str>, + type_hashcodes: @mut HashMap, + type_short_names: @mut HashMap, + all_llvm_symbols: @mut HashSet<~str>, tcx: ty::ctxt, maps: astencode::Maps, stats: @mut Stats, @@ -314,12 +314,12 @@ pub struct fn_ctxt_ { loop_ret: Option<(ValueRef, ValueRef)>, // Maps arguments to allocas created for them in llallocas. - llargs: @mut LinearMap, + llargs: @mut HashMap, // Maps the def_ids for local variables to the allocas created for // them in llallocas. - lllocals: @mut LinearMap, + lllocals: @mut HashMap, // Same as above, but for closure upvars - llupvars: @mut LinearMap, + llupvars: @mut HashMap, // The node_id of the function, or -1 if it doesn't correspond to // a user-defined function. diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 69a70c5a2fd51..277d529c8462f 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -20,7 +20,7 @@ use middle::trans; use middle::ty; use util::ppaux::ty_to_str; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::libc; use core::option; use core::sys; @@ -106,7 +106,7 @@ pub struct DebugContext { pub fn mk_ctxt(+crate: ~str, intr: @ident_interner) -> DebugContext { DebugContext { - llmetadata: @mut LinearMap::new(), + llmetadata: @mut HashMap::new(), names: new_namegen(intr), crate_file: crate } @@ -151,7 +151,7 @@ struct RetvalMetadata { id: ast::node_id } -type metadata_cache = @mut LinearMap; +type metadata_cache = @mut HashMap; enum debug_metadata { file_metadata(@Metadata), diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 616a25d3c164f..5afdd1b027188 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -153,7 +153,7 @@ use util::common::indenter; use util::ppaux::ty_to_str; use core::cast::transmute; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use syntax::print::pprust::{expr_to_str}; use syntax::ast; use syntax::codemap; @@ -1091,7 +1091,7 @@ pub fn trans_local_var(bcx: block, def: ast::def) -> Datum { }; fn take_local(bcx: block, - table: &LinearMap, + table: &HashMap, nid: ast::node_id) -> Datum { let (v, mode) = match table.find(&nid) { Some(&local_mem(v)) => (v, ByRef), diff --git a/src/librustc/middle/trans/reachable.rs b/src/librustc/middle/trans/reachable.rs index fd0eb9667098b..9f9323bf9f788 100644 --- a/src/librustc/middle/trans/reachable.rs +++ b/src/librustc/middle/trans/reachable.rs @@ -21,7 +21,7 @@ use middle::ty; use middle::typeck; use core::prelude::*; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use syntax::ast; use syntax::ast::*; use syntax::ast_util::def_id_of_def; @@ -30,18 +30,18 @@ use syntax::codemap; use syntax::print::pprust::expr_to_str; use syntax::{visit, ast_map}; -pub type map = @LinearSet; +pub type map = @HashSet; struct ctx<'self> { exp_map2: resolve::ExportMap2, tcx: ty::ctxt, method_map: typeck::method_map, - rmap: &'self mut LinearSet, + rmap: &'self mut HashSet, } pub fn find_reachable(crate_mod: &_mod, exp_map2: resolve::ExportMap2, tcx: ty::ctxt, method_map: typeck::method_map) -> map { - let mut rmap = LinearSet::new(); + let mut rmap = HashSet::new(); { let cx = ctx { exp_map2: exp_map2, @@ -96,7 +96,7 @@ fn traverse_public_mod(cx: ctx, mod_id: node_id, m: &_mod) { fn traverse_public_item(cx: ctx, item: @item) { // XXX: it shouldn't be necessary to do this - let rmap: &mut LinearSet = cx.rmap; + let rmap: &mut HashSet = cx.rmap; if rmap.contains(&item.id) { return; } rmap.insert(item.id); match item.node { @@ -154,7 +154,7 @@ fn mk_ty_visitor() -> visit::vt { fn traverse_ty<'a>(ty: @Ty, cx: ctx<'a>, v: visit::vt>) { // XXX: it shouldn't be necessary to do this - let rmap: &mut LinearSet = cx.rmap; + let rmap: &mut HashSet = cx.rmap; if rmap.contains(&ty.id) { return; } rmap.insert(ty.id); diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 2b00bd0c71246..30b933061e215 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -36,7 +36,7 @@ use core::result; use core::to_bytes; use core::uint; use core::vec; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use std::smallintmap::SmallIntMap; use syntax::ast::*; use syntax::ast_util::{is_local, local_def}; @@ -119,7 +119,7 @@ pub struct creader_cache_key { len: uint } -type creader_cache = @mut LinearMap; +type creader_cache = @mut HashMap; impl to_bytes::IterBytes for creader_cache_key { fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) { @@ -210,7 +210,7 @@ pub enum AutoRefKind { // This is a map from ID of each implementation to the method info and trait // method ID of each of the default methods belonging to the trait that that // implementation implements. -pub type ProvidedMethodsMap = @mut LinearMap; +pub type ProvidedMethodsMap = @mut HashMap; // Stores the method info and definition ID of the associated trait method for // each instantiation of each provided method. @@ -233,7 +233,7 @@ pub type ctxt = @ctxt_; struct ctxt_ { diag: @syntax::diagnostic::span_handler, - interner: @mut LinearMap, + interner: @mut HashMap, next_id: @mut uint, vecs_implicitly_copyable: bool, legacy_modes: bool, @@ -253,43 +253,43 @@ struct ctxt_ { // of this node. This only applies to nodes that refer to entities // parameterized by type parameters, such as generic fns, types, or // other items. - node_type_substs: @mut LinearMap, + node_type_substs: @mut HashMap, items: ast_map::map, - intrinsic_defs: @mut LinearMap, + intrinsic_defs: @mut HashMap, freevars: freevars::freevar_map, tcache: type_cache, rcache: creader_cache, ccache: constness_cache, - short_names_cache: @mut LinearMap, - needs_unwind_cleanup_cache: @mut LinearMap, - tc_cache: @mut LinearMap, - ast_ty_to_ty_cache: @mut LinearMap, - enum_var_cache: @mut LinearMap, - trait_method_cache: @mut LinearMap, - ty_param_bounds: @mut LinearMap, - inferred_modes: @mut LinearMap, - adjustments: @mut LinearMap, - normalized_cache: @mut LinearMap, + short_names_cache: @mut HashMap, + needs_unwind_cleanup_cache: @mut HashMap, + tc_cache: @mut HashMap, + ast_ty_to_ty_cache: @mut HashMap, + enum_var_cache: @mut HashMap, + trait_method_cache: @mut HashMap, + ty_param_bounds: @mut HashMap, + inferred_modes: @mut HashMap, + adjustments: @mut HashMap, + normalized_cache: @mut HashMap, lang_items: middle::lang_items::LanguageItems, // A mapping from an implementation ID to the method info and trait // method ID of the provided (a.k.a. default) methods in the traits that // that implementation implements. provided_methods: ProvidedMethodsMap, - provided_method_sources: @mut LinearMap, - supertraits: @mut LinearMap, + provided_method_sources: @mut HashMap, + supertraits: @mut HashMap, // A mapping from the def ID of an enum or struct type to the def ID // of the method that implements its destructor. If the type is not // present in this map, it does not have a destructor. This map is // populated during the coherence phase of typechecking. - destructor_for_type: @mut LinearMap, + destructor_for_type: @mut HashMap, // A method will be in this list if and only if it is a destructor. - destructors: @mut LinearSet, + destructors: @mut HashSet, // Maps a trait onto a mapping from self-ty to impl - trait_impls: @mut LinearMap> + trait_impls: @mut HashMap> } enum tbox_flag { @@ -771,18 +771,18 @@ pub struct ty_param_substs_and_ty { ty: ty::t } -type type_cache = @mut LinearMap; +type type_cache = @mut HashMap; -type constness_cache = @mut LinearMap; +type constness_cache = @mut HashMap; pub type node_type_table = @mut SmallIntMap; fn mk_rcache() -> creader_cache { - return @mut LinearMap::new(); + return @mut HashMap::new(); } -pub fn new_ty_hash() -> @mut LinearMap { - @mut LinearMap::new() +pub fn new_ty_hash() -> @mut HashMap { + @mut HashMap::new() } pub fn mk_ctxt(s: session::Session, @@ -809,7 +809,7 @@ pub fn mk_ctxt(s: session::Session, lint::vecs_implicitly_copyable) == allow; @ctxt_ { diag: s.diagnostic(), - interner: @mut LinearMap::new(), + interner: @mut HashMap::new(), next_id: @mut 0, vecs_implicitly_copyable: vecs_implicitly_copyable, legacy_modes: legacy_modes, @@ -819,30 +819,30 @@ pub fn mk_ctxt(s: session::Session, region_map: region_map, region_paramd_items: region_paramd_items, node_types: @mut SmallIntMap::new(), - node_type_substs: @mut LinearMap::new(), + node_type_substs: @mut HashMap::new(), items: amap, - intrinsic_defs: @mut LinearMap::new(), + intrinsic_defs: @mut HashMap::new(), freevars: freevars, - tcache: @mut LinearMap::new(), + tcache: @mut HashMap::new(), rcache: mk_rcache(), - ccache: @mut LinearMap::new(), + ccache: @mut HashMap::new(), short_names_cache: new_ty_hash(), needs_unwind_cleanup_cache: new_ty_hash(), - tc_cache: @mut LinearMap::new(), - ast_ty_to_ty_cache: @mut LinearMap::new(), - enum_var_cache: @mut LinearMap::new(), - trait_method_cache: @mut LinearMap::new(), - ty_param_bounds: @mut LinearMap::new(), - inferred_modes: @mut LinearMap::new(), - adjustments: @mut LinearMap::new(), + tc_cache: @mut HashMap::new(), + ast_ty_to_ty_cache: @mut HashMap::new(), + enum_var_cache: @mut HashMap::new(), + trait_method_cache: @mut HashMap::new(), + ty_param_bounds: @mut HashMap::new(), + inferred_modes: @mut HashMap::new(), + adjustments: @mut HashMap::new(), normalized_cache: new_ty_hash(), lang_items: lang_items, - provided_methods: @mut LinearMap::new(), - provided_method_sources: @mut LinearMap::new(), - supertraits: @mut LinearMap::new(), - destructor_for_type: @mut LinearMap::new(), - destructors: @mut LinearSet::new(), - trait_impls: @mut LinearMap::new() + provided_methods: @mut HashMap::new(), + provided_method_sources: @mut HashMap::new(), + supertraits: @mut HashMap::new(), + destructor_for_type: @mut HashMap::new(), + destructors: @mut HashSet::new(), + trait_impls: @mut HashMap::new() } } @@ -1620,7 +1620,7 @@ pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool { None => () } - let mut tycache = LinearSet::new(); + let mut tycache = HashSet::new(); let needs_unwind_cleanup = type_needs_unwind_cleanup_(cx, ty, &mut tycache, false); cx.needs_unwind_cleanup_cache.insert(ty, needs_unwind_cleanup); @@ -1628,7 +1628,7 @@ pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool { } fn type_needs_unwind_cleanup_(cx: ctxt, ty: t, - tycache: &mut LinearSet, + tycache: &mut HashSet, encountered_box: bool) -> bool { // Prevent infinite recursion @@ -1855,14 +1855,14 @@ pub fn type_contents(cx: ctxt, ty: t) -> TypeContents { None => {} } - let mut cache = LinearMap::new(); + let mut cache = HashMap::new(); let result = tc_ty(cx, ty, &mut cache); cx.tc_cache.insert(ty_id, result); return result; fn tc_ty(cx: ctxt, ty: t, - cache: &mut LinearMap) -> TypeContents + cache: &mut HashMap) -> TypeContents { // Subtle: Note that we are *not* using cx.tc_cache here but rather a // private cache for this walk. This is needed in the case of cyclic @@ -2054,7 +2054,7 @@ pub fn type_contents(cx: ctxt, ty: t) -> TypeContents { fn tc_mt(cx: ctxt, mt: mt, - cache: &mut LinearMap) -> TypeContents + cache: &mut HashMap) -> TypeContents { let mc = if mt.mutbl == m_mutbl {TC_MUTABLE} else {TC_NONE}; mc + tc_ty(cx, mt.ty, cache) @@ -3258,7 +3258,7 @@ pub fn occurs_check(tcx: ctxt, sp: span, vid: TyVid, rt: t) { // Maintains a little union-set tree for inferred modes. `canon()` returns // the current head value for `m0`. -fn canon(tbl: &mut LinearMap>, +fn canon(tbl: &mut HashMap>, +m0: ast::inferable) -> ast::inferable { match m0 { ast::infer(id) => { @@ -4286,7 +4286,7 @@ pub fn iter_bound_traits_and_supertraits(tcx: ctxt, } }; - let mut supertrait_map = LinearMap::new(); + let mut supertrait_map = HashMap::new(); let mut seen_def_ids = ~[]; let mut i = 0; let trait_ty_id = ty_to_def_id(bound_trait_ty).expect( diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index dd1dcbe67b94a..f2d0ef22970b4 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -18,7 +18,7 @@ use middle::typeck::check::{instantiate_path, lookup_def}; use middle::typeck::check::{structure_of, valid_range_bounds}; use middle::typeck::require_same_types; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::vec; use syntax::ast; use syntax::ast_util; @@ -228,7 +228,7 @@ pub fn check_pat_variant(pcx: pat_ctxt, pat: @ast::pat, path: @ast::path, /// `class_fields` describes the type of each field of the struct. /// `class_id` is the ID of the struct. /// `substitutions` are the type substitutions applied to this struct type -/// (e.g. K,V in LinearMap). +/// (e.g. K,V in HashMap). /// `etc` is true if the pattern said '...' and false otherwise. pub fn check_struct_pat_fields(pcx: pat_ctxt, span: span, @@ -241,13 +241,13 @@ pub fn check_struct_pat_fields(pcx: pat_ctxt, let tcx = pcx.fcx.ccx.tcx; // Index the class fields. - let mut field_map = LinearMap::new(); + let mut field_map = HashMap::new(); for class_fields.eachi |i, class_field| { field_map.insert(class_field.ident, i); } // Typecheck each field. - let mut found_fields = LinearSet::new(); + let mut found_fields = HashSet::new(); for fields.each |field| { match field_map.find(&field.ident) { Some(&index) => { diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 8f7e8478f8adb..3b01f0e839ab9 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -95,7 +95,7 @@ use middle::typeck::{method_self, method_static, method_trait, method_super}; use util::common::indenter; use util::ppaux::expr_repr; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use core::result; use core::uint; use core::vec; @@ -131,7 +131,7 @@ pub fn lookup( check_traits: CheckTraitsFlag, // Whether we check traits only. autoderef_receiver: AutoderefReceiverFlag) -> Option { - let mut impl_dups = LinearSet::new(); + let mut impl_dups = HashSet::new(); let lcx = LookupContext { fcx: fcx, expr: expr, @@ -159,7 +159,7 @@ pub struct LookupContext<'self> { callee_id: node_id, m_name: ast::ident, supplied_tps: &'self [ty::t], - impl_dups: &'self mut LinearSet, + impl_dups: &'self mut HashSet, inherent_candidates: @mut ~[Candidate], extension_candidates: @mut ~[Candidate], deref_args: check::DerefArgs, diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 1c144b294d219..eba207f978b6e 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -110,7 +110,7 @@ use util::common::{block_query, indenter, loop_query}; use util::ppaux::{bound_region_to_str, expr_repr, pat_repr}; use util::ppaux; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::ptr; use core::result::{Result, Ok, Err}; use core::result; @@ -158,12 +158,12 @@ pub struct SelfInfo { /// share the inherited fields. pub struct inherited { infcx: @mut infer::InferCtxt, - locals: @mut LinearMap, + locals: @mut HashMap, // Temporary tables: - node_types: @mut LinearMap, - node_type_substs: @mut LinearMap, - adjustments: @mut LinearMap, + node_types: @mut HashMap, + node_type_substs: @mut HashMap, + adjustments: @mut HashMap, method_map: method_map, vtable_map: vtable_map, } @@ -220,12 +220,12 @@ pub struct FnCtxt { pub fn blank_inherited(ccx: @mut CrateCtxt) -> @inherited { @inherited { infcx: infer::new_infer_ctxt(ccx.tcx), - locals: @mut LinearMap::new(), - node_types: @mut LinearMap::new(), - node_type_substs: @mut LinearMap::new(), - adjustments: @mut LinearMap::new(), - method_map: @mut LinearMap::new(), - vtable_map: @mut LinearMap::new(), + locals: @mut HashMap::new(), + node_types: @mut HashMap::new(), + node_type_substs: @mut HashMap::new(), + adjustments: @mut HashMap::new(), + method_map: @mut HashMap::new(), + vtable_map: @mut HashMap::new(), } } @@ -504,7 +504,7 @@ pub fn check_method(ccx: @mut CrateCtxt, pub fn check_no_duplicate_fields(tcx: ty::ctxt, fields: ~[(ast::ident, span)]) { - let mut field_names = LinearMap::new(); + let mut field_names = HashMap::new(); for fields.each |p| { let (id, sp) = *p; @@ -1761,7 +1761,7 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, check_completeness: bool) { let tcx = fcx.ccx.tcx; - let mut class_field_map = LinearMap::new(); + let mut class_field_map = HashMap::new(); let mut fields_found = 0; for field_types.each |field| { // XXX: Check visibility here. diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index ddce274c54207..51f54d21ec4af 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -28,7 +28,7 @@ use core::result::{Ok, Err}; use core::result; use core::uint; use core::vec; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use syntax::ast; use syntax::ast_util; use syntax::codemap::span; @@ -234,7 +234,7 @@ pub fn lookup_vtable(vcx: &VtableContext, _ => { let mut found = ~[]; - let mut impls_seen = LinearSet::new(); + let mut impls_seen = HashSet::new(); match vcx.ccx.coherence_info.extension_methods.find(&trait_id) { None => { diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index 9f4984e02a603..466cb8ed54f2b 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -53,7 +53,7 @@ use syntax::visit::{visit_mod}; use util::ppaux::ty_to_str; use core::result::Ok; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::uint; pub struct UniversalQuantificationResult { @@ -164,17 +164,17 @@ pub fn method_to_MethodInfo(ast_method: @method) -> @MethodInfo { pub struct CoherenceInfo { // Contains implementations of methods that are inherent to a type. // Methods in these implementations don't need to be exported. - inherent_methods: @mut LinearMap, + inherent_methods: @mut HashMap, // Contains implementations of methods associated with a trait. For these, // the associated trait must be imported at the call site. - extension_methods: @mut LinearMap, + extension_methods: @mut HashMap, } pub fn CoherenceInfo() -> CoherenceInfo { CoherenceInfo { - inherent_methods: @mut LinearMap::new(), - extension_methods: @mut LinearMap::new(), + inherent_methods: @mut HashMap::new(), + extension_methods: @mut HashMap::new(), } } @@ -183,7 +183,7 @@ pub fn CoherenceChecker(crate_context: @mut CrateCtxt) -> CoherenceChecker { crate_context: crate_context, inference_context: new_infer_ctxt(crate_context.tcx), - base_type_def_ids: @mut LinearMap::new(), + base_type_def_ids: @mut HashMap::new(), } } @@ -194,7 +194,7 @@ pub struct CoherenceChecker { // A mapping from implementations to the corresponding base type // definition ID. - base_type_def_ids: @mut LinearMap, + base_type_def_ids: @mut HashMap, } pub impl CoherenceChecker { @@ -471,7 +471,7 @@ pub impl CoherenceChecker { ty_to_str(self.crate_context.tcx, self_t)); match self.crate_context.tcx.trait_impls.find(&trait_t) { None => { - let m = @mut LinearMap::new(); + let m = @mut HashMap::new(); m.insert(self_t, the_impl); self.crate_context.tcx.trait_impls.insert(trait_t, m); } @@ -501,7 +501,7 @@ pub impl CoherenceChecker { f: &fn(x: &ty::method) -> bool) { // Make a list of all the names of the provided methods. // XXX: This is horrible. - let mut provided_method_idents = LinearSet::new(); + let mut provided_method_idents = HashSet::new(); let tcx = self.crate_context.tcx; for ty::provided_trait_methods(tcx, trait_did).each |ident| { provided_method_idents.insert(*ident); @@ -705,7 +705,7 @@ pub impl CoherenceChecker { let tcx = self.crate_context.tcx; - let mut provided_names = LinearSet::new(); + let mut provided_names = HashSet::new(); // Implemented methods for uint::range(0, all_methods.len()) |i| { provided_names.insert(all_methods[i].ident); @@ -812,7 +812,7 @@ pub impl CoherenceChecker { // External crate handling - fn add_impls_for_module(&self, impls_seen: &mut LinearSet, + fn add_impls_for_module(&self, impls_seen: &mut HashSet, crate_store: @mut CStore, module_def_id: def_id) { let implementations = get_impls_for_mod(crate_store, @@ -931,7 +931,7 @@ pub impl CoherenceChecker { // Adds implementations and traits from external crates to the coherence // info. fn add_external_crates(&self) { - let mut impls_seen = LinearSet::new(); + let mut impls_seen = HashSet::new(); let crate_store = self.crate_context.tcx.sess.cstore; do iter_crate_data(crate_store) |crate_number, _crate_metadata| { diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index b190a98f8cd08..98d12bea6a429 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -548,7 +548,7 @@ use util::common::indenter; use util::ppaux::note_and_explain_region; use core::cell::{Cell, empty_cell}; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::result::{Err, Ok}; use core::to_bytes; use core::uint; @@ -600,12 +600,12 @@ enum CombineMapType { Lub, Glb } -type CombineMap = LinearMap; +type CombineMap = HashMap; pub struct RegionVarBindings { tcx: ty::ctxt, var_spans: ~[span], - constraints: LinearMap, + constraints: HashMap, lubs: CombineMap, glbs: CombineMap, skolemization_count: uint, @@ -632,9 +632,9 @@ pub fn RegionVarBindings(tcx: ty::ctxt) -> RegionVarBindings { tcx: tcx, var_spans: ~[], values: empty_cell(), - constraints: LinearMap::new(), - lubs: LinearMap::new(), - glbs: LinearMap::new(), + constraints: HashMap::new(), + lubs: HashMap::new(), + glbs: HashMap::new(), skolemization_count: 0, bound_count: 0, undo_log: ~[] @@ -1194,7 +1194,7 @@ struct SpannedRegion { span: span, } -type TwoRegionsMap = LinearSet; +type TwoRegionsMap = HashSet; pub impl RegionVarBindings { fn infer_variable_values(&mut self) -> ~[GraphNodeValue] { @@ -1423,7 +1423,7 @@ pub impl RegionVarBindings { &mut self, graph: &Graph) -> ~[GraphNodeValue] { - let mut dup_map = LinearSet::new(); + let mut dup_map = HashSet::new(); graph.nodes.mapi(|idx, node| { match node.value { Value(_) => { @@ -1598,7 +1598,7 @@ pub impl RegionVarBindings { orig_node_idx: RegionVid, dir: Direction) -> ~[SpannedRegion] { - let mut set = LinearSet::new(); + let mut set = HashSet::new(); let mut stack = ~[orig_node_idx]; set.insert(orig_node_idx.to_uint()); let mut result = ~[]; diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 1a0a1fceb52a8..d829b0d2a0d51 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -55,7 +55,7 @@ use middle::ty; use util::common::time; use util::ppaux; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::result; use core::vec; use std::list::List; @@ -129,7 +129,7 @@ pub struct method_map_entry { // maps from an expression id that corresponds to a method call to the details // of the method to be invoked -pub type method_map = @mut LinearMap; +pub type method_map = @mut HashMap; // Resolutions for bounds of all parameters, left to right, for a given path. pub type vtable_res = @~[vtable_origin]; @@ -170,7 +170,7 @@ pub impl vtable_origin { } } -pub type vtable_map = @mut LinearMap; +pub type vtable_map = @mut HashMap; pub struct CrateCtxt { // A mapping from method call sites to traits that have that method. @@ -342,8 +342,8 @@ pub fn check_crate(tcx: ty::ctxt, let time_passes = tcx.sess.time_passes(); let ccx = @mut CrateCtxt { trait_map: trait_map, - method_map: @mut LinearMap::new(), - vtable_map: @mut LinearMap::new(), + method_map: @mut HashMap::new(), + vtable_map: @mut HashMap::new(), coherence_info: @coherence::CoherenceInfo(), tcx: tcx }; diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 98eff8b50d14d..30152c2284574 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -14,7 +14,7 @@ use syntax::ast; use syntax::codemap::{span}; use syntax::visit; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use core::str; use std; @@ -114,7 +114,7 @@ pub fn pluralize(n: uint, +s: ~str) -> ~str { } // A set of node IDs (used to keep track of which node IDs are for statements) -pub type stmt_set = @mut LinearSet; +pub type stmt_set = @mut HashSet; // // Local Variables: diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index 2f1d25425ec2b..bf1301868af54 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -28,7 +28,7 @@ extern mod syntax(vers = "0.6"); use core::*; use core::container::Map; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::io::WriterUtil; use rustc::driver::{driver, session}; use rustc::metadata::filesearch; @@ -253,7 +253,7 @@ impl PackageScript { struct Ctx { cfgs: ~[~str], json: bool, - dep_cache: @mut LinearMap<~str, bool> + dep_cache: @mut HashMap<~str, bool> } impl Ctx { @@ -483,14 +483,14 @@ impl Ctx { if self.json { match PackageScript::parse(&os::getcwd()) { result::Ok(script) => { - let mut map = ~LinearMap::new(); + let mut map = ~HashMap::new(); map.insert(~"id", json::String(script.id)); map.insert(~"name", json::String(script.name)); map.insert(~"vers", json::String(script.vers.to_str())); map.insert(~"deps", json::List(do script.deps.map |&dep| { let (url, target) = dep; - let mut inner = ~LinearMap::new(); + let mut inner = ~HashMap::new(); inner.insert(~"url", json::String(url)); @@ -921,7 +921,7 @@ pub fn main() { Ctx { cfgs: cfgs, json: json, - dep_cache: @mut LinearMap::new() + dep_cache: @mut HashMap::new() }.run(cmd, args); } diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 15546e96653d8..9d3751c3de297 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -10,7 +10,7 @@ use core::*; use core::hash::Streaming; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use rustc::driver::{driver, session}; use rustc::metadata::filesearch; use std::getopts::groups::getopts; @@ -337,7 +337,7 @@ fn _add_pkg(packages: ~[json::Json], pkg: &Package) -> ~[json::Json] { } } - let mut map = ~LinearMap::new(); + let mut map = ~HashMap::new(); map.insert(~"id", json::String(pkg.id)); map.insert(~"vers", json::String(pkg.vers.to_str())); diff --git a/src/libstd/json.rs b/src/libstd/json.rs index 1b79708e59017..f426b74736ad3 100644 --- a/src/libstd/json.rs +++ b/src/libstd/json.rs @@ -16,7 +16,7 @@ use core::prelude::*; use core::io::{WriterUtil, ReaderUtil}; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use serialize::Encodable; use serialize; @@ -33,7 +33,7 @@ pub enum Json { } pub type List = ~[Json]; -pub type Object = LinearMap<~str, Json>; +pub type Object = HashMap<~str, Json>; #[deriving(Eq)] pub struct Error { @@ -677,7 +677,7 @@ priv impl Parser { self.bump(); self.parse_whitespace(); - let mut values = ~LinearMap::new(); + let mut values = ~HashMap::new(); if self.ch == '}' { self.bump(); @@ -1127,9 +1127,9 @@ impl ToJson for ~[A] { fn to_json(&self) -> Json { List(self.map(|elt| elt.to_json())) } } -impl ToJson for LinearMap<~str, A> { +impl ToJson for HashMap<~str, A> { fn to_json(&self) -> Json { - let mut d = LinearMap::new(); + let mut d = HashMap::new(); for self.each |&(key, value)| { d.insert(copy *key, value.to_json()); } @@ -1161,7 +1161,7 @@ mod tests { use super::*; use core::prelude::*; - use core::hashmap::LinearMap; + use core::hashmap::HashMap; use std::serialize::Decodable; @@ -1190,7 +1190,7 @@ mod tests { } fn mk_object(items: &[(~str, Json)]) -> Json { - let mut d = ~LinearMap::new(); + let mut d = ~HashMap::new(); for items.each |item| { match *item { @@ -1755,7 +1755,7 @@ mod tests { fn test_decode_map() { let s = ~"{\"a\": \"Dog\", \"b\": [\"Frog\", \"Henry\", 349]}"; let decoder = Decoder(from_str(s).unwrap()); - let mut map: LinearMap<~str, Animal> = Decodable::decode(&decoder); + let mut map: HashMap<~str, Animal> = Decodable::decode(&decoder); assert_eq!(map.pop(&~"a"), Some(Dog)); assert_eq!(map.pop(&~"b"), Some(Frog(~"Henry", 349))); diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index b32a9841ac6c1..81598f17aed16 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -17,7 +17,7 @@ use core::from_str::FromStr; use core::io::{Reader, ReaderUtil}; use core::io; use core::prelude::*; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::str; use core::to_bytes::IterBytes; use core::to_bytes; @@ -212,7 +212,7 @@ fn encode_plus(s: &str) -> ~str { /** * Encode a hashmap to the 'application/x-www-form-urlencoded' media type. */ -pub fn encode_form_urlencoded(m: &LinearMap<~str, ~[~str]>) -> ~str { +pub fn encode_form_urlencoded(m: &HashMap<~str, ~[~str]>) -> ~str { let mut out = ~""; let mut first = true; @@ -238,9 +238,9 @@ pub fn encode_form_urlencoded(m: &LinearMap<~str, ~[~str]>) -> ~str { * Decode a string encoded with the 'application/x-www-form-urlencoded' media * type into a hashmap. */ -pub fn decode_form_urlencoded(s: &[u8]) -> LinearMap<~str, ~[~str]> { +pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<~str, ~[~str]> { do io::with_bytes_reader(s) |rdr| { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); let mut key = ~""; let mut value = ~""; let mut parsing_key = true; @@ -818,7 +818,7 @@ mod tests { use net_url::*; - use core::hashmap::LinearMap; + use core::hashmap::HashMap; #[test] pub fn test_url_parse() { @@ -1053,18 +1053,18 @@ mod tests { #[test] pub fn test_encode_form_urlencoded() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); assert!(encode_form_urlencoded(&m) == ~""); m.insert(~"", ~[]); m.insert(~"foo", ~[]); assert!(encode_form_urlencoded(&m) == ~""); - let mut m = LinearMap::new(); + let mut m = HashMap::new(); m.insert(~"foo", ~[~"bar", ~"123"]); assert!(encode_form_urlencoded(&m) == ~"foo=bar&foo=123"); - let mut m = LinearMap::new(); + let mut m = HashMap::new(); m.insert(~"foo bar", ~[~"abc", ~"12 = 34"]); assert!(encode_form_urlencoded(&m) == ~"foo+bar=abc&foo+bar=12+%3D+34"); diff --git a/src/libstd/serialize.rs b/src/libstd/serialize.rs index 88ae58ee01b4c..e1ab59fb2b3ae 100644 --- a/src/libstd/serialize.rs +++ b/src/libstd/serialize.rs @@ -17,7 +17,7 @@ Core encoding and decoding interfaces. #[forbid(non_camel_case_types)]; use core::prelude::*; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::trie::{TrieMap, TrieSet}; use deque::Deque; use dlist::DList; @@ -591,7 +591,7 @@ impl< E: Encoder, K: Encodable + Hash + IterBytes + Eq, V: Encodable -> Encodable for LinearMap { +> Encodable for HashMap { fn encode(&self, e: &E) { do e.emit_map(self.len()) { let mut i = 0; @@ -608,10 +608,10 @@ impl< D: Decoder, K: Decodable + Hash + IterBytes + Eq, V: Decodable -> Decodable for LinearMap { - fn decode(d: &D) -> LinearMap { +> Decodable for HashMap { + fn decode(d: &D) -> HashMap { do d.read_map |len| { - let mut map = LinearMap::with_capacity(len); + let mut map = HashMap::with_capacity(len); for uint::range(0, len) |i| { let key = d.read_map_elt_key(i, || Decodable::decode(d)); let val = d.read_map_elt_val(i, || Decodable::decode(d)); @@ -625,7 +625,7 @@ impl< impl< S: Encoder, T: Encodable + Hash + IterBytes + Eq -> Encodable for LinearSet { +> Encodable for HashSet { fn encode(&self, s: &S) { do s.emit_seq(self.len()) { let mut i = 0; @@ -640,10 +640,10 @@ impl< impl< D: Decoder, T: Decodable + Hash + IterBytes + Eq -> Decodable for LinearSet { - fn decode(d: &D) -> LinearSet { +> Decodable for HashSet { + fn decode(d: &D) -> HashSet { do d.read_seq |len| { - let mut set = LinearSet::with_capacity(len); + let mut set = HashSet::with_capacity(len); for uint::range(0, len) |i| { set.insert(d.read_seq_elt(i, || Decodable::decode(d))); } diff --git a/src/libstd/workcache.rs b/src/libstd/workcache.rs index 6886d5d630e19..3e494d0236e97 100644 --- a/src/libstd/workcache.rs +++ b/src/libstd/workcache.rs @@ -24,7 +24,7 @@ use core::pipes::recv; use core::prelude::*; use core::result; use core::run; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::task; use core::to_bytes; @@ -136,10 +136,10 @@ pub impl WorkKey { } } -struct WorkMap(LinearMap); +struct WorkMap(HashMap); impl WorkMap { - fn new() -> WorkMap { WorkMap(LinearMap::new()) } + fn new() -> WorkMap { WorkMap(HashMap::new()) } } impl Encodable for WorkMap { @@ -166,7 +166,7 @@ impl Decodable for WorkMap { struct Database { db_filename: Path, - db_cache: LinearMap<~str, ~str>, + db_cache: HashMap<~str, ~str>, db_dirty: bool } @@ -212,7 +212,7 @@ struct Context { db: @mut Database, logger: @mut Logger, cfg: @json::Object, - freshness: LinearMap<~str,@fn(&str,&str)->bool> + freshness: HashMap<~str,@fn(&str,&str)->bool> } struct Prep { @@ -267,7 +267,7 @@ pub impl Context { db: db, logger: lg, cfg: cfg, - freshness: LinearMap::new() + freshness: HashMap::new() } } @@ -411,10 +411,10 @@ fn test() { use core::io::WriterUtil; let db = @mut Database { db_filename: Path("db.json"), - db_cache: LinearMap::new(), + db_cache: HashMap::new(), db_dirty: false }; let lg = @mut Logger { a: () }; - let cfg = @LinearMap::new(); + let cfg = @HashMap::new(); let cx = @Context::new(db, lg, cfg); let w:Work<~str> = do cx.prep("test1") |prep| { let pth = Path("foo.c"); diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 04d7cbdca0c3d..147d8227b81ea 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -23,7 +23,7 @@ use print::pprust; use visit; use core::cmp; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::str; use core::vec; @@ -104,7 +104,7 @@ pub enum ast_node { node_struct_ctor(@struct_def, @item, @path), } -pub type map = @mut LinearMap; +pub type map = @mut HashMap; pub struct Ctx { map: map, @@ -134,7 +134,7 @@ pub fn mk_ast_map_visitor() -> vt { pub fn map_crate(diag: @span_handler, c: crate) -> map { let cx = @mut Ctx { - map: @mut LinearMap::new(), + map: @mut HashMap::new(), path: ~[], local_id: 0u, diag: diag, diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 71e2faa93f569..5063a0381e782 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -20,7 +20,7 @@ use diagnostic::span_handler; use parse::comments::{doc_comment_style, strip_doc_comment_decoration}; use core::vec; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use std; /* Constructors */ @@ -333,7 +333,7 @@ pub fn find_inline_attr(attrs: &[ast::attribute]) -> inline_attr { pub fn require_unique_names(diagnostic: @span_handler, metas: &[@ast::meta_item]) { - let mut set = LinearSet::new(); + let mut set = HashSet::new(); for metas.each |meta| { let name = get_meta_item_name(*meta); diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index cae56267f5eb3..92f0c7c7679a9 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -20,7 +20,7 @@ use parse; use parse::token; use core::vec; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; // new-style macro! tt code: // @@ -125,7 +125,7 @@ pub fn syntax_expander_table() -> SyntaxEnv { fn builtin_item_tt(f: SyntaxExpanderTTItemFun) -> @Transformer { @SE(IdentTT(SyntaxExpanderTTItem{expander: f, span: None})) } - let mut syntax_expanders = LinearMap::new(); + let mut syntax_expanders = HashMap::new(); // NB identifier starts with space, and can't conflict with legal idents syntax_expanders.insert(@~" block", @ScopeMacros(true)); @@ -430,8 +430,8 @@ pub fn get_exprs_from_tts(cx: @ext_ctxt, tts: &[ast::token_tree]) // a transformer env is either a base map or a map on top // of another chain. pub enum MapChain { - BaseMapChain(~LinearMap), - ConsMapChain(~LinearMap,@mut MapChain) + BaseMapChain(~HashMap), + ConsMapChain(~HashMap,@mut MapChain) } @@ -439,13 +439,13 @@ pub enum MapChain { impl MapChain{ // Constructor. I don't think we need a zero-arg one. - fn new(+init: ~LinearMap) -> @mut MapChain { + fn new(+init: ~HashMap) -> @mut MapChain { @mut BaseMapChain(init) } // add a new frame to the environment (functionally) fn push_frame (@mut self) -> @mut MapChain { - @mut ConsMapChain(~LinearMap::new() ,self) + @mut ConsMapChain(~HashMap::new() ,self) } // no need for pop, it'll just be functional. @@ -454,7 +454,7 @@ impl MapChain{ // ugh: can't get this to compile with mut because of the // lack of flow sensitivity. - fn get_map(&self) -> &'self LinearMap { + fn get_map(&self) -> &'self HashMap { match *self { BaseMapChain (~ref map) => map, ConsMapChain (~ref map,_) => map @@ -509,10 +509,10 @@ impl MapChain{ #[cfg(test)] mod test { use super::MapChain; - use core::hashmap::LinearMap; + use core::hashmap::HashMap; #[test] fn testenv () { - let mut a = LinearMap::new(); + let mut a = HashMap::new(); a.insert (@~"abc",@15); let m = MapChain::new(~a); m.insert (@~"def",@16); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index fcb0c76a2c78a..afb7e04a53204 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -20,7 +20,7 @@ use parse::token::{Token, EOF, to_str, nonterminal}; use parse::token; use core::prelude::*; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; /* This is an Earley-like parser, without support for in-grammar nonterminals, only by calling out to the main rust parser for named nonterminals (which it @@ -186,9 +186,9 @@ pub enum named_match { pub type earley_item = ~MatcherPos; pub fn nameize(p_s: @mut ParseSess, ms: ~[matcher], res: ~[@named_match]) - -> LinearMap { + -> HashMap { fn n_rec(p_s: @mut ParseSess, m: matcher, res: ~[@named_match], - ret_val: &mut LinearMap) { + ret_val: &mut HashMap) { match m { codemap::spanned {node: match_tok(_), _} => (), codemap::spanned {node: match_seq(ref more_ms, _, _, _, _), _} => { @@ -207,13 +207,13 @@ pub fn nameize(p_s: @mut ParseSess, ms: ~[matcher], res: ~[@named_match]) } } } - let mut ret_val = LinearMap::new(); + let mut ret_val = HashMap::new(); for ms.each() |m| { n_rec(p_s, *m, res, &mut ret_val) } return ret_val; } pub enum parse_result { - success(LinearMap), + success(HashMap), failure(codemap::span, ~str), error(codemap::span, ~str) } @@ -223,7 +223,7 @@ pub fn parse_or_else( +cfg: ast::crate_cfg, rdr: @reader, ms: ~[matcher] -) -> LinearMap { +) -> HashMap { match parse(sess, cfg, rdr, ms) { success(m) => m, failure(sp, str) => sess.span_diagnostic.span_fatal(sp, str), diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index de0b4c0799fba..0a74b6a94354a 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -18,7 +18,7 @@ use ext::tt::macro_parser::{named_match, matched_seq, matched_nonterminal}; use parse::token::{EOF, INTERPOLATED, IDENT, Token, nt_ident, ident_interner}; use parse::lexer::TokenAndSpan; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::option; use core::vec; @@ -39,7 +39,7 @@ pub struct TtReader { // the unzipped tree: cur: @mut TtFrame, /* for MBE-style macro transcription */ - interpolations: LinearMap, + interpolations: HashMap, repeat_idx: ~[uint], repeat_len: ~[uint], /* cached: */ @@ -52,7 +52,7 @@ pub struct TtReader { * should) be none. */ pub fn new_tt_reader(sp_diag: @span_handler, itr: @ident_interner, - interp: Option>, + interp: Option>, +src: ~[ast::token_tree]) -> @mut TtReader { let r = @mut TtReader { @@ -66,7 +66,7 @@ pub fn new_tt_reader(sp_diag: @span_handler, up: option::None }, interpolations: match interp { /* just a convienience */ - None => LinearMap::new(), + None => HashMap::new(), Some(x) => x }, repeat_idx: ~[], diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 1b845ad1dd9d4..f36d8f42f2ac6 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -94,7 +94,7 @@ use opt_vec::OptVec; use core::either::Either; use core::either; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use core::vec; #[deriving(Eq)] @@ -243,7 +243,7 @@ pub fn Parser(sess: @mut ParseSess, keywords: token::keyword_table(), strict_keywords: token::strict_keyword_table(), reserved_keywords: token::reserved_keyword_table(), - obsolete_set: @mut LinearSet::new(), + obsolete_set: @mut HashSet::new(), mod_path_stack: @mut ~[], } } @@ -262,12 +262,12 @@ pub struct Parser { quote_depth: @mut uint, // not (yet) related to the quasiquoter reader: @reader, interner: @token::ident_interner, - keywords: LinearSet<~str>, - strict_keywords: LinearSet<~str>, - reserved_keywords: LinearSet<~str>, + keywords: HashSet<~str>, + strict_keywords: HashSet<~str>, + reserved_keywords: HashSet<~str>, /// The set of seen errors about obsolete syntax. Used to suppress /// extra detail when the same error is seen twice - obsolete_set: @mut LinearSet, + obsolete_set: @mut HashSet, /// Used to determine the path to externally loaded source files mod_path_stack: @mut ~[~str], diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index ff10b6070e66d..713a6e8947554 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -18,7 +18,7 @@ use util::interner; use core::cast; use core::char; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use core::str; use core::task; @@ -458,8 +458,8 @@ pub fn mk_fake_ident_interner() -> @ident_interner { * appear as identifiers at all. Reserved keywords are not used anywhere in * the language and may not appear as identifiers. */ -pub fn keyword_table() -> LinearSet<~str> { - let mut keywords = LinearSet::new(); +pub fn keyword_table() -> HashSet<~str> { + let mut keywords = HashSet::new(); let mut tmp = temporary_keyword_table(); let mut strict = strict_keyword_table(); let mut reserved = reserved_keyword_table(); @@ -471,8 +471,8 @@ pub fn keyword_table() -> LinearSet<~str> { } /// Keywords that may be used as identifiers -pub fn temporary_keyword_table() -> LinearSet<~str> { - let mut words = LinearSet::new(); +pub fn temporary_keyword_table() -> HashSet<~str> { + let mut words = HashSet::new(); let keys = ~[ ~"self", ~"static", ]; @@ -483,8 +483,8 @@ pub fn temporary_keyword_table() -> LinearSet<~str> { } /// Full keywords. May not appear anywhere else. -pub fn strict_keyword_table() -> LinearSet<~str> { - let mut words = LinearSet::new(); +pub fn strict_keyword_table() -> HashSet<~str> { + let mut words = HashSet::new(); let keys = ~[ ~"as", ~"break", @@ -509,8 +509,8 @@ pub fn strict_keyword_table() -> LinearSet<~str> { return words; } -pub fn reserved_keyword_table() -> LinearSet<~str> { - let mut words = LinearSet::new(); +pub fn reserved_keyword_table() -> HashSet<~str> { + let mut words = HashSet::new(); let keys = ~[ ~"be" ]; diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index dd4044036ef84..4108871d0089c 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -13,10 +13,10 @@ // type, and vice versa. use core::prelude::*; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; pub struct Interner { - priv map: @mut LinearMap, + priv map: @mut HashMap, priv vect: @mut ~[T], } @@ -24,7 +24,7 @@ pub struct Interner { pub impl Interner { fn new() -> Interner { Interner { - map: @mut LinearMap::new(), + map: @mut HashMap::new(), vect: @mut ~[], } } diff --git a/src/test/auxiliary/issue-2631-a.rs b/src/test/auxiliary/issue-2631-a.rs index eded285eef117..bee754f5bd448 100644 --- a/src/test/auxiliary/issue-2631-a.rs +++ b/src/test/auxiliary/issue-2631-a.rs @@ -13,9 +13,9 @@ extern mod std; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; -pub type header_map = LinearMap<~str, @mut ~[@~str]>; +pub type header_map = HashMap<~str, @mut ~[@~str]>; // the unused ty param is necessary so this gets monomorphized pub fn request(req: &header_map) { diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index c30c38e92f724..8a8962fb9d637 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -13,7 +13,7 @@ extern mod std; use core::io; use std::time; use std::treemap::TreeMap; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::trie::TrieMap; fn timed(label: &str, f: &fn()) { @@ -102,7 +102,7 @@ fn main() { { let rng = core::rand::seeded_rng([1, 1, 1, 1, 1, 1, 1]); - let mut set = LinearSet::new(); + let mut set = HashSet::new(); while set.len() != n_keys { let next = rng.next() as uint; if set.insert(next) { @@ -131,21 +131,21 @@ fn main() { vector(&mut map, n_keys, rand); } - io::println("\nLinearMap:"); + io::println("\nHashMap:"); { - let mut map = LinearMap::new::(); + let mut map = HashMap::new::(); ascending(&mut map, n_keys); } { - let mut map = LinearMap::new::(); + let mut map = HashMap::new::(); descending(&mut map, n_keys); } { io::println(" Random integers:"); - let mut map = LinearMap::new::(); + let mut map = HashMap::new::(); vector(&mut map, n_keys, rand); } diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index 2fcd82eefe61b..5f8f13896fb95 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -9,7 +9,7 @@ // except according to those terms. extern mod std; -use core::hashmap::LinearSet; +use core::hashmap::HashSet; use std::bitv::BitvSet; use std::treemap::TreeSet; use core::io::WriterUtil; @@ -158,9 +158,9 @@ fn main() { { let rng = rand::seeded_rng(seed); let mut results = empty_results(); - results.bench_int(rng, num_keys, max, || LinearSet::new::()); - results.bench_str(rng, num_keys, || LinearSet::new::<~str>()); - write_results("core::hashmap::LinearSet", &results); + results.bench_int(rng, num_keys, max, || HashSet::new::()); + results.bench_str(rng, num_keys, || HashSet::new::<~str>()); + write_results("core::hashmap::HashSet", &results); } { diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index 397c08228995c..396ea08136281 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -24,7 +24,7 @@ use std::arc; use std::time; use std::deque::Deque; use std::par; -use core::hashmap::{LinearMap, LinearSet}; +use core::hashmap::{HashMap, HashSet}; use core::io::WriterUtil; use core::int::abs; use core::rand::RngUtil; @@ -81,7 +81,7 @@ fn make_edges(scale: uint, edgefactor: uint) -> ~[(node_id, node_id)] { fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph { let mut graph = do vec::from_fn(N) |_i| { - LinearSet::new() + HashSet::new() }; do vec::each(edges) |e| { @@ -104,7 +104,7 @@ fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph { } fn gen_search_keys(graph: &[~[node_id]], n: uint) -> ~[node_id] { - let mut keys = LinearSet::new(); + let mut keys = HashSet::new(); let r = rand::Rng(); while keys.len() < n { diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index f608c71000b29..6ba1caa0d1e1a 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -15,13 +15,13 @@ extern mod std; use std::sort; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use core::io::ReaderUtil; use core::comm::{stream, Port, Chan}; use core::cmp::Ord; // given a map, print a sorted version of it -fn sort_and_fmt(mm: &LinearMap<~[u8], uint>, total: uint) -> ~str { +fn sort_and_fmt(mm: &HashMap<~[u8], uint>, total: uint) -> ~str { fn pct(xx: uint, yy: uint) -> float { return (xx as float) * 100f / (yy as float); } @@ -67,7 +67,7 @@ fn sort_and_fmt(mm: &LinearMap<~[u8], uint>, total: uint) -> ~str { } // given a map, search for the frequency of a pattern -fn find(mm: &LinearMap<~[u8], uint>, key: ~str) -> uint { +fn find(mm: &HashMap<~[u8], uint>, key: ~str) -> uint { match mm.find(&str::to_bytes(str::to_lower(key))) { option::None => { return 0u; } option::Some(&num) => { return num; } @@ -75,7 +75,7 @@ fn find(mm: &LinearMap<~[u8], uint>, key: ~str) -> uint { } // given a map, increment the counter for a key -fn update_freq(mm: &mut LinearMap<~[u8], uint>, key: &[u8]) { +fn update_freq(mm: &mut HashMap<~[u8], uint>, key: &[u8]) { let key = vec::slice(key, 0, key.len()).to_vec(); let newval = match mm.pop(&key) { Some(v) => v + 1, @@ -103,7 +103,7 @@ fn windows_with_carry(bb: &[u8], nn: uint, fn make_sequence_processor(sz: uint, from_parent: comm::Port<~[u8]>, to_parent: comm::Chan<~str>) { - let mut freqs: LinearMap<~[u8], uint> = LinearMap::new(); + let mut freqs: HashMap<~[u8], uint> = HashMap::new(); let mut carry: ~[u8] = ~[]; let mut total: uint = 0u; diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 65d99858d1d36..f5d1661fa52bd 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -25,7 +25,7 @@ // writes pbm image to output path use core::io::WriterUtil; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; struct cmplx { re: f64, @@ -125,7 +125,7 @@ fn writer(path: ~str, pport: comm::Port, size: uint) }; cout.write_line("P4"); cout.write_line(fmt!("%u %u", size, size)); - let mut lines: LinearMap = LinearMap::new(); + let mut lines: HashMap = HashMap::new(); let mut done = 0_u; let mut i = 0_u; while i < size { diff --git a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs index b3cf314edd001..bda659aa7b97e 100644 --- a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs +++ b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs @@ -10,11 +10,11 @@ //buggy.rs -use core::hashmap::LinearMap; +use core::hashmap::HashMap; fn main() { - let mut buggy_map :LinearMap = - LinearMap::new::(); + let mut buggy_map :HashMap = + HashMap::new::(); buggy_map.insert(42, &*~1); //~ ERROR illegal borrow // but it is ok if we use a temporary diff --git a/src/test/compile-fail/borrowck-insert-during-each.rs b/src/test/compile-fail/borrowck-insert-during-each.rs index 1420a67556cad..17c0efe225e4d 100644 --- a/src/test/compile-fail/borrowck-insert-during-each.rs +++ b/src/test/compile-fail/borrowck-insert-during-each.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::LinearSet; +use core::hashmap::HashSet; struct Foo { - n: LinearSet, + n: HashSet, } pub impl Foo { @@ -29,6 +29,6 @@ fn bar(f: &mut Foo) { } fn main() { - let mut f = Foo { n: LinearSet::new() }; + let mut f = Foo { n: HashSet::new() }; bar(&mut f); } diff --git a/src/test/compile-fail/for-loop-decl.rs b/src/test/compile-fail/for-loop-decl.rs index c7c1ea4821307..de28d72677728 100644 --- a/src/test/compile-fail/for-loop-decl.rs +++ b/src/test/compile-fail/for-loop-decl.rs @@ -11,10 +11,10 @@ // error-pattern: mismatched types extern mod std; use std::bitv; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; struct FnInfo { - vars: LinearMap + vars: HashMap } struct VarInfo { diff --git a/src/test/compile-fail/map-types.rs b/src/test/compile-fail/map-types.rs index 00efdbbf75acc..ebc5b015d2752 100644 --- a/src/test/compile-fail/map-types.rs +++ b/src/test/compile-fail/map-types.rs @@ -9,12 +9,12 @@ // except according to those terms. use core::container::Map; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; // Test that trait types printed in error msgs include the type arguments. fn main() { - let x: @Map<~str, ~str> = @LinearMap::new::<~str, ~str>() as + let x: @Map<~str, ~str> = @HashMap::new::<~str, ~str>() as @Map<~str, ~str>; let y: @Map = @x; //~^ ERROR mismatched types: expected `@core::container::Map` diff --git a/src/test/run-fail/unwind-misc-1.rs b/src/test/run-fail/unwind-misc-1.rs index 5ec4beb364d89..7e3318f865228 100644 --- a/src/test/run-fail/unwind-misc-1.rs +++ b/src/test/run-fail/unwind-misc-1.rs @@ -14,7 +14,7 @@ fn main() { let count = @mut 0u; - let mut map = core::hashmap::LinearMap::new(); + let mut map = core::hashmap::HashMap::new(); let mut arr = ~[]; for uint::range(0u, 10u) |i| { arr += ~[@~"key stuff"]; diff --git a/src/test/run-pass/explicit-self-generic.rs b/src/test/run-pass/explicit-self-generic.rs index fdf733d0314bc..1a2a8cab3032c 100644 --- a/src/test/run-pass/explicit-self-generic.rs +++ b/src/test/run-pass/explicit-self-generic.rs @@ -20,17 +20,17 @@ type EqFn = ~fn(K, K) -> bool; struct LM { resize_at: uint, size: uint } -enum LinearMap { - LinearMap_(LM) +enum HashMap { + HashMap_(LM) } -fn linear_map() -> LinearMap { - LinearMap_(LM{ +fn linear_map() -> HashMap { + HashMap_(LM{ resize_at: 32, size: 0}) } -pub impl LinearMap { +pub impl HashMap { fn len(&mut self) -> uint { self.size } diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index 415f753a562e2..910708b710602 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -19,7 +19,7 @@ pub fn map(filename: ~str, emit: map_reduce::putter) { emit(filename, ~"1"); } mod map_reduce { - use core::hashmap::LinearMap; + use core::hashmap::HashMap; use core::comm::*; pub type putter = @fn(~str, ~str); @@ -37,9 +37,9 @@ mod map_reduce { } fn map_task(ctrl: SharedChan, input: ~str) { - let intermediates = @mut LinearMap::new(); + let intermediates = @mut HashMap::new(); - fn emit(im: &mut LinearMap<~str, int>, ctrl: SharedChan, key: ~str, + fn emit(im: &mut HashMap<~str, int>, ctrl: SharedChan, key: ~str, _val: ~str) { if im.contains_key(&key) { return; @@ -65,9 +65,9 @@ mod map_reduce { // This task becomes the master control task. It spawns others // to do the rest. - let mut reducers: LinearMap<~str, int>; + let mut reducers: HashMap<~str, int>; - reducers = LinearMap::new(); + reducers = HashMap::new(); start_mappers(ctrl_chan, inputs.clone()); diff --git a/src/test/run-pass/issue-1696.rs b/src/test/run-pass/issue-1696.rs index 401920789c098..5b40d0abff818 100644 --- a/src/test/run-pass/issue-1696.rs +++ b/src/test/run-pass/issue-1696.rs @@ -10,10 +10,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::LinearMap; +use core::hashmap::HashMap; pub fn main() { - let mut m = LinearMap::new(); + let mut m = HashMap::new(); m.insert(str::to_bytes(~"foo"), str::to_bytes(~"bar")); error!(m); } diff --git a/src/test/run-pass/issue-2631-b.rs b/src/test/run-pass/issue-2631-b.rs index 42452d3a2bb0f..f6e40fa247d5e 100644 --- a/src/test/run-pass/issue-2631-b.rs +++ b/src/test/run-pass/issue-2631-b.rs @@ -14,11 +14,11 @@ extern mod req; use req::*; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; pub fn main() { let v = ~[@~"hi"]; - let mut m: req::header_map = LinearMap::new(); + let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @mut v); request::(&m); } diff --git a/src/test/run-pass/issue-2804-2.rs b/src/test/run-pass/issue-2804-2.rs index 4f0930deaaef1..b25e4095b185e 100644 --- a/src/test/run-pass/issue-2804-2.rs +++ b/src/test/run-pass/issue-2804-2.rs @@ -13,9 +13,9 @@ // Minimized version of issue-2804.rs. Both check that callee IDs don't // clobber the previous node ID in a macro expr -use core::hashmap::LinearMap; +use core::hashmap::HashMap; -fn add_interfaces(managed_ip: ~str, device: LinearMap<~str, int>) { +fn add_interfaces(managed_ip: ~str, device: HashMap<~str, int>) { error!("%s, %?", managed_ip, device.get(&~"interfaces")); } diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index a1c5f4a6757dc..4614c26fa5fc8 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -11,7 +11,7 @@ // except according to those terms. extern mod std; -use core::hashmap::LinearMap; +use core::hashmap::HashMap; use std::json; enum object { @@ -58,7 +58,7 @@ fn add_interface(store: int, managed_ip: ~str, data: std::json::Json) -> (~str, } } -fn add_interfaces(store: int, managed_ip: ~str, device: LinearMap<~str, std::json::Json>) -> ~[(~str, object)] +fn add_interfaces(store: int, managed_ip: ~str, device: HashMap<~str, std::json::Json>) -> ~[(~str, object)] { match device.get(&~"interfaces") { diff --git a/src/test/run-pass/issue-3026.rs b/src/test/run-pass/issue-3026.rs index 9665113bc0cee..16e9b4753f830 100644 --- a/src/test/run-pass/issue-3026.rs +++ b/src/test/run-pass/issue-3026.rs @@ -10,10 +10,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::LinearMap; +use core::hashmap::HashMap; pub fn main() { - let mut buggy_map: LinearMap = LinearMap::new::(); + let mut buggy_map: HashMap = HashMap::new::(); let x = ~1; buggy_map.insert(42, &*x); } diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index a73f130e88981..334831fea4d03 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -29,7 +29,7 @@ fn check_strs(actual: &str, expected: &str) -> bool #[test] fn tester() { - let mut table = core::hashmap::LinearMap(); + let mut table = core::hashmap::HashMap(); table.insert(@~"one", 1); table.insert(@~"two", 2); assert!(check_strs(table.to_str(), ~"xxx")); // not sure what expected should be diff --git a/src/test/run-pass/issue-4092.rs b/src/test/run-pass/issue-4092.rs index 8cda78840b341..e129e0a88687a 100644 --- a/src/test/run-pass/issue-4092.rs +++ b/src/test/run-pass/issue-4092.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::LinearMap; +use core::hashmap::HashMap; pub fn main() { - let mut x = LinearMap::new(); + let mut x = HashMap::new(); x.insert((@"abc", 0), 0); } From c16919d3a8e83e4c72668f6ad89d48f6ba8341f6 Mon Sep 17 00:00:00 2001 From: Matthijs Hofstra Date: Tue, 2 Apr 2013 23:15:04 +0200 Subject: [PATCH 17/35] Removing mut fields from vec.rs, at_vec.rs, str.rs, unstable.rs, and cell.rs. --- src/libcore/at_vec.rs | 4 ++-- src/libcore/cell.rs | 12 +++++------- src/libcore/str.rs | 4 ++-- src/libcore/unstable.rs | 14 +++++++------- src/libcore/vec.rs | 12 ++++++------ 5 files changed, 22 insertions(+), 24 deletions(-) diff --git a/src/libcore/at_vec.rs b/src/libcore/at_vec.rs index 3e3d70530dd35..38a663dc24504 100644 --- a/src/libcore/at_vec.rs +++ b/src/libcore/at_vec.rs @@ -208,7 +208,7 @@ pub mod raw { */ #[inline(always)] pub unsafe fn set_len(v: @[T], new_len: uint) { - let repr: **VecRepr = ::cast::reinterpret_cast(&addr_of(&v)); + let repr: **mut VecRepr = ::cast::reinterpret_cast(&addr_of(&v)); (**repr).unboxed.fill = new_len * sys::size_of::(); } @@ -226,7 +226,7 @@ pub mod raw { #[inline(always)] // really pretty please pub unsafe fn push_fast(v: &mut @[T], initval: T) { - let repr: **VecRepr = ::cast::reinterpret_cast(&v); + let repr: **mut VecRepr = ::cast::reinterpret_cast(&v); let fill = (**repr).unboxed.fill; (**repr).unboxed.fill += sys::size_of::(); let p = addr_of(&((**repr).unboxed.data)); diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 28b3ebe4484c7..c2983e033e537 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -10,7 +10,7 @@ //! A mutable, nullable memory location -use cast::transmute; +use cast::transmute_mut; use prelude::*; /* @@ -20,16 +20,12 @@ Similar to a mutable option type, but friendlier. */ pub struct Cell { - mut value: Option + value: Option } impl cmp::Eq for Cell { fn eq(&self, other: &Cell) -> bool { - unsafe { - let frozen_self: &Option = transmute(&mut self.value); - let frozen_other: &Option = transmute(&mut other.value); - frozen_self == frozen_other - } + (self.value) == (other.value) } fn ne(&self, other: &Cell) -> bool { !self.eq(other) } } @@ -46,6 +42,7 @@ pub fn empty_cell() -> Cell { pub impl Cell { /// Yields the value, failing if the cell is empty. fn take(&self) -> T { + let mut self = unsafe { transmute_mut(self) }; if self.is_empty() { fail!(~"attempt to take an empty cell"); } @@ -57,6 +54,7 @@ pub impl Cell { /// Returns the value, failing if the cell is full. fn put_back(&self, value: T) { + let mut self = unsafe { transmute_mut(self) }; if !self.is_empty() { fail!(~"attempt to put a value back into a full cell"); } diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 67fd37996cda0..18ea169d96e5c 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -2274,8 +2274,8 @@ pub mod raw { /// Sets the length of the string and adds the null terminator pub unsafe fn set_len(v: &mut ~str, new_len: uint) { - let v: **vec::raw::VecRepr = cast::transmute(v); - let repr: *vec::raw::VecRepr = *v; + let v: **mut vec::raw::VecRepr = cast::transmute(v); + let repr: *mut vec::raw::VecRepr = *v; (*repr).unboxed.fill = new_len + 1u; let null = ptr::mut_offset(cast::transmute(&((*repr).unboxed.data)), new_len); diff --git a/src/libcore/unstable.rs b/src/libcore/unstable.rs index 665a3e1b6b6d4..e2b57a8dd3eda 100644 --- a/src/libcore/unstable.rs +++ b/src/libcore/unstable.rs @@ -106,13 +106,13 @@ fn compare_and_swap(address: &mut int, oldval: int, newval: int) -> bool { ****************************************************************************/ struct ArcData { - mut count: libc::intptr_t, + count: libc::intptr_t, // FIXME(#3224) should be able to make this non-option to save memory - mut data: Option, + data: Option, } struct ArcDestruct { - mut data: *libc::c_void, + data: *libc::c_void, } #[unsafe_destructor] @@ -122,7 +122,7 @@ impl Drop for ArcDestruct{ do task::unkillable { let data: ~ArcData = cast::reinterpret_cast(&self.data); let new_count = - intrinsics::atomic_xsub(&mut data.count, 1) - 1; + intrinsics::atomic_xsub(cast::transmute_mut(&data.count), 1) - 1; assert!(new_count >= 0); if new_count == 0 { // drop glue takes over. @@ -186,7 +186,7 @@ pub unsafe fn clone_shared_mutable_state(rc: &SharedMutableState) -> SharedMutableState { unsafe { let ptr: ~ArcData = cast::reinterpret_cast(&(*rc).data); - let new_count = intrinsics::atomic_xadd(&mut ptr.count, 1) + 1; + let new_count = intrinsics::atomic_xadd(cast::transmute_mut(&ptr.count), 1) + 1; assert!(new_count >= 2); cast::forget(ptr); } @@ -252,7 +252,7 @@ pub impl LittleLock { } } -struct ExData { lock: LittleLock, mut failed: bool, mut data: T, } +struct ExData { lock: LittleLock, failed: bool, data: T, } /** * An arc over mutable data that is protected by a lock. For library use only. */ @@ -260,7 +260,7 @@ pub struct Exclusive { x: SharedMutableState> } pub fn exclusive(user_data: T) -> Exclusive { let data = ExData { - lock: LittleLock(), mut failed: false, mut data: user_data + lock: LittleLock(), failed: false, data: user_data }; Exclusive { x: unsafe { shared_mutable_state(data) } } } diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 0ac86ac280d06..21e876ea0fb02 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -633,7 +633,7 @@ pub fn push(v: &mut ~[T], initval: T) { // This doesn't bother to make sure we have space. #[inline(always)] // really pretty please unsafe fn push_fast(v: &mut ~[T], initval: T) { - let repr: **raw::VecRepr = ::cast::transmute(v); + let repr: **mut raw::VecRepr = ::cast::transmute(v); let fill = (**repr).unboxed.fill; (**repr).unboxed.fill += sys::nonzero_size_of::(); let p = addr_of(&((**repr).unboxed.data)); @@ -2148,8 +2148,8 @@ pub unsafe fn from_buf(ptr: *T, elts: uint) -> ~[T] { /// The internal 'unboxed' representation of a vector pub struct UnboxedVecRepr { - mut fill: uint, - mut alloc: uint, + fill: uint, + alloc: uint, data: u8 } @@ -2171,8 +2171,8 @@ pub mod raw { } pub struct SliceRepr { - mut data: *u8, - mut len: uint + data: *u8, + len: uint } /** @@ -2184,7 +2184,7 @@ pub mod raw { */ #[inline(always)] pub unsafe fn set_len(v: &mut ~[T], new_len: uint) { - let repr: **VecRepr = ::cast::transmute(v); + let repr: **mut VecRepr = ::cast::transmute(v); (**repr).unboxed.fill = new_len * sys::nonzero_size_of::(); } From 397a47852849ac2e286508f2315e695f5d8168cf Mon Sep 17 00:00:00 2001 From: Matthijs Hofstra Date: Wed, 3 Apr 2013 18:28:44 +0200 Subject: [PATCH 18/35] Unstable didn't need transmute_mut after all. --- src/libcore/unstable.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/unstable.rs b/src/libcore/unstable.rs index e2b57a8dd3eda..c717c1692a8c5 100644 --- a/src/libcore/unstable.rs +++ b/src/libcore/unstable.rs @@ -120,9 +120,9 @@ impl Drop for ArcDestruct{ fn finalize(&self) { unsafe { do task::unkillable { - let data: ~ArcData = cast::reinterpret_cast(&self.data); + let mut data: ~ArcData = cast::reinterpret_cast(&self.data); let new_count = - intrinsics::atomic_xsub(cast::transmute_mut(&data.count), 1) - 1; + intrinsics::atomic_xsub(&mut data.count, 1) - 1; assert!(new_count >= 0); if new_count == 0 { // drop glue takes over. @@ -185,8 +185,8 @@ pub unsafe fn get_shared_immutable_state<'a,T:Owned>( pub unsafe fn clone_shared_mutable_state(rc: &SharedMutableState) -> SharedMutableState { unsafe { - let ptr: ~ArcData = cast::reinterpret_cast(&(*rc).data); - let new_count = intrinsics::atomic_xadd(cast::transmute_mut(&ptr.count), 1) + 1; + let mut ptr: ~ArcData = cast::reinterpret_cast(&(*rc).data); + let new_count = intrinsics::atomic_xadd(&mut ptr.count, 1) + 1; assert!(new_count >= 2); cast::forget(ptr); } From c4d2b7999a12b8c9111ae1d897c476c052ddc05a Mon Sep 17 00:00:00 2001 From: Jack Moffitt Date: Wed, 3 Apr 2013 11:03:41 -0600 Subject: [PATCH 19/35] Add Clone derivation for std::net::url types. --- src/libstd/net_url.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index d23784953ef99..9174e99e40a0a 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -25,7 +25,7 @@ use core::to_str::ToStr; use core::to_str; use core::uint; -#[deriving(Eq)] +#[deriving(Clone, Eq)] struct Url { scheme: ~str, user: Option, @@ -36,7 +36,7 @@ struct Url { fragment: Option<~str> } -#[deriving(Eq)] +#[deriving(Clone, Eq)] struct UserInfo { user: ~str, pass: Option<~str> @@ -398,7 +398,7 @@ pub fn get_scheme(rawurl: &str) -> Result<(~str, ~str), ~str> { return Err(~"url: Scheme must be terminated with a colon."); } -#[deriving(Eq)] +#[deriving(Clone, Eq)] enum Input { Digit, // all digits Hex, // digits and letters a-f From d79b22474cf9b02d0d3a0a78f8c6ef279770c36b Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 3 Apr 2013 11:40:23 -0700 Subject: [PATCH 20/35] Add information about logging macros to the tutorial. Closes #5699. --- doc/rust.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/doc/rust.md b/doc/rust.md index c6dba96267679..eceb308b4f6a5 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -3251,6 +3251,28 @@ of runtime logging modules follows. * `::rt::backtrace` Log a backtrace on task failure * `::rt::callback` Unused +#### Logging Expressions + +Rust provides several macros to log information. Here's a simple Rust program +that demonstrates all four of them: + +```rust +fn main() { + error!("This is an error log") + warn!("This is a warn log") + info!("this is an info log") + debug!("This is a dubug log") +} +``` + +These four log levels correspond to levels 1-4, as controlled by `RUST_LOG`: + +```bash +$ RUST_LOG=rust=3 ./rust +rust: ~"\"This is na error log\"" +rust: ~"\"This is a warn log\"" +rust: ~"\"this is an info log\"" +``` # Appendix: Rationales and design tradeoffs From 34b2336dd08c7d8eeb8a79cb9c06c89ccb1639cb Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 3 Apr 2013 11:54:49 -0700 Subject: [PATCH 21/35] Fix compiletest on windows --- src/compiletest/procsrv.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index a96f36f5e702c..ca10aa0da7d45 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -26,7 +26,7 @@ fn target_env(lib_path: ~str, prog: ~str) -> ~[(~str,~str)] { // Make sure we include the aux directory in the path assert!(prog.ends_with(~".exe")); - let aux_path = prog.slice(0u, prog.len() - 4u) + ~".libaux"; + let aux_path = prog.slice(0u, prog.len() - 4u).to_owned() + ~".libaux"; env = do vec::map(env) |pair| { let (k,v) = *pair; From 3044f5e2b64ae8c0ee726ec42f3d2a3faca9e77e Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 3 Apr 2013 12:44:41 -0700 Subject: [PATCH 22/35] typo fix: na -> an --- doc/rust.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/rust.md b/doc/rust.md index eceb308b4f6a5..1cb8b7053b5ce 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -3269,7 +3269,7 @@ These four log levels correspond to levels 1-4, as controlled by `RUST_LOG`: ```bash $ RUST_LOG=rust=3 ./rust -rust: ~"\"This is na error log\"" +rust: ~"\"This is an error log\"" rust: ~"\"This is a warn log\"" rust: ~"\"this is an info log\"" ``` From 8dd5a70ef4bf951c4cdecef3ef9a27ddfc6a03fb Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Wed, 3 Apr 2013 18:52:28 -0300 Subject: [PATCH 23/35] Update tut. to not sound like I missed a section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sentence "Remember that `(float, float)` is a tuple of two floats" sounds like you've already read a section on tuples, but that section comes later. Changing it to "Assuming that ..." makes it more about taking the writer's word that the syntax is how tuples are defined. --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/tutorial.md b/doc/tutorial.md index 42b0d5a585aee..92e2f55b02d12 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -495,7 +495,7 @@ omitted. A powerful application of pattern matching is *destructuring*: matching in order to bind names to the contents of data -types. Remember that `(float, float)` is a tuple of two floats: +types. Assuming that `(float, float)` is a tuple of two floats: ~~~~ fn angle(vector: (float, float)) -> float { From a7f0bfbda65d6ac2494d2270a96f45570dfb552e Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 3 Apr 2013 16:59:13 -0700 Subject: [PATCH 24/35] One more typo: dubug -> debug --- doc/rust.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/rust.md b/doc/rust.md index 1cb8b7053b5ce..d70fcded5e76a 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -3261,7 +3261,7 @@ fn main() { error!("This is an error log") warn!("This is a warn log") info!("this is an info log") - debug!("This is a dubug log") + debug!("This is a debug log") } ``` From e2c7a4def2730e33babf26ff834abe32a1de9a04 Mon Sep 17 00:00:00 2001 From: Anthony Juckel Date: Wed, 3 Apr 2013 19:10:09 -0500 Subject: [PATCH 25/35] Simple typo fix --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/tutorial.md b/doc/tutorial.md index 42b0d5a585aee..499eb7e387880 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -988,7 +988,7 @@ custom destructors. # Boxes -Many modern languages represent values as as pointers to heap memory by +Many modern languages represent values as pointers to heap memory by default. In contrast, Rust, like C and C++, represents such types directly. Another way to say this is that aggregate data in Rust are *unboxed*. This means that if you `let x = Point { x: 1f, y: 1f };`, you are creating a struct From f06404860ce4c083461483b41879ae40f08a3fc2 Mon Sep 17 00:00:00 2001 From: ILyoan Date: Wed, 3 Apr 2013 14:42:50 +0900 Subject: [PATCH 26/35] Remove a android hack --- src/librustc/middle/trans/base.rs | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index aa97c287b4c05..5c5f78aeab6f5 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -2284,25 +2284,14 @@ pub fn create_main_wrapper(ccx: @CrateContext, let opaque_crate_map = llvm::LLVMBuildPointerCast( bld, crate_map, T_ptr(T_i8()), noname()); - if *ccx.sess.building_library { - ~[ - retptr, - C_null(T_opaque_box_ptr(ccx)), - opaque_rust_main, - llvm::LLVMConstInt(T_i32(), 0u as c_ulonglong, False), - llvm::LLVMConstInt(T_i32(), 0u as c_ulonglong, False), - opaque_crate_map - ] - } else { - ~[ - retptr, - C_null(T_opaque_box_ptr(ccx)), - opaque_rust_main, - llvm::LLVMGetParam(llfn, 0 as c_uint), - llvm::LLVMGetParam(llfn, 1 as c_uint), - opaque_crate_map - ] - } + ~[ + retptr, + C_null(T_opaque_box_ptr(ccx)), + opaque_rust_main, + llvm::LLVMGetParam(llfn, 0 as c_uint), + llvm::LLVMGetParam(llfn, 1 as c_uint), + opaque_crate_map + ] }; unsafe { From fac0d9d89bd55eccda2549d59b5355afdcaa783f Mon Sep 17 00:00:00 2001 From: ILyoan Date: Wed, 3 Apr 2013 15:44:26 +0900 Subject: [PATCH 27/35] Decides main name by target --- src/librustc/middle/trans/base.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 5c5f78aeab6f5..a8fe60ba68ee8 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -2243,17 +2243,17 @@ pub fn create_main_wrapper(ccx: @CrateContext, } fn create_entry_fn(ccx: @CrateContext, rust_main: ValueRef) { - #[cfg(windows)] - fn main_name() -> ~str { return ~"WinMain@16"; } - #[cfg(unix)] - fn main_name() -> ~str { return ~"main"; } let llfty = T_fn(~[ccx.int_type, T_ptr(T_ptr(T_i8()))], ccx.int_type); // FIXME #4404 android JNI hacks let llfn = if *ccx.sess.building_library { decl_cdecl_fn(ccx.llmod, ~"amain", llfty) } else { - decl_cdecl_fn(ccx.llmod, main_name(), llfty) + let main_name = match ccx.sess.targ_cfg.os { + session::os_win32 => ~"WinMain@16", + _ => ~"main", + }; + decl_cdecl_fn(ccx.llmod, main_name, llfty) }; let llbb = str::as_c_str(~"top", |buf| { unsafe { From 53232f7acfa651f14c7ed5afd5ec44da9f82eb08 Mon Sep 17 00:00:00 2001 From: ILyoan Date: Thu, 4 Apr 2013 11:16:26 +0900 Subject: [PATCH 28/35] Fix fileinput test fail --- src/libstd/fileinput.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/fileinput.rs b/src/libstd/fileinput.rs index df733425f3ef0..4ac3e0b174729 100644 --- a/src/libstd/fileinput.rs +++ b/src/libstd/fileinput.rs @@ -534,7 +534,7 @@ mod test { fn test_empty_files() { let filenames = pathify(vec::from_fn( 3, - |i| fmt!("tmp/lib-fileinput-test-next-file-%u.tmp", i)),true); + |i| fmt!("tmp/lib-fileinput-test-empty-files-%u.tmp", i)),true); make_file(filenames[0].get_ref(), ~[~"1", ~"2"]); make_file(filenames[1].get_ref(), ~[]); From 679b1dcb62b53f52f6e4ffe18cc89be8dbf5cc15 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 3 Apr 2013 22:34:29 -0700 Subject: [PATCH 29/35] doc: Rewrite task tutorial intro It doesn't quite reflect reality --- doc/tutorial-tasks.md | 67 ++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 39 deletions(-) diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index 5168809e9aab7..7831dc1d80fc0 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -2,66 +2,56 @@ # Introduction -The designers of Rust designed the language from the ground up to support pervasive -and safe concurrency through lightweight, memory-isolated tasks and -message passing. - -Rust tasks are not the same as traditional threads: rather, they are more like -_green threads_. The Rust runtime system schedules tasks cooperatively onto a -small number of operating system threads. Because tasks are significantly +Rust provides safe concurrency through a combination +of lightweight, memory-isolated tasks and message passing. +This tutorial will describe the concurrency model in Rust, how it +relates to the Rust type system, and introduce +the fundamental library abstractions for constructing concurrent programs. + +Rust tasks are not the same as traditional threads: rather, +they are considered _green threads_, lightweight units of execution that the Rust +runtime schedules cooperatively onto a small number of operating system threads. +On a multi-core system Rust tasks will be scheduled in parallel by default. +Because tasks are significantly cheaper to create than traditional threads, Rust can create hundreds of thousands of concurrent tasks on a typical 32-bit system. +In general, all Rust code executes inside a task, including the `main` function. + +In order to make efficient use of memory Rust tasks have dynamically sized stacks. +A task begins its life with a small +amount of stack space (currently in the low thousands of bytes, depending on +platform), and acquires more stack as needed. +Unlike in languages such as C, a Rust task cannot accidentally write to +memory beyond the end of the stack, causing crashes or worse. -Tasks provide failure isolation and recovery. When an exception occurs in Rust -code (as a result of an explicit call to `fail!()`, an assertion failure, or -another invalid operation), the runtime system destroys the entire +Tasks provide failure isolation and recovery. When a fatal error occurs in Rust +code as a result of an explicit call to `fail!()`, an assertion failure, or +another invalid operation, the runtime system destroys the entire task. Unlike in languages such as Java and C++, there is no way to `catch` an exception. Instead, tasks may monitor each other for failure. -Rust tasks have dynamically sized stacks. A task begins its life with a small -amount of stack space (currently in the low thousands of bytes, depending on -platform), and acquires more stack as needed. Unlike in languages such as C, a -Rust task cannot run off the end of the stack. However, tasks do have a stack -budget. If a Rust task exceeds its stack budget, then it will fail safely: -with a checked exception. - Tasks use Rust's type system to provide strong memory safety guarantees. In particular, the type system guarantees that tasks cannot share mutable state with each other. Tasks communicate with each other by transferring _owned_ data through the global _exchange heap_. -This tutorial explains the basics of tasks and communication in Rust, -explores some typical patterns in concurrent Rust code, and finally -discusses some of the more unusual synchronization types in the standard -library. - -> ***Warning:*** This tutorial is incomplete - ## A note about the libraries While Rust's type system provides the building blocks needed for safe and efficient tasks, all of the task functionality itself is implemented in the core and standard libraries, which are still under development -and do not always present a consistent interface. - -In particular, there are currently two independent modules that provide a -message passing interface to Rust code: `core::comm` and `core::pipes`. -`core::comm` is an older, less efficient system that is being phased out in -favor of `pipes`. At some point, we will remove the existing `core::comm` API -and move the user-facing portions of `core::pipes` to `core::comm`. In this -tutorial, we discuss `pipes` and ignore the `comm` API. +and do not always present a consistent or complete interface. For your reference, these are the standard modules involved in Rust concurrency at this writing. * [`core::task`] - All code relating to tasks and task scheduling -* [`core::comm`] - The deprecated message passing API -* [`core::pipes`] - The new message passing infrastructure and API -* [`std::comm`] - Higher level messaging types based on `core::pipes` +* [`core::comm`] - The message passing interface +* [`core::pipes`] - The underlying messaging infrastructure +* [`std::comm`] - Additional messaging types based on `core::pipes` * [`std::sync`] - More exotic synchronization tools, including locks -* [`std::arc`] - The ARC (atomic reference counted) type, for safely sharing - immutable data -* [`std::par`] - Some basic tools for implementing parallel algorithms +* [`std::arc`] - The ARC (atomically reference counted) type, + for safely sharing immutable data [`core::task`]: core/task.html [`core::comm`]: core/comm.html @@ -69,7 +59,6 @@ concurrency at this writing. [`std::comm`]: std/comm.html [`std::sync`]: std/sync.html [`std::arc`]: std/arc.html -[`std::par`]: std/par.html # Basics From 99b156e78a592e8195ae7918a1ad958abef96050 Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Tue, 19 Mar 2013 13:32:03 +0800 Subject: [PATCH 30/35] mk: mips toolchain config --- mk/platform.mk | 25 +++++++++++++++++++++++++ mk/rt.mk | 5 +++++ 2 files changed, 30 insertions(+) diff --git a/mk/platform.mk b/mk/platform.mk index 16b5ba452f4c9..1e102587bf4a0 100644 --- a/mk/platform.mk +++ b/mk/platform.mk @@ -239,6 +239,31 @@ CFG_RUN_arm-linux-androideabi= CFG_RUN_TARG_arm-linux-androideabi= RUSTC_FLAGS_arm-linux-androideabi :=--android-cross-path=$(CFG_ANDROID_CROSS_PATH) +# mips-unknown-linux-gnu configuration +CC_mips-unknown-linux-gnu=mips-linux-gnu-gcc +CXX_mips-unknown-linux-gnu=mips-linux-gnu-g++ +CPP_mips-unknown-linux-gnu=mips-linux-gnu-gcc -E +AR_mips-unknown-linux-gnu=mips-linux-gnu-ar +CFG_LIB_NAME_mips-unknown-linux-gnu=lib$(1).so +CFG_LIB_GLOB_mips-unknown-linux-gnu=lib$(1)-*.so +CFG_LIB_DSYM_GLOB_mips-unknown-linux-gnu=lib$(1)-*.dylib.dSYM +CFG_GCCISH_CFLAGS_mips-unknown-linux-gnu := -Wall -g -fPIC -mips32r2 -msoft-float -mabi=32 +CFG_GCCISH_CXXFLAGS_mips-unknown-linux-gnu := -fno-rtti +CFG_GCCISH_LINK_FLAGS_mips-unknown-linux-gnu := -shared -fPIC -g -mips32r2 -msoft-float -mabi=32 +CFG_GCCISH_DEF_FLAG_mips-unknown-linux-gnu := -Wl,--export-dynamic,--dynamic-list= +CFG_GCCISH_PRE_LIB_FLAGS_mips-unknown-linux-gnu := -Wl,-whole-archive +CFG_GCCISH_POST_LIB_FLAGS_mips-unknown-linux-gnu := -Wl,-no-whole-archive -Wl,-znoexecstack +CFG_DEF_SUFFIX_mips-unknown-linux-gnu := .linux.def +CFG_INSTALL_NAME_mips-unknown-linux-gnu = +CFG_LIBUV_LINK_FLAGS_mips-unknown-linux-gnu = +CFG_EXE_SUFFIX_mips-unknown-linux-gnu := +CFG_WINDOWSY_mips-unknown-linux-gnu := +CFG_UNIXY_mips-unknown-linux-gnu := 1 +CFG_PATH_MUNGE_mips-unknown-linux-gnu := true +CFG_LDPATH_mips-unknown-linux-gnu := +CFG_RUN_mips-unknown-linux-gnu= +CFG_RUN_TARG_mips-unknown-linux-gnu= + # i686-pc-mingw32 configuration CC_i686-pc-mingw32=$(CC) CXX_i686-pc-mingw32=$(CXX) diff --git a/mk/rt.mk b/mk/rt.mk index 15712b91a1e47..b2c282e207fbc 100644 --- a/mk/rt.mk +++ b/mk/rt.mk @@ -27,6 +27,7 @@ LIBUV_FLAGS_i386 = -m32 -fPIC LIBUV_FLAGS_x86_64 = -m64 -fPIC LIBUV_FLAGS_arm = -fPIC -DANDROID -std=gnu99 +LIBUV_FLAGS_mips = -fPIC -mips32r2 -msoft-float -mabi=32 # when we're doing a snapshot build, we intentionally degrade as many # features in libuv and the runtime as possible, to ease portability. @@ -180,6 +181,10 @@ else $$(LIBUV_LIB_$(1)): $$(LIBUV_DEPS) $$(Q)$$(MAKE) -C $$(S)src/libuv/ \ CFLAGS="$$(LIBUV_FLAGS_$$(HOST_$(1))) $$(SNAP_DEFINES)" \ + LDFLAGS="$$(LIBUV_FLAGS_$$(HOST_$(1)))" \ + CC="$$(CC_$(1))" \ + CXX="$$(CXX_$(1))" \ + AR="$$(AR_$(1))" \ builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/libuv" \ V=$$(VERBOSE) endif From fdf48a7b52de948b3ec4ba187539a6164a56edcb Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Tue, 19 Mar 2013 13:34:12 +0800 Subject: [PATCH 31/35] rt: improve mips backend --- src/libcore/rt/context.rs | 1 + src/librustc/driver/driver.rs | 2 +- src/rt/arch/mips/_context.S | 3 ++- src/rt/arch/mips/ccall.S | 29 +++++++++++++++++++---------- src/rt/arch/mips/context.cpp | 1 + src/rt/sync/rust_thread.cpp | 3 +++ 6 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/libcore/rt/context.rs b/src/libcore/rt/context.rs index 224f28a0329f8..9dc9f5da8c1da 100644 --- a/src/libcore/rt/context.rs +++ b/src/libcore/rt/context.rs @@ -189,6 +189,7 @@ fn initialize_call_frame(regs: &mut Registers, fptr: *c_void, arg: *c_void, sp: regs[4] = arg as uint; regs[29] = sp as uint; + regs[25] = fptr as uint; regs[31] = fptr as uint; } diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 809a4a591ac83..3b1401ae1d2c8 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -89,7 +89,7 @@ pub fn default_configuration(sess: Session, +argv0: ~str, input: input) -> abi::X86 => (~"little",~"x86",~"32"), abi::X86_64 => (~"little",~"x86_64",~"64"), abi::Arm => (~"little",~"arm",~"32"), - abi::Mips => (~"little",~"arm",~"32") + abi::Mips => (~"big",~"mips",~"32") }; return ~[ // Target bindings. diff --git a/src/rt/arch/mips/_context.S b/src/rt/arch/mips/_context.S index c926a03798d2d..6d8207d97d094 100644 --- a/src/rt/arch/mips/_context.S +++ b/src/rt/arch/mips/_context.S @@ -51,7 +51,6 @@ swap_registers: lw $2, 2 * 4($5) lw $3, 3 * 4($5) lw $4, 4 * 4($5) - lw $5, 5 * 4($5) lw $6, 6 * 4($5) lw $7, 7 * 4($5) @@ -82,6 +81,8 @@ swap_registers: lw $30, 30 * 4($5) lw $31, 31 * 4($5) + lw $5, 5 * 4($5) + jr $31 nop .end swap_registers diff --git a/src/rt/arch/mips/ccall.S b/src/rt/arch/mips/ccall.S index f41d8e721f66f..abbbad164fd37 100644 --- a/src/rt/arch/mips/ccall.S +++ b/src/rt/arch/mips/ccall.S @@ -5,30 +5,39 @@ .text +.align 2 .globl __morestack .hidden __morestack -.align 2 +.cfi_sections .eh_frame_entry +.cfi_startproc .set nomips16 .ent __morestack __morestack: .set noreorder .set nomacro - move $7, $29 - move $29, $6 - sw $7, 0($29) - sw $31, -4($29) + addiu $29, $29, -8 + sw $31, 4($29) + sw $30, 0($29) - addiu $29, $29, -24 + .cfi_def_cfa_offset 8 + .cfi_offset 31, -4 + .cfi_offset 30, -8 + + move $30, $29 + .cfi_def_cfa_register 30 + + move $29, $6 move $25, $5 jalr $25 nop - addiu $29, $29, 24 + move $29, $30 - lw $31, -4($29) - lw $7, 0($29) + lw $30, 0($29) + lw $31, 4($29) + addiu $29, $29, 8 - move $29, $7 jr $31 nop .end __morestack +.cfi_endproc diff --git a/src/rt/arch/mips/context.cpp b/src/rt/arch/mips/context.cpp index d8c3c38daa6df..7347a92e98b92 100644 --- a/src/rt/arch/mips/context.cpp +++ b/src/rt/arch/mips/context.cpp @@ -40,6 +40,7 @@ void context::call(void *f, void *arg, void *stack) regs.data[4] = (uint32_t)arg; regs.data[29] = (uint32_t)sp; + regs.data[25] = (uint32_t)f; regs.data[31] = (uint32_t)f; // Last base pointer on the stack should be 0 diff --git a/src/rt/sync/rust_thread.cpp b/src/rt/sync/rust_thread.cpp index 70fa08d7f2e5d..99613da9b0dbf 100644 --- a/src/rt/sync/rust_thread.cpp +++ b/src/rt/sync/rust_thread.cpp @@ -41,6 +41,9 @@ rust_thread::start() { #if defined(__WIN32__) thread = CreateThread(NULL, stack_sz, rust_thread_start, this, 0, NULL); #else + if (stack_sz < PTHREAD_STACK_MIN) { + stack_sz = PTHREAD_STACK_MIN; + } pthread_attr_t attr; CHECKED(pthread_attr_init(&attr)); CHECKED(pthread_attr_setstacksize(&attr, stack_sz)); From 4f1d8cb6fce625d13baf12f49e41d29f1433c8dd Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Fri, 29 Mar 2013 11:31:34 +0800 Subject: [PATCH 32/35] fix mac build and comment on stack size check --- src/rt/sync/rust_thread.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/rt/sync/rust_thread.cpp b/src/rt/sync/rust_thread.cpp index 99613da9b0dbf..824642fc435d0 100644 --- a/src/rt/sync/rust_thread.cpp +++ b/src/rt/sync/rust_thread.cpp @@ -10,6 +10,7 @@ #include "rust_thread.h" +#include const size_t default_stack_sz = 1024*1024; @@ -41,6 +42,8 @@ rust_thread::start() { #if defined(__WIN32__) thread = CreateThread(NULL, stack_sz, rust_thread_start, this, 0, NULL); #else + // PTHREAD_STACK_MIN of some system is larger than default size + // so we check stack_sz to prevent assertion failure. if (stack_sz < PTHREAD_STACK_MIN) { stack_sz = PTHREAD_STACK_MIN; } From cb91e914185f4be9073dcec9a96ca6b78b7e877f Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Thu, 4 Apr 2013 15:08:25 +0200 Subject: [PATCH 33/35] Tutorial: rename variable to avoid confusion. --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/tutorial.md b/doc/tutorial.md index 42b0d5a585aee..c7d92c03b6d1d 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1191,7 +1191,7 @@ they are frozen: let x = @mut 5; let y = x; { - let y = &*y; // the managed box is now frozen + let z = &*y; // the managed box is now frozen // modifying it through x or y will cause a task failure } // the box is now unfrozen again From 2c02aab75851f6bc86b033f07d971fe892c111ef Mon Sep 17 00:00:00 2001 From: Jack Moffitt Date: Thu, 4 Apr 2013 11:34:35 -0600 Subject: [PATCH 34/35] Add cell#with_mut_ref for handling mutable references to the content. --- src/libcore/cell.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index c2983e033e537..1707bddc2b9d4 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -73,6 +73,14 @@ pub impl Cell { self.put_back(v); r } + + // Calls a closure with a mutable reference to the value. + fn with_mut_ref(&self, op: &fn(v: &mut T) -> R) -> R { + let mut v = self.take(); + let r = op(&mut v); + self.put_back(v); + r + } } #[test] @@ -101,3 +109,21 @@ fn test_put_back_non_empty() { let value_cell = Cell(~10); value_cell.put_back(~20); } + +#[test] +fn test_with_ref() { + let good = 6; + let c = Cell(~[1, 2, 3, 4, 5, 6]); + let l = do c.with_ref() |v| { v.len() }; + assert!(l == good); +} + +#[test] +fn test_with_mut_ref() { + let good = ~[1, 2, 3]; + let mut v = ~[1, 2]; + let c = Cell(v); + do c.with_mut_ref() |v| { v.push(3); } + let v = c.take(); + assert!(v == good); +} From b22a06000d68faf7fe080dc9fd5a2686502d212f Mon Sep 17 00:00:00 2001 From: Jack Moffitt Date: Fri, 5 Apr 2013 16:41:47 -0600 Subject: [PATCH 35/35] Implement Clone for @ and @mut types. The borrowck-borrow-from-expr-block test had to be updated. I'm not sure why it compiled before since ~int was already clonable. --- src/libcore/clone.rs | 10 +++++++ .../borrowck-borrow-from-expr-block.rs | 2 +- src/test/run-pass/clones.rs | 27 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/test/run-pass/clones.rs diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 7b86355c91e50..10cce4f69c611 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -36,6 +36,16 @@ impl Clone for ~T { fn clone(&self) -> ~T { ~(**self).clone() } } +impl Clone for @T { + #[inline(always)] + fn clone(&self) -> @T { @(**self).clone() } +} + +impl Clone for @mut T { + #[inline(always)] + fn clone(&self) -> @mut T { @mut (**self).clone() } +} + macro_rules! clone_impl( ($t:ty) => { impl Clone for $t { diff --git a/src/test/run-pass/borrowck-borrow-from-expr-block.rs b/src/test/run-pass/borrowck-borrow-from-expr-block.rs index 401985023bcc7..fc7786d08cb57 100644 --- a/src/test/run-pass/borrowck-borrow-from-expr-block.rs +++ b/src/test/run-pass/borrowck-borrow-from-expr-block.rs @@ -13,7 +13,7 @@ fn borrow(x: &int, f: &fn(x: &int)) { } fn test1(x: @~int) { - do borrow(&*x.clone()) |p| { + do borrow(&**x.clone()) |p| { let x_a = ptr::addr_of(&(**x)); assert!((x_a as uint) != ptr::to_uint(p)); assert!(unsafe{*x_a} == *p); diff --git a/src/test/run-pass/clones.rs b/src/test/run-pass/clones.rs new file mode 100644 index 0000000000000..f4fa1b81ab1ad --- /dev/null +++ b/src/test/run-pass/clones.rs @@ -0,0 +1,27 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + let a : ~int = ~5i; + let b : ~int = a.clone(); + + debug!(fmt!("a: %?, b: %?", a, b)); + + let a : @int = @5i; + let b : @int = a.clone(); + + debug!(fmt!("a: %?, b: %?", a, b)); + + let a : @mut int = @mut 5i; + let b : @mut int = a.clone(); + *b = 6; + + debug!(fmt!("a: %?, b: %?", a, b)); +}