]> git.lizzy.rs Git - rust.git/commitdiff
Make fields of `Span` private
authorVadim Petrochenkov <vadim.petrochenkov@gmail.com>
Mon, 31 Jul 2017 20:04:34 +0000 (23:04 +0300)
committerVadim Petrochenkov <vadim.petrochenkov@gmail.com>
Tue, 29 Aug 2017 22:38:54 +0000 (01:38 +0300)
60 files changed:
src/libproc_macro/lib.rs
src/librustc/hir/lowering.rs
src/librustc/hir/print.rs
src/librustc/ich/hcx.rs
src/librustc/infer/error_reporting/mod.rs
src/librustc/middle/region.rs
src/librustc_allocator/expand.rs
src/librustc_errors/emitter.rs
src/librustc_errors/lib.rs
src/librustc_metadata/cstore_impl.rs
src/librustc_metadata/decoder.rs
src/librustc_mir/build/mod.rs
src/librustc_mir/build/scope.rs
src/librustc_privacy/lib.rs
src/librustc_resolve/lib.rs
src/librustc_resolve/resolve_imports.rs
src/librustc_save_analysis/lib.rs
src/librustc_save_analysis/span_utils.rs
src/librustc_trans/base.rs
src/librustc_trans/debuginfo/utils.rs
src/librustc_trans/mir/block.rs
src/librustc_trans/mir/mod.rs
src/librustc_typeck/check/mod.rs
src/librustdoc/clean/mod.rs
src/librustdoc/test.rs
src/libsyntax/ast.rs
src/libsyntax/attr.rs
src/libsyntax/codemap.rs
src/libsyntax/config.rs
src/libsyntax/diagnostics/metadata.rs
src/libsyntax/ext/base.rs
src/libsyntax/ext/build.rs
src/libsyntax/ext/derive.rs
src/libsyntax/ext/expand.rs
src/libsyntax/ext/source_util.rs
src/libsyntax/ext/tt/macro_parser.rs
src/libsyntax/ext/tt/macro_rules.rs
src/libsyntax/ext/tt/quoted.rs
src/libsyntax/ext/tt/transcribe.rs
src/libsyntax/json.rs
src/libsyntax/parse/lexer/comments.rs
src/libsyntax/parse/lexer/mod.rs
src/libsyntax/parse/lexer/tokentrees.rs
src/libsyntax/parse/lexer/unicode_chars.rs
src/libsyntax/parse/mod.rs
src/libsyntax/parse/parser.rs
src/libsyntax/print/pprust.rs
src/libsyntax/std_inject.rs
src/libsyntax/test.rs
src/libsyntax/test_snippet.rs
src/libsyntax/tokenstream.rs
src/libsyntax_ext/deriving/clone.rs
src/libsyntax_ext/deriving/cmp/eq.rs
src/libsyntax_ext/deriving/debug.rs
src/libsyntax_ext/deriving/generic/mod.rs
src/libsyntax_ext/deriving/mod.rs
src/libsyntax_ext/format.rs
src/libsyntax_ext/proc_macro_registrar.rs
src/libsyntax_pos/lib.rs
src/test/run-pass/import-crate-with-invalid-spans/main.rs

index 3f425c24a9143479b72c3ed62ec4adb80f917a75..a86854cdbc7dff237c782ca602f0bef956ff39bd 100644 (file)
@@ -89,10 +89,7 @@ fn from_str(src: &str) -> Result<TokenStream, LexError> {
             // notify the expansion info that it is unhygienic
             let mark = Mark::fresh(mark);
             mark.set_expn_info(expn_info);
-            let span = syntax_pos::Span {
-                ctxt: SyntaxContext::empty().apply_mark(mark),
-                ..call_site
-            };
+            let span = call_site.with_ctxt(SyntaxContext::empty().apply_mark(mark));
             let stream = parse::parse_stream_from_source_str(name, src, sess, Some(span));
             Ok(__internal::token_stream_wrap(stream))
         })
@@ -177,10 +174,10 @@ pub fn is_empty(&self) -> bool {
 #[unstable(feature = "proc_macro", issue = "38356")]
 impl Default for Span {
     fn default() -> Span {
-        ::__internal::with_sess(|(_, mark)| Span(syntax_pos::Span {
-            ctxt: SyntaxContext::empty().apply_mark(mark),
-            ..mark.expn_info().unwrap().call_site
-        }))
+        ::__internal::with_sess(|(_, mark)| {
+            let call_site = mark.expn_info().unwrap().call_site;
+            Span(call_site.with_ctxt(SyntaxContext::empty().apply_mark(mark)))
+        })
     }
 }
 
@@ -570,7 +567,7 @@ fn to_internal(self) -> tokenstream::TokenStream {
                 }).into();
             },
             TokenNode::Term(symbol) => {
-                let ident = ast::Ident { name: symbol.0, ctxt: self.span.0.ctxt };
+                let ident = ast::Ident { name: symbol.0, ctxt: self.span.0.ctxt() };
                 let token =
                     if symbol.0.as_str().starts_with("'") { Lifetime(ident) } else { Ident(ident) };
                 return TokenTree::Token(self.span.0, token).into();
index f6ded6468b102d80f439406ef8b20151b4d39f45..0f69c06c417a1e5b7fcfd5d6ecfc44827009fb09 100644 (file)
@@ -425,8 +425,7 @@ fn str_to_ident(&self, s: &'static str) -> Name {
         Symbol::gensym(s)
     }
 
-    fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, mut span: Span)
-        -> Span
+    fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span
     {
         let mark = Mark::fresh(Mark::root());
         mark.set_expn_info(codemap::ExpnInfo {
@@ -438,8 +437,7 @@ fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, mut span: Span
                 allow_internal_unsafe: false,
             },
         });
-        span.ctxt = SyntaxContext::empty().apply_mark(mark);
-        span
+        span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
     }
 
     fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
@@ -613,7 +611,7 @@ fn lower_ty(&mut self, t: &Ty) -> P<hir::Ty> {
             TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty)),
             TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt)),
             TyKind::Rptr(ref region, ref mt) => {
-                let span = Span { hi: t.span.lo, ..t.span };
+                let span = t.span.with_hi(t.span.lo());
                 let lifetime = match *region {
                     Some(ref lt) => self.lower_lifetime(lt),
                     None => self.elided_lifetime(span)
@@ -1237,7 +1235,7 @@ fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::Stru
             name: self.lower_ident(match f.ident {
                 Some(ident) => ident,
                 // FIXME(jseyfried) positional field hygiene
-                None => Ident { name: Symbol::intern(&index.to_string()), ctxt: f.span.ctxt },
+                None => Ident { name: Symbol::intern(&index.to_string()), ctxt: f.span.ctxt() },
             }),
             vis: self.lower_visibility(&f.vis, None),
             ty: self.lower_ty(&f.ty),
index 80269592bb78e676cf08a54ffb2e5ba0204335b3..dce824bd513a7d9d00392914346a40ffac879ccf 100644 (file)
@@ -262,7 +262,7 @@ pub fn bclose_maybe_open(&mut self,
                              indented: usize,
                              close_box: bool)
                              -> io::Result<()> {
-        self.maybe_print_comment(span.hi)?;
+        self.maybe_print_comment(span.hi())?;
         self.break_offset_if_not_bol(1, -(indented as isize))?;
         self.s.word("}")?;
         if close_box {
@@ -324,12 +324,12 @@ pub fn commasep_cmnt<T, F, G>(&mut self,
         let len = elts.len();
         let mut i = 0;
         for elt in elts {
-            self.maybe_print_comment(get_span(elt).hi)?;
+            self.maybe_print_comment(get_span(elt).hi())?;
             op(self, elt)?;
             i += 1;
             if i < len {
                 self.s.word(",")?;
-                self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi))?;
+                self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
                 self.space_if_not_bol()?;
             }
         }
@@ -368,7 +368,7 @@ pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()>
     }
 
     pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
-        self.maybe_print_comment(ty.span.lo)?;
+        self.maybe_print_comment(ty.span.lo())?;
         self.ibox(0)?;
         match ty.node {
             hir::TySlice(ref ty) => {
@@ -458,7 +458,7 @@ pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
 
     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(item.span.lo)?;
+        self.maybe_print_comment(item.span.lo())?;
         self.print_outer_attributes(&item.attrs)?;
         match item.node {
             hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
@@ -531,7 +531,7 @@ fn print_associated_type(&mut self,
     /// Pretty-print an item
     pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(item.span.lo)?;
+        self.maybe_print_comment(item.span.lo())?;
         self.print_outer_attributes(&item.attrs)?;
         self.ann.pre(self, NodeItem(item))?;
         match item.node {
@@ -797,7 +797,7 @@ pub fn print_variants(&mut self,
         self.bopen()?;
         for v in variants {
             self.space_if_not_bol()?;
-            self.maybe_print_comment(v.span.lo)?;
+            self.maybe_print_comment(v.span.lo())?;
             self.print_outer_attributes(&v.node.attrs)?;
             self.ibox(indent_unit)?;
             self.print_variant(v)?;
@@ -842,7 +842,7 @@ pub fn print_struct(&mut self,
             if struct_def.is_tuple() {
                 self.popen()?;
                 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
-                    s.maybe_print_comment(field.span.lo)?;
+                    s.maybe_print_comment(field.span.lo())?;
                     s.print_outer_attributes(&field.attrs)?;
                     s.print_visibility(&field.vis)?;
                     s.print_type(&field.ty)
@@ -863,7 +863,7 @@ pub fn print_struct(&mut self,
 
             for field in struct_def.fields() {
                 self.hardbreak_if_not_bol()?;
-                self.maybe_print_comment(field.span.lo)?;
+                self.maybe_print_comment(field.span.lo())?;
                 self.print_outer_attributes(&field.attrs)?;
                 self.print_visibility(&field.vis)?;
                 self.print_name(field.name)?;
@@ -908,7 +908,7 @@ pub fn print_method_sig(&mut self,
     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
         self.ann.pre(self, NodeSubItem(ti.id))?;
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(ti.span.lo)?;
+        self.maybe_print_comment(ti.span.lo())?;
         self.print_outer_attributes(&ti.attrs)?;
         match ti.node {
             hir::TraitItemKind::Const(ref ty, default) => {
@@ -938,7 +938,7 @@ pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
         self.ann.pre(self, NodeSubItem(ii.id))?;
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(ii.span.lo)?;
+        self.maybe_print_comment(ii.span.lo())?;
         self.print_outer_attributes(&ii.attrs)?;
         self.print_defaultness(ii.defaultness)?;
 
@@ -962,7 +962,7 @@ pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
     }
 
     pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
-        self.maybe_print_comment(st.span.lo)?;
+        self.maybe_print_comment(st.span.lo())?;
         match st.node {
             hir::StmtDecl(ref decl, _) => {
                 self.print_decl(&decl)?;
@@ -1017,7 +1017,7 @@ pub fn print_block_maybe_unclosed(&mut self,
             hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
             hir::DefaultBlock => (),
         }
-        self.maybe_print_comment(blk.span.lo)?;
+        self.maybe_print_comment(blk.span.lo())?;
         self.ann.pre(self, NodeBlock(blk))?;
         self.bopen()?;
 
@@ -1030,7 +1030,7 @@ pub fn print_block_maybe_unclosed(&mut self,
             Some(ref expr) => {
                 self.space_if_not_bol()?;
                 self.print_expr(&expr)?;
-                self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
+                self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
             }
             _ => (),
         }
@@ -1228,7 +1228,7 @@ fn print_expr_addr_of(&mut self,
     }
 
     pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
-        self.maybe_print_comment(expr.span.lo)?;
+        self.maybe_print_comment(expr.span.lo())?;
         self.print_outer_attributes(&expr.attrs)?;
         self.ibox(indent_unit)?;
         self.ann.pre(self, NodeExpr(expr))?;
@@ -1480,7 +1480,7 @@ pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
     }
 
     pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
-        self.maybe_print_comment(decl.span.lo)?;
+        self.maybe_print_comment(decl.span.lo())?;
         match decl.node {
             hir::DeclLocal(ref loc) => {
                 self.space_if_not_bol()?;
@@ -1523,7 +1523,7 @@ pub fn print_path(&mut self,
                       path: &hir::Path,
                       colons_before_params: bool)
                       -> io::Result<()> {
-        self.maybe_print_comment(path.span.lo)?;
+        self.maybe_print_comment(path.span.lo())?;
 
         for (i, segment) in path.segments.iter().enumerate() {
             if i > 0 {
@@ -1641,7 +1641,7 @@ fn print_path_parameters(&mut self,
     }
 
     pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
-        self.maybe_print_comment(pat.span.lo)?;
+        self.maybe_print_comment(pat.span.lo())?;
         self.ann.pre(self, NodePat(pat))?;
         // Pat isn't normalized, but the beauty of it
         // is that it doesn't matter
@@ -1897,7 +1897,7 @@ fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io
         match decl.output {
             hir::Return(ref ty) => {
                 self.print_type(&ty)?;
-                self.maybe_print_comment(ty.span.lo)
+                self.maybe_print_comment(ty.span.lo())
             }
             hir::DefaultReturn(..) => unreachable!(),
         }
@@ -2074,7 +2074,7 @@ pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
         self.end()?;
 
         match decl.output {
-            hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
+            hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
             _ => Ok(()),
         }
     }
@@ -2124,13 +2124,13 @@ pub fn maybe_print_trailing_comment(&mut self,
             if (*cmnt).style != comments::Trailing {
                 return Ok(());
             }
-            let span_line = cm.lookup_char_pos(span.hi);
+            let span_line = cm.lookup_char_pos(span.hi());
             let comment_line = cm.lookup_char_pos((*cmnt).pos);
             let mut next = (*cmnt).pos + BytePos(1);
             if let Some(p) = next_pos {
                 next = p;
             }
-            if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
+            if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
                span_line.line == comment_line.line {
                 self.print_comment(cmnt)?;
             }
index 218483232d673f66f362f9a565a1808f677a9681..544c824f83ce2f9e4c048da32ac0efce704d6577 100644 (file)
@@ -253,17 +253,17 @@ fn hash_stable<W: StableHasherResult>(&self,
         // If this is not an empty or invalid span, we want to hash the last
         // position that belongs to it, as opposed to hashing the first
         // position past it.
-        let span_hi = if self.hi > self.lo {
+        let span_hi = if self.hi() > self.lo() {
             // We might end up in the middle of a multibyte character here,
             // but that's OK, since we are not trying to decode anything at
             // this position.
-            self.hi - ::syntax_pos::BytePos(1)
+            self.hi() - ::syntax_pos::BytePos(1)
         } else {
-            self.hi
+            self.hi()
         };
 
         {
-            let loc1 = hcx.codemap().byte_pos_to_line_and_col(self.lo);
+            let loc1 = hcx.codemap().byte_pos_to_line_and_col(self.lo());
             let loc1 = loc1.as_ref()
                            .map(|&(ref fm, line, col)| (&fm.name[..], line, col.to_usize()))
                            .unwrap_or(("???", 0, 0));
@@ -296,7 +296,7 @@ fn hash_stable<W: StableHasherResult>(&self,
             }
         }
 
-        if self.ctxt == SyntaxContext::empty() {
+        if self.ctxt() == SyntaxContext::empty() {
             0u8.hash_stable(hcx, hasher);
         } else {
             1u8.hash_stable(hcx, hasher);
index edf9ca89b3394e7bc11ffd2d1758d5c8ab69ee08..4c55c1474a326c11759e6ce1aa87c81dbcba47d4 100644 (file)
@@ -118,7 +118,7 @@ fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
         fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
                                         heading: &str, span: Span)
                                         -> (String, Option<Span>) {
-            let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
+            let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo());
             (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
              Some(span))
         }
index 944d03737d37d0eb48dfa595ca8b1d9178a76284..a611b3b937beef5bbaf37a70ef15825ec14d5b9d 100644 (file)
@@ -180,7 +180,7 @@ pub fn span(&self, hir_map: &hir_map::Map) -> Option<Span> {
                         // (This is the special case aluded to in the
                         // doc-comment for this method)
                         let stmt_span = blk.stmts[r.first_statement_index as usize].span;
-                        Some(Span { lo: stmt_span.hi, hi: blk.span.hi, ctxt: stmt_span.ctxt })
+                        Some(Span::new(stmt_span.hi(), blk.span.hi(), stmt_span.ctxt()))
                     }
                 }
             }
index f99c6a29ff00a9cd71033aa40781b7a68c2027b4..eafb4c5c80078c6cc8a91bf73786369f0e2384c2 100644 (file)
@@ -82,10 +82,7 @@ fn fold_item(&mut self, item: P<Item>) -> SmallVector<P<Item>> {
                 allow_internal_unsafe: false,
             }
         });
-        let span = Span {
-            ctxt: SyntaxContext::empty().apply_mark(mark),
-            ..item.span
-        };
+        let span = item.span.with_ctxt(SyntaxContext::empty().apply_mark(mark));
         let ecfg = ExpansionConfig::default(name.to_string());
         let mut f = AllocFnFactory {
             span,
index 53d90531cc946a4c043d7c7983200f0f6ffc1228..daa132dbf6213b35202b2fd375f44e043ed7b51d 100644 (file)
@@ -183,8 +183,8 @@ fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
                     continue;
                 }
 
-                let lo = cm.lookup_char_pos(span_label.span.lo);
-                let mut hi = cm.lookup_char_pos(span_label.span.hi);
+                let lo = cm.lookup_char_pos(span_label.span.lo());
+                let mut hi = cm.lookup_char_pos(span_label.span.hi());
 
                 // Watch out for "empty spans". If we get a span like 6..6, we
                 // want to just display a `^` at 6, so convert that to
@@ -683,7 +683,7 @@ fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
         if let Some(ref cm) = self.cm {
             for primary_span in msp.primary_spans() {
                 if primary_span != &DUMMY_SP {
-                    let hi = cm.lookup_char_pos(primary_span.hi);
+                    let hi = cm.lookup_char_pos(primary_span.hi());
                     if hi.line > max {
                         max = hi.line;
                     }
@@ -691,7 +691,7 @@ fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
             }
             for span_label in msp.span_labels() {
                 if span_label.span != DUMMY_SP {
-                    let hi = cm.lookup_char_pos(span_label.span.hi);
+                    let hi = cm.lookup_char_pos(span_label.span.hi());
                     if hi.line > max {
                         max = hi.line;
                     }
@@ -914,7 +914,7 @@ fn emit_message_default(&mut self,
         let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
             (self.cm.as_ref(), msp.primary_span().as_ref()) {
             if primary_span != &&DUMMY_SP {
-                (cm.lookup_char_pos(primary_span.lo), cm)
+                (cm.lookup_char_pos(primary_span.lo()), cm)
             } else {
                 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
                 return Ok(());
@@ -1091,7 +1091,7 @@ fn emit_suggestion_default(&mut self,
                                Some(Style::HeaderMsg));
 
             let suggestions = suggestion.splice_lines(cm.borrow());
-            let span_start_pos = cm.lookup_char_pos(primary_sub.span.lo);
+            let span_start_pos = cm.lookup_char_pos(primary_sub.span.lo());
             let line_start = span_start_pos.line;
             draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
             let mut row_num = 2;
index 870bb01bb9ffb7963ff6a6b6057721a690e28c31..7aaf4e598d6bf273b0f06ece3b10347986a58ae9 100644 (file)
@@ -148,16 +148,12 @@ fn push_trailing(buf: &mut String,
 
         // Assumption: all spans are in the same file, and all spans
         // are disjoint. Sort in ascending order.
-        primary_spans.sort_by_key(|sp| sp.0.lo);
+        primary_spans.sort_by_key(|sp| sp.0.lo());
 
         // Find the bounding span.
-        let lo = primary_spans.iter().map(|sp| sp.0.lo).min().unwrap();
-        let hi = primary_spans.iter().map(|sp| sp.0.hi).min().unwrap();
-        let bounding_span = Span {
-            lo,
-            hi,
-            ctxt: NO_EXPANSION,
-        };
+        let lo = primary_spans.iter().map(|sp| sp.0.lo()).min().unwrap();
+        let hi = primary_spans.iter().map(|sp| sp.0.hi()).min().unwrap();
+        let bounding_span = Span::new(lo, hi, NO_EXPANSION);
         let lines = cm.span_to_lines(bounding_span).unwrap();
         assert!(!lines.lines.is_empty());
 
@@ -171,14 +167,14 @@ fn push_trailing(buf: &mut String,
         //
         // Finally push the trailing line segment of the last span
         let fm = &lines.file;
-        let mut prev_hi = cm.lookup_char_pos(bounding_span.lo);
+        let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
         prev_hi.col = CharPos::from_usize(0);
 
         let mut prev_line = fm.get_line(lines.lines[0].line_index);
         let mut bufs = vec![(String::new(), false); self.substitutions()];
 
         for (sp, substitutes) in primary_spans {
-            let cur_lo = cm.lookup_char_pos(sp.lo);
+            let cur_lo = cm.lookup_char_pos(sp.lo());
             for (&mut (ref mut buf, ref mut underline), substitute) in bufs.iter_mut()
                                                                            .zip(substitutes) {
                 if prev_hi.line == cur_lo.line {
@@ -208,7 +204,7 @@ fn push_trailing(buf: &mut String,
                 }
                 buf.push_str(substitute);
             }
-            prev_hi = cm.lookup_char_pos(sp.hi);
+            prev_hi = cm.lookup_char_pos(sp.hi());
             prev_line = fm.get_line(prev_hi.line - 1);
         }
         for &mut (ref mut buf, _) in &mut bufs {
index 56138955e8e66e6c50cdeb8b8a3e25d9d05eafc6..268071ed434827792308817b44b8b80735b00e9a 100644 (file)
@@ -369,7 +369,7 @@ fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
         let source_name = format!("<{} macros>", name);
 
         let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
-        let local_span = Span { lo: filemap.start_pos, hi: filemap.end_pos, ctxt: NO_EXPANSION };
+        let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
         let body = filemap_to_stream(&sess.parse_sess, filemap, None);
 
         // Mark the attrs as used
index 72058747a76d284f7046bb8ca89521eb264d2b4a..1e2f167f199621e466c99b5959d992beb354d0c6 100644 (file)
@@ -242,7 +242,7 @@ fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
         let sess = if let Some(sess) = self.sess {
             sess
         } else {
-            return Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION });
+            return Ok(Span::new(lo, hi, NO_EXPANSION));
         };
 
         let (lo, hi) = if lo > hi {
@@ -289,7 +289,7 @@ fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
         let lo = (lo - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
         let hi = (hi - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
 
-        Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
+        Ok(Span::new(lo, hi, NO_EXPANSION))
     }
 }
 
index 65bbf098cbe174c49bec2a62cf02ffa68466e259..904e30a01eba68791894f69df05735a08a35e59a 100644 (file)
@@ -364,7 +364,7 @@ fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
             builder.args_and_body(block, &arguments, arg_extent, &body.value)
         }));
         // Attribute epilogue to function's closing brace
-        let fn_end = Span { lo: span.hi, ..span };
+        let fn_end = span.with_lo(span.hi());
         let source_info = builder.source_info(fn_end);
         let return_block = builder.return_block();
         builder.cfg.terminate(block, source_info,
index c32e7b247634a60ed123b89ebfe10c00622937ea..90f9c1c0d5f56cbb69ed203118da821e559a21d6 100644 (file)
@@ -636,7 +636,7 @@ pub fn schedule_drop(&mut self,
                 let tcx = self.hir.tcx();
                 let extent_span = extent.span(&tcx.hir).unwrap();
                 // Attribute scope exit drops to scope's closing brace
-                let scope_end = Span { lo: extent_span.hi, .. extent_span};
+                let scope_end = extent_span.with_lo(extent_span.hi());
                 scope.drops.push(DropData {
                     span: scope_end,
                     location: lvalue.clone(),
index 772b16bbecfbaa72a17f7e40674aa13e9bbf0d84..e34b0927f67a9010f4e070065924ff4fbc6d6cee 100644 (file)
@@ -477,7 +477,7 @@ struct NamePrivacyVisitor<'a, 'tcx: 'a> {
 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
     // Checks that a field is accessible.
     fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
-        let ident = Ident { ctxt: span.ctxt.modern(), ..keywords::Invalid.ident() };
+        let ident = Ident { ctxt: span.ctxt().modern(), ..keywords::Invalid.ident() };
         let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
         if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
             struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
index a83ac9bb6336958e4d5e6d644f73c30b8fc72743..2183c9124e7f4367d9390f7651d63dda95b48332 100644 (file)
@@ -606,9 +606,7 @@ fn visit_mod(
                     // don't suggest placing a use before the prelude
                     // import or other generated ones
                     if item.span == DUMMY_SP {
-                        let mut span = item.span;
-                        span.hi = span.lo;
-                        self.span = Some(span);
+                        self.span = Some(item.span.with_hi(item.span.lo()));
                         self.found_use = true;
                         return;
                     }
@@ -617,9 +615,7 @@ fn visit_mod(
                 ItemKind::ExternCrate(_) => {}
                 // but place them before the first other item
                 _ => if self.span.map_or(true, |span| item.span < span ) {
-                    let mut span = item.span;
-                    span.hi = span.lo;
-                    self.span = Some(span);
+                    self.span = Some(item.span.with_hi(item.span.lo()));
                 },
             }
         }
@@ -1732,7 +1728,7 @@ fn resolve_crate_root(&mut self, mut ctxt: SyntaxContext) -> Module<'a> {
 
     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
         let mut module = self.get_module(module.normal_ancestor_id);
-        while module.span.ctxt.modern() != *ctxt {
+        while module.span.ctxt().modern() != *ctxt {
             let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
             module = self.get_module(parent.normal_ancestor_id);
         }
@@ -2659,8 +2655,8 @@ fn type_ascription_suggestion(&self,
                 sp = sp.next_point();
                 if let Ok(snippet) = cm.span_to_snippet(sp.to(sp.next_point())) {
                     debug!("snippet {:?}", snippet);
-                    let line_sp = cm.lookup_char_pos(sp.hi).line;
-                    let line_base_sp = cm.lookup_char_pos(base_span.lo).line;
+                    let line_sp = cm.lookup_char_pos(sp.hi()).line;
+                    let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
                     debug!("{:?} {:?}", line_sp, line_base_sp);
                     if snippet == ":" {
                         err.span_label(base_span,
@@ -3360,7 +3356,7 @@ fn get_traits_in_module_containing_item(&mut self,
         for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
             let module = binding.module().unwrap();
             let mut ident = ident;
-            if ident.ctxt.glob_adjust(module.expansion, binding.span.ctxt.modern()).is_none() {
+            if ident.ctxt.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
                 continue
             }
             if self.resolve_ident_in_module_unadjusted(module, ident, ns, false, false, module.span)
@@ -3586,7 +3582,7 @@ fn report_conflict(&mut self,
                        new_binding: &NameBinding,
                        old_binding: &NameBinding) {
         // Error on the second of two conflicting names
-        if old_binding.span.lo > new_binding.span.lo {
+        if old_binding.span.lo() > new_binding.span.lo() {
             return self.report_conflict(parent, ident, ns, old_binding, new_binding);
         }
 
index 5616971e9d1f54ff50197e1e8f920778f9c94e96..71bcee56ecc515f2d46ae2cabd9d2213178f79f1 100644 (file)
@@ -237,7 +237,7 @@ pub fn resolve_ident_in_module_unadjusted(&mut self,
             }
             let module = unwrap_or!(directive.imported_module.get(), return Err(Undetermined));
             let (orig_current_module, mut ident) = (self.current_module, ident.modern());
-            match ident.ctxt.glob_adjust(module.expansion, directive.span.ctxt.modern()) {
+            match ident.ctxt.glob_adjust(module.expansion, directive.span.ctxt().modern()) {
                 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
                 Some(None) => {}
                 None => continue,
@@ -398,7 +398,7 @@ fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Name
         for directive in module.glob_importers.borrow_mut().iter() {
             let mut ident = ident.modern();
             let scope = match ident.ctxt.reverse_glob_adjust(module.expansion,
-                                                             directive.span.ctxt.modern()) {
+                                                             directive.span.ctxt().modern()) {
                 Some(Some(def)) => self.macro_def_scope(def),
                 Some(None) => directive.parent,
                 None => continue,
@@ -800,7 +800,7 @@ fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
         }).collect::<Vec<_>>();
         for ((mut ident, ns), binding) in bindings {
             let scope = match ident.ctxt.reverse_glob_adjust(module.expansion,
-                                                             directive.span.ctxt.modern()) {
+                                                             directive.span.ctxt().modern()) {
                 Some(Some(def)) => self.macro_def_scope(def),
                 Some(None) => self.current_module,
                 None => continue,
index 9b74df865d74756059db8a89d272f6a17a2675d9..9ee38dd86c1b556859e2a7e8e6a1f1d60bb5b0e8 100644 (file)
@@ -91,13 +91,13 @@ fn span_from_span(&self, span: Span) -> SpanData {
         use rls_span::{Row, Column};
 
         let cm = self.tcx.sess.codemap();
-        let start = cm.lookup_char_pos(span.lo);
-        let end = cm.lookup_char_pos(span.hi);
+        let start = cm.lookup_char_pos(span.lo());
+        let end = cm.lookup_char_pos(span.hi());
 
         SpanData {
             file_name: start.file.name.clone().into(),
-            byte_start: span.lo.0,
-            byte_end: span.hi.0,
+            byte_start: span.lo().0,
+            byte_end: span.hi().0,
             line_start: Row::new_one_indexed(start.line as u32),
             line_end: Row::new_one_indexed(end.line as u32),
             column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
@@ -117,7 +117,7 @@ pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
                     continue;
                 }
             };
-            let lo_loc = self.span_utils.sess.codemap().lookup_char_pos(span.lo);
+            let lo_loc = self.span_utils.sess.codemap().lookup_char_pos(span.lo());
             result.push(ExternalCrateData {
                 name: self.tcx.sess.cstore.crate_name(n).to_string(),
                 num: n.as_u32(),
@@ -999,7 +999,7 @@ fn escape(s: String) -> String {
 // Helper function to determine if a span came from a
 // macro expansion or syntax extension.
 fn generated_code(span: Span) -> bool {
-    span.ctxt != NO_EXPANSION || span == DUMMY_SP
+    span.ctxt() != NO_EXPANSION || span == DUMMY_SP
 }
 
 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
index 36e4d09c963f5b6bd1e8f9d813b77c4b82b45f81..b9d82b8e2512a1c21bb64a871c7b879c6274222f 100644 (file)
@@ -192,7 +192,7 @@ pub fn sub_span_for_type_name(&self, span: Span) -> Option<Span> {
             prev = next;
         }
         if angle_count != 0 || bracket_count != 0 {
-            let loc = self.sess.codemap().lookup_char_pos(span.lo);
+            let loc = self.sess.codemap().lookup_char_pos(span.lo());
             span_bug!(span,
                       "Mis-counted brackets when breaking path? Parsing '{}' \
                        in {}, line {}",
@@ -319,7 +319,7 @@ pub fn filter_generated(&self, sub_span: Option<Span>, parent: Span) -> bool {
         };
 
         //If the span comes from a fake filemap, filter it.
-        if !self.sess.codemap().lookup_char_pos(parent.lo).file.is_real_file() {
+        if !self.sess.codemap().lookup_char_pos(parent.lo()).file.is_real_file() {
             return true;
         }
 
index e4b090471d75a9ca493da22af3525d70de2f42c7..a6c6b0efcfa8cb7f9d760a92b22c06e07b49811d 100644 (file)
@@ -1371,7 +1371,7 @@ fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_i
             // Deterministically select one of the spans for error reporting
             let span = match (span1, span2) {
                 (Some(span1), Some(span2)) => {
-                    Some(if span1.lo.0 > span2.lo.0 {
+                    Some(if span1.lo().0 > span2.lo().0 {
                         span1
                     } else {
                         span2
index 6df509f34a472d16a93dbb5572f6aa16ee52ac85..7529139c05aacfb78eef8621b669ae2e165cf8a0 100644 (file)
@@ -49,7 +49,7 @@ pub fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray {
 
 /// Return syntax_pos::Loc corresponding to the beginning of the span
 pub fn span_start(cx: &CrateContext, span: Span) -> syntax_pos::Loc {
-    cx.sess().codemap().lookup_char_pos(span.lo)
+    cx.sess().codemap().lookup_char_pos(span.lo())
 }
 
 pub fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u32) {
index 57709b18c3b1c851e515193629bd881fcee6aa9a..bba3b1fa5baee102f3873310c99c19f09a53e76e 100644 (file)
@@ -330,7 +330,7 @@ fn trans_terminator(&mut self,
                 self.set_debug_loc(&bcx, terminator.source_info);
 
                 // Get the location information.
-                let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
+                let loc = bcx.sess().codemap().lookup_char_pos(span.lo());
                 let filename = Symbol::intern(&loc.file.name).as_str();
                 let filename = C_str_slice(bcx.ccx, filename);
                 let line = C_u32(bcx.ccx, loc.line as u32);
index 53cecea3d010174c939f8524fafda4799cd8fd1f..5206ad74e20544825e42db2f69d61643ee47c342 100644 (file)
@@ -129,23 +129,23 @@ pub fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (DIScope, Span) {
         // In order to have a good line stepping behavior in debugger, we overwrite debug
         // locations of macro expansions with that of the outermost expansion site
         // (unless the crate is being compiled with `-Z debug-macros`).
-        if source_info.span.ctxt == NO_EXPANSION ||
+        if source_info.span.ctxt() == NO_EXPANSION ||
            self.ccx.sess().opts.debugging_opts.debug_macros {
-            let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo);
+            let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo());
             (scope, source_info.span)
         } else {
             // Walk up the macro expansion chain until we reach a non-expanded span.
             // We also stop at the function body level because no line stepping can occur
             // at the level above that.
             let mut span = source_info.span;
-            while span.ctxt != NO_EXPANSION && span.ctxt != self.mir.span.ctxt {
-                if let Some(info) = span.ctxt.outer().expn_info() {
+            while span.ctxt() != NO_EXPANSION && span.ctxt() != self.mir.span.ctxt() {
+                if let Some(info) = span.ctxt().outer().expn_info() {
                     span = info.call_site;
                 } else {
                     break;
                 }
             }
-            let scope = self.scope_metadata_for_loc(source_info.scope, span.lo);
+            let scope = self.scope_metadata_for_loc(source_info.scope, span.lo());
             // Use span of the outermost expansion site, while keeping the original lexical scope.
             (scope, span)
         }
index 0427727269607b00175ed38ce7dd516e398d35c6..dc362b4d953d2ad6676cd041e8cf38fad0feb3bf 100644 (file)
@@ -2486,9 +2486,9 @@ fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
                 err.span_label(def_s, "defined here");
             }
             if sugg_unit {
-                let mut sugg_span = sp.end_point();
+                let sugg_span = sp.end_point();
                 // remove closing `)` from the span
-                sugg_span.hi = sugg_span.lo;
+                let sugg_span = sugg_span.with_hi(sugg_span.lo());
                 err.span_suggestion(
                     sugg_span,
                     "expected the unit value `()`. You can create one with a pair of parenthesis",
@@ -3137,7 +3137,7 @@ fn check_tup_field(&self,
                     debug!("tuple struct named {:?}",  base_t);
                     let ident = ast::Ident {
                         name: Symbol::intern(&idx.node.to_string()),
-                        ctxt: idx.span.ctxt.modern(),
+                        ctxt: idx.span.ctxt().modern(),
                     };
                     let (ident, def_scope) =
                         self.tcx.adjust_ident(ident, base_def.did, self.body_id);
@@ -4524,11 +4524,7 @@ fn consider_hint_about_removing_semicolon(&self,
             return;
         }
         let original_span = original_sp(last_stmt.span, blk.span);
-        let span_semi = Span {
-            lo: original_span.hi - BytePos(1),
-            hi: original_span.hi,
-            ctxt: original_span.ctxt,
-        };
+        let span_semi = original_span.with_lo(original_span.hi() - BytePos(1));
         err.span_suggestion(span_semi, "consider removing this semicolon", "".to_string());
     }
 
index 662064fd37e17bf6be88097b6ac1e89b6603b51e..aab44ddce0e6af711a15d6c6e5c68f0b0df8cead 100644 (file)
@@ -457,8 +457,8 @@ fn clean(&self, cx: &DocContext) -> Item {
         // the outer `mod` item for the source code.
         let whence = {
             let cm = cx.sess().codemap();
-            let outer = cm.lookup_char_pos(self.where_outer.lo);
-            let inner = cm.lookup_char_pos(self.where_inner.lo);
+            let outer = cm.lookup_char_pos(self.where_outer.lo());
+            let inner = cm.lookup_char_pos(self.where_inner.lo());
             if outer.file.start_pos == inner.file.start_pos {
                 // mod foo { ... }
                 self.where_outer
@@ -2251,8 +2251,8 @@ fn clean(&self, cx: &DocContext) -> Span {
 
         let cm = cx.sess().codemap();
         let filename = cm.span_to_filename(*self);
-        let lo = cm.lookup_char_pos(self.lo);
-        let hi = cm.lookup_char_pos(self.hi);
+        let lo = cm.lookup_char_pos(self.lo());
+        let hi = cm.lookup_char_pos(self.hi());
         Span {
             filename: filename.to_string(),
             loline: lo.line,
index 47e8d63f80aa0f08be6734929157aa993baa340e..5d74cbdf56a196d2c1bf2d7762eeaec83a30ae90 100644 (file)
@@ -532,7 +532,7 @@ pub fn add_test(&mut self, test: String,
 
     pub fn get_line(&self) -> usize {
         if let Some(ref codemap) = self.codemap {
-            let line = self.position.lo.to_usize();
+            let line = self.position.lo().to_usize();
             let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
             if line > 0 { line - 1 } else { line }
         } else {
index c1c2faaef0b32bae49aff453f18c35844479a51c..925178f86398fbe2fa524cd54b69d7735584cec2 100644 (file)
@@ -134,7 +134,7 @@ pub fn from_ident(ident: Ident, span: Span) -> Self {
     }
     pub fn crate_root(span: Span) -> Self {
         PathSegment {
-            identifier: Ident { ctxt: span.ctxt, ..keywords::CrateRoot.ident() },
+            identifier: Ident { ctxt: span.ctxt(), ..keywords::CrateRoot.ident() },
             span,
             parameters: None,
         }
index f97a8f67e2243f09565be16277c56aeda9e4e34b..bf8e0c0996ae4ebe6ca02be944cd8c52bb080c18 100644 (file)
@@ -1059,7 +1059,7 @@ fn tokens(&self) -> TokenStream {
     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
         where I: Iterator<Item = TokenTree>,
     {
-        let (mut span, name) = match tokens.next() {
+        let (span, name) = match tokens.next() {
             Some(TokenTree::Token(span, Token::Ident(ident))) => (span, ident.name),
             Some(TokenTree::Token(_, Token::Interpolated(ref nt))) => match nt.0 {
                 token::Nonterminal::NtIdent(ident) => (ident.span, ident.node.name),
@@ -1068,17 +1068,17 @@ fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
             },
             _ => return None,
         };
-        let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi);
+        let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
         let node = match MetaItemKind::from_tokens(tokens) {
             Some(node) => node,
             _ => return None,
         };
-        span.hi = match node {
-            MetaItemKind::NameValue(ref lit) => lit.span.hi,
-            MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(span.hi),
-            _ => span.hi,
+        let hi = match node {
+            MetaItemKind::NameValue(ref lit) => lit.span.hi(),
+            MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(span.hi()),
+            _ => span.hi(),
         };
-        Some(MetaItem { name: name, span: span, node: node })
+        Some(MetaItem { name, node, span: span.with_hi(hi) })
     }
 }
 
index 30ae7df93532e02bca75d4eac21d91cea980f3a1..cd4a6f921fe6f1a74ce7ae0ad85f3abc98f3e476 100644 (file)
@@ -34,8 +34,8 @@
 /// otherwise return the call site span up to the `enclosing_sp` by
 /// following the `expn_info` chain.
 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
-    let call_site1 = sp.ctxt.outer().expn_info().map(|ei| ei.call_site);
-    let call_site2 = enclosing_sp.ctxt.outer().expn_info().map(|ei| ei.call_site);
+    let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
+    let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
     match (call_site1, call_site2) {
         (None, _) => sp,
         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
@@ -232,7 +232,7 @@ pub fn new_imported_filemap(&self,
     }
 
     pub fn mk_substr_filename(&self, sp: Span) -> String {
-        let pos = self.lookup_char_pos(sp.lo);
+        let pos = self.lookup_char_pos(sp.lo());
         (format!("<{}:{}:{}>",
                  pos.file.name,
                  pos.line,
@@ -299,18 +299,16 @@ pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
     ///    * the lhs span needs to end on the same line the rhs span begins
     ///    * the lhs span must start at or before the rhs span
     pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
-        use std::cmp;
-
         // make sure we're at the same expansion id
-        if sp_lhs.ctxt != sp_rhs.ctxt {
+        if sp_lhs.ctxt() != sp_rhs.ctxt() {
             return None;
         }
 
-        let lhs_end = match self.lookup_line(sp_lhs.hi) {
+        let lhs_end = match self.lookup_line(sp_lhs.hi()) {
             Ok(x) => x,
             Err(_) => return None
         };
-        let rhs_begin = match self.lookup_line(sp_rhs.lo) {
+        let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
             Ok(x) => x,
             Err(_) => return None
         };
@@ -321,12 +319,8 @@ pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
         }
 
         // ensure these follow the expected order and we don't overlap
-        if (sp_lhs.lo <= sp_rhs.lo) && (sp_lhs.hi <= sp_rhs.lo) {
-            Some(Span {
-                lo: cmp::min(sp_lhs.lo, sp_rhs.lo),
-                hi: cmp::max(sp_lhs.hi, sp_rhs.hi),
-                ctxt: sp_lhs.ctxt,
-            })
+        if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
+            Some(sp_lhs.to(sp_rhs))
         } else {
             None
         }
@@ -337,8 +331,8 @@ pub fn span_to_string(&self, sp: Span) -> String {
             return "no-location".to_string();
         }
 
-        let lo = self.lookup_char_pos_adj(sp.lo);
-        let hi = self.lookup_char_pos_adj(sp.hi);
+        let lo = self.lookup_char_pos_adj(sp.lo());
+        let hi = self.lookup_char_pos_adj(sp.hi());
         return (format!("{}:{}:{}: {}:{}",
                         lo.filename,
                         lo.line,
@@ -348,19 +342,19 @@ pub fn span_to_string(&self, sp: Span) -> String {
     }
 
     pub fn span_to_filename(&self, sp: Span) -> FileName {
-        self.lookup_char_pos(sp.lo).file.name.to_string()
+        self.lookup_char_pos(sp.lo()).file.name.to_string()
     }
 
     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
         debug!("span_to_lines(sp={:?})", sp);
 
-        if sp.lo > sp.hi {
+        if sp.lo() > sp.hi() {
             return Err(SpanLinesError::IllFormedSpan(sp));
         }
 
-        let lo = self.lookup_char_pos(sp.lo);
+        let lo = self.lookup_char_pos(sp.lo());
         debug!("span_to_lines: lo={:?}", lo);
-        let hi = self.lookup_char_pos(sp.hi);
+        let hi = self.lookup_char_pos(sp.hi());
         debug!("span_to_lines: hi={:?}", hi);
 
         if lo.file.start_pos != hi.file.start_pos {
@@ -400,12 +394,12 @@ pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
     }
 
     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
-        if sp.lo > sp.hi {
+        if sp.lo() > sp.hi() {
             return Err(SpanSnippetError::IllFormedSpan(sp));
         }
 
-        let local_begin = self.lookup_byte_offset(sp.lo);
-        let local_end = self.lookup_byte_offset(sp.hi);
+        let local_begin = self.lookup_byte_offset(sp.lo());
+        let local_end = self.lookup_byte_offset(sp.hi());
 
         if local_begin.fm.start_pos != local_end.fm.start_pos {
             return Err(SpanSnippetError::DistinctSources(DistinctSources {
@@ -450,7 +444,7 @@ pub fn span_until_char(&self, sp: Span, c: char) -> Span {
             Ok(snippet) => {
                 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
                 if !snippet.is_empty() && !snippet.contains('\n') {
-                    Span { hi: BytePos(sp.lo.0 + snippet.len() as u32), ..sp }
+                    sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
                 } else {
                     sp
                 }
@@ -752,7 +746,7 @@ fn t6() {
     fn t7() {
         // Test span_to_lines for a span ending at the end of filemap
         let cm = init_code_map();
-        let span = Span {lo: BytePos(12), hi: BytePos(23), ctxt: NO_EXPANSION};
+        let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
         let file_lines = cm.span_to_lines(span).unwrap();
 
         assert_eq!(file_lines.file.name, "blork.rs");
@@ -768,7 +762,7 @@ fn span_from_selection(input: &str, selection: &str) -> Span {
         assert_eq!(input.len(), selection.len());
         let left_index = selection.find('~').unwrap() as u32;
         let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
-        Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), ctxt: NO_EXPANSION }
+        Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
     }
 
     /// Test span_to_snippet and span_to_lines for a span converting 3
@@ -798,7 +792,7 @@ fn span_to_snippet_and_lines_spanning_multiple_lines() {
     fn t8() {
         // Test span_to_snippet for a span ending at the end of filemap
         let cm = init_code_map();
-        let span = Span {lo: BytePos(12), hi: BytePos(23), ctxt: NO_EXPANSION};
+        let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
         let snippet = cm.span_to_snippet(span);
 
         assert_eq!(snippet, Ok("second line".to_string()));
@@ -808,7 +802,7 @@ fn t8() {
     fn t9() {
         // Test span_to_str for a span ending at the end of filemap
         let cm = init_code_map();
-        let span = Span {lo: BytePos(12), hi: BytePos(23), ctxt: NO_EXPANSION};
+        let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
         let sstr =  cm.span_to_string(span);
 
         assert_eq!(sstr, "blork.rs:2:1: 2:12");
@@ -859,11 +853,11 @@ fn span_substr(&self,
                 let lo = hi + offset;
                 hi = lo + substring.len();
                 if i == n {
-                    let span = Span {
-                        lo: BytePos(lo as u32 + file.start_pos.0),
-                        hi: BytePos(hi as u32 + file.start_pos.0),
-                        ctxt: NO_EXPANSION,
-                    };
+                    let span = Span::new(
+                        BytePos(lo as u32 + file.start_pos.0),
+                        BytePos(hi as u32 + file.start_pos.0),
+                        NO_EXPANSION,
+                    );
                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
                             substring);
                     return span;
index 14f1f8fbf8cb0f52acc78e2817f9cfdc076d2724..0909eec62691b39f582327f477b6f5914f5c11e9 100644 (file)
@@ -14,7 +14,6 @@
 use ast;
 use codemap::Spanned;
 use parse::{token, ParseSess};
-use syntax_pos::Span;
 
 use ptr::P;
 use util::small_vector::SmallVector;
@@ -89,10 +88,10 @@ fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
             parser.expect(&token::OpenDelim(token::Paren))?;
             let cfg = parser.parse_meta_item()?;
             parser.expect(&token::Comma)?;
-            let lo = parser.span.lo;
+            let lo = parser.span.lo();
             let (path, tokens) = parser.parse_path_and_tokens()?;
             parser.expect(&token::CloseDelim(token::Paren))?;
-            Ok((cfg, path, tokens, Span { lo: lo, ..parser.prev_span }))
+            Ok((cfg, path, tokens, parser.prev_span.with_lo(lo)))
         }) {
             Ok(result) => result,
             Err(mut e) => {
index 5bbd18bd9ee2e02f64af3b2f15f3ea092af48dbc..daa7112235f4769cb5d96ccfc3b6d3ef07a57a63 100644 (file)
@@ -47,7 +47,7 @@ pub struct ErrorLocation {
 impl ErrorLocation {
     /// Create an error location from a span.
     pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
-        let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
+        let loc = ecx.codemap().lookup_char_pos_adj(sp.lo());
         ErrorLocation {
             filename: loc.filename,
             line: loc.line
index e57d9c6fe896ad8fc5d4b00bd71f782b893435d7..cac2ff975d64b2f00c67ca115d2b55a36699c569 100644 (file)
@@ -731,7 +731,7 @@ pub fn expansion_cause(&self) -> Option<Span> {
                     // Stop going up the backtrace once include! is encountered
                     return None;
                 }
-                ctxt = info.call_site.ctxt;
+                ctxt = info.call_site.ctxt();
                 last_macro = Some(info.call_site);
                 Some(())
             }).is_none() {
@@ -837,7 +837,7 @@ pub fn expr_to_spanned_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &st
                               -> Option<Spanned<(Symbol, ast::StrStyle)>> {
     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
     let expr = expr.map(|mut expr| {
-        expr.span.ctxt = expr.span.ctxt.apply_mark(cx.current_expansion.mark);
+        expr.span = expr.span.with_ctxt(expr.span.ctxt().apply_mark(cx.current_expansion.mark));
         expr
     });
 
index cbdd00135930ef4f26d998bf49f22325d5d2e00d..66df734b328c0cf2b6db635e4eaaba5d6a8bc5c5 100644 (file)
@@ -755,7 +755,7 @@ fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
     }
 
     fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> {
-        let loc = self.codemap().lookup_char_pos(span.lo);
+        let loc = self.codemap().lookup_char_pos(span.lo());
         let expr_file = self.expr_str(span, Symbol::intern(&loc.file.name));
         let expr_line = self.expr_u32(span, loc.line as u32);
         let expr_col = self.expr_u32(span, loc.col.to_usize() as u32 + 1);
index 38715f7275de5add9d39a947fa4a95dacb9b4dcb..2e70962cad6f86201d75a7c16ee87e31066dc0fd 100644 (file)
@@ -68,7 +68,7 @@ pub fn add_derived_markers<T>(cx: &mut ExtCtxt, span: Span, traits: &[ast::Path]
         },
     });
 
-    let span = Span { ctxt: cx.backtrace(), ..span };
+    let span = span.with_ctxt(cx.backtrace());
     item.map_attrs(|mut attrs| {
         if names.contains(&Symbol::intern("Eq")) && names.contains(&Symbol::intern("PartialEq")) {
             let meta = cx.meta_word(span, Symbol::intern("structural_match"));
index d1172b1b2ce9468ebfc370a07cd25661ba7caeb7..2f7d5685b6efecb42c669116745c93d8da219162 100644 (file)
@@ -598,7 +598,7 @@ fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -
         match *ext {
             ProcMacroDerive(ref ext, _) => {
                 invoc.expansion_data.mark.set_expn_info(expn_info);
-                let span = Span { ctxt: self.cx.backtrace(), ..span };
+                let span = span.with_ctxt(self.cx.backtrace());
                 let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
                     name: keywords::Invalid.name(),
                     span: DUMMY_SP,
@@ -609,7 +609,7 @@ fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -
             BuiltinDerive(func) => {
                 expn_info.callee.allow_internal_unstable = true;
                 invoc.expansion_data.mark.set_expn_info(expn_info);
-                let span = Span { ctxt: self.cx.backtrace(), ..span };
+                let span = span.with_ctxt(self.cx.backtrace());
                 let mut items = Vec::new();
                 func(self.cx, span, &attr.meta().unwrap(), &item, &mut |a| items.push(a));
                 kind.expect_from_annotatables(items)
@@ -684,8 +684,8 @@ pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span
         if self.token != token::Eof {
             let msg = format!("macro expansion ignores token `{}` and any following",
                               self.this_token_to_string());
-            let mut def_site_span = self.span;
-            def_site_span.ctxt = SyntaxContext::empty(); // Avoid emitting backtrace info twice.
+            // Avoid emitting backtrace info twice.
+            let def_site_span = self.span.with_ctxt(SyntaxContext::empty());
             let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
             let msg = format!("caused by the macro expansion here; the usage \
                                of `{}!` is likely invalid in {} context",
@@ -1069,9 +1069,8 @@ fn fold_ident(&mut self, mut ident: Ident) -> Ident {
         ident
     }
 
-    fn new_span(&mut self, mut span: Span) -> Span {
-        span.ctxt = span.ctxt.apply_mark(self.0);
-        span
+    fn new_span(&mut self, span: Span) -> Span {
+        span.with_ctxt(span.ctxt().apply_mark(self.0))
     }
 
     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
index 95fe41be122545cd4061ea0986c7c20c1266c020..18a262d139a27571c54ee5870644f393256b8a9c 100644 (file)
@@ -36,7 +36,7 @@ pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
     base::check_zero_tts(cx, sp, tts, "line!");
 
     let topmost = cx.expansion_cause().unwrap_or(sp);
-    let loc = cx.codemap().lookup_char_pos(topmost.lo);
+    let loc = cx.codemap().lookup_char_pos(topmost.lo());
 
     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
 }
@@ -47,7 +47,7 @@ pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
     base::check_zero_tts(cx, sp, tts, "column!");
 
     let topmost = cx.expansion_cause().unwrap_or(sp);
-    let loc = cx.codemap().lookup_char_pos(topmost.lo);
+    let loc = cx.codemap().lookup_char_pos(topmost.lo());
 
     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32))
 }
@@ -70,7 +70,7 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
     base::check_zero_tts(cx, sp, tts, "file!");
 
     let topmost = cx.expansion_cause().unwrap_or(sp);
-    let loc = cx.codemap().lookup_char_pos(topmost.lo);
+    let loc = cx.codemap().lookup_char_pos(topmost.lo());
     base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name)))
 }
 
index 405d06dafbfdaa6383427dc57c8782536caf3789..2167b64e6103d8bac3d7c2289b4576dc9116bfb1 100644 (file)
@@ -329,7 +329,8 @@ fn inner_parse_loop(sess: &ParseSess,
                     // Only touch the binders we have actually bound
                     for idx in item.match_lo..item.match_hi {
                         let sub = item.matches[idx].clone();
-                        new_pos.push_match(idx, MatchedSeq(sub, Span { lo: item.sp_lo, ..span }));
+                        let span = span.with_lo(item.sp_lo);
+                        new_pos.push_match(idx, MatchedSeq(sub, span));
                     }
 
                     new_pos.match_cur = item.match_hi;
@@ -379,7 +380,7 @@ fn inner_parse_loop(sess: &ParseSess,
                         match_cur: item.match_cur,
                         match_hi: item.match_cur + seq.num_captures,
                         up: Some(item),
-                        sp_lo: sp.lo,
+                        sp_lo: sp.lo(),
                         top_elts: Tt(TokenTree::Sequence(sp, seq)),
                     }));
                 }
@@ -424,7 +425,7 @@ pub fn parse(sess: &ParseSess,
              recurse_into_modules: bool)
              -> NamedParseResult {
     let mut parser = Parser::new(sess, tts, directory, recurse_into_modules, true);
-    let mut cur_items = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo));
+    let mut cur_items = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo()));
     let mut next_items = Vec::new(); // or proceed normally
 
     loop {
index 983b19c5bf073f7c678f57db62f9e6e459472c82..6d58af497f091256ec603e4b0bf926dd2059e13f 100644 (file)
@@ -130,7 +130,7 @@ fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
                     tts = tts.map_enumerated(|i, tt| {
                         let mut tt = tt.clone();
                         let mut sp = rhs_spans[i];
-                        sp.ctxt = tt.span().ctxt;
+                        sp = sp.with_ctxt(tt.span().ctxt());
                         tt.set_span(sp);
                         tt
                     });
@@ -161,7 +161,7 @@ fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
                     macro_ident: name
                 })
             }
-            Failure(sp, tok) => if sp.lo >= best_fail_spot.lo {
+            Failure(sp, tok) => if sp.lo() >= best_fail_spot.lo() {
                 best_fail_spot = sp;
                 best_fail_tok = Some(tok);
             },
index 012d4a54b36f7e0508e2ae1b645e549829fa11d1..0e21e3f6b00109e48863721368f91167262446a1 100644 (file)
@@ -37,7 +37,7 @@ pub fn open_tt(&self, span: Span) -> TokenTree {
         let open_span = if span == DUMMY_SP {
             DUMMY_SP
         } else {
-            Span { hi: span.lo + BytePos(self.delim.len() as u32), ..span }
+            span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
         };
         TokenTree::Token(open_span, self.open_token())
     }
@@ -46,7 +46,7 @@ pub fn close_tt(&self, span: Span) -> TokenTree {
         let close_span = if span == DUMMY_SP {
             DUMMY_SP
         } else {
-            Span { lo: span.hi - BytePos(self.delim.len() as u32), ..span }
+            span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
         };
         TokenTree::Token(close_span, self.close_token())
     }
@@ -152,7 +152,7 @@ pub fn parse(input: tokenstream::TokenStream, expect_matchers: bool, sess: &Pars
                     Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
                         Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
                             Some(kind) => {
-                                let span = Span { lo: start_sp.lo, ..end_sp };
+                                let span = end_sp.with_lo(start_sp.lo());
                                 result.push(TokenTree::MetaVarDecl(span, ident, kind));
                                 continue
                             }
@@ -198,7 +198,7 @@ fn parse_tree<I>(tree: tokenstream::TokenTree,
             }
             Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
                 let ident = token.ident().unwrap();
-                let span = Span { lo: span.lo, ..ident_span };
+                let span = ident_span.with_lo(span.lo());
                 if ident.name == keywords::Crate.name() {
                     let ident = ast::Ident { name: keywords::DollarCrate.name(), ..ident };
                     TokenTree::Token(span, token::Ident(ident))
index fe3dd83f9d5c0e60af278b297feba77380eb4608..d51b0d0ae3e939091c18a3c5a0476afc6b41518d 100644 (file)
@@ -155,7 +155,7 @@ pub fn transcribe(cx: &ExtCtxt,
                         if let NtTT(ref tt) = **nt {
                             result.push(tt.clone().into());
                         } else {
-                            sp.ctxt = sp.ctxt.apply_mark(cx.current_expansion.mark);
+                            sp = sp.with_ctxt(sp.ctxt().apply_mark(cx.current_expansion.mark));
                             let token = TokenTree::Token(sp, Token::interpolated((**nt).clone()));
                             result.push(token.into());
                         }
@@ -166,13 +166,13 @@ pub fn transcribe(cx: &ExtCtxt,
                 } else {
                     let ident =
                         Ident { ctxt: ident.ctxt.apply_mark(cx.current_expansion.mark), ..ident };
-                    sp.ctxt = sp.ctxt.apply_mark(cx.current_expansion.mark);
+                    sp = sp.with_ctxt(sp.ctxt().apply_mark(cx.current_expansion.mark));
                     result.push(TokenTree::Token(sp, token::Dollar).into());
                     result.push(TokenTree::Token(sp, token::Ident(ident)).into());
                 }
             }
             quoted::TokenTree::Delimited(mut span, delimited) => {
-                span.ctxt = span.ctxt.apply_mark(cx.current_expansion.mark);
+                span = span.with_ctxt(span.ctxt().apply_mark(cx.current_expansion.mark));
                 stack.push(Frame::Delimited { forest: delimited, idx: 0, span: span });
                 result_stack.push(mem::replace(&mut result, Vec::new()));
             }
index 37a59411c16185fc7bc996c550ba04e546c159cc..db49ab1034358787325725168ad91a0524fdc12f 100644 (file)
@@ -230,8 +230,8 @@ fn from_span_full(span: Span,
                       mut backtrace: vec::IntoIter<MacroBacktrace>,
                       je: &JsonEmitter)
                       -> DiagnosticSpan {
-        let start = je.cm.lookup_char_pos(span.lo);
-        let end = je.cm.lookup_char_pos(span.hi);
+        let start = je.cm.lookup_char_pos(span.lo());
+        let end = je.cm.lookup_char_pos(span.hi());
         let backtrace_step = backtrace.next().map(|bt| {
             let call_site =
                 Self::from_span_full(bt.call_site,
@@ -256,8 +256,8 @@ fn from_span_full(span: Span,
         });
         DiagnosticSpan {
             file_name: start.file.name.clone(),
-            byte_start: span.lo.0 - start.file.start_pos.0,
-            byte_end: span.hi.0 - start.file.start_pos.0,
+            byte_start: span.lo().0 - start.file.start_pos.0,
+            byte_end: span.hi().0 - start.file.start_pos.0,
             line_start: start.line,
             line_end: end.line,
             column_start: start.col.0 + 1,
index f65fffebe337a21b2a4cb5b5d47b692b5f8575fb..fb558d1a58f85140060ed1ecd95f26d8a93280a3 100644 (file)
@@ -386,7 +386,7 @@ pub fn gather_comments_and_literals(sess: &ParseSess, path: String, srdr: &mut R
                 debug!("tok lit: {}", s);
                 literals.push(Literal {
                     lit: s.to_string(),
-                    pos: sp.lo,
+                    pos: sp.lo(),
                 });
             })
         } else {
index 527d2e413969e4264fab62af600b624a029a3554..f26a04609054527669f034d689eae36dd0cc2d01 100644 (file)
@@ -71,7 +71,7 @@ pub struct StringReader<'a> {
 
 impl<'a> StringReader<'a> {
     fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
-        unwrap_or!(self.override_span, Span { lo: lo, hi: hi, ctxt: NO_EXPANSION})
+        unwrap_or!(self.override_span, Span::new(lo, hi, NO_EXPANSION))
     }
 
     fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
@@ -190,20 +190,20 @@ pub fn new(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
     }
 
     pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
-        let begin = sess.codemap().lookup_byte_offset(span.lo);
-        let end = sess.codemap().lookup_byte_offset(span.hi);
+        let begin = sess.codemap().lookup_byte_offset(span.lo());
+        let end = sess.codemap().lookup_byte_offset(span.hi());
 
         // Make the range zero-length if the span is invalid.
-        if span.lo > span.hi || begin.fm.start_pos != end.fm.start_pos {
-            span.hi = span.lo;
+        if span.lo() > span.hi() || begin.fm.start_pos != end.fm.start_pos {
+            span = span.with_hi(span.lo());
         }
 
         let mut sr = StringReader::new_raw_internal(sess, begin.fm);
 
         // Seek the lexer to the right byte range.
         sr.save_new_lines_and_multibyte = false;
-        sr.next_pos = span.lo;
-        sr.terminator = Some(span.hi);
+        sr.next_pos = span.lo();
+        sr.terminator = Some(span.hi());
 
         sr.bump();
 
@@ -1745,11 +1745,7 @@ fn t1() {
         let tok1 = string_reader.next_token();
         let tok2 = TokenAndSpan {
             tok: token::Ident(id),
-            sp: Span {
-                lo: BytePos(21),
-                hi: BytePos(23),
-                ctxt: NO_EXPANSION,
-            },
+            sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
         };
         assert_eq!(tok1, tok2);
         assert_eq!(string_reader.next_token().tok, token::Whitespace);
@@ -1759,11 +1755,7 @@ fn t1() {
         let tok3 = string_reader.next_token();
         let tok4 = TokenAndSpan {
             tok: token::Ident(Ident::from_str("main")),
-            sp: Span {
-                lo: BytePos(24),
-                hi: BytePos(28),
-                ctxt: NO_EXPANSION,
-            },
+            sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
         };
         assert_eq!(tok3, tok4);
         // the lparen is already read:
@@ -1921,7 +1913,7 @@ fn crlf_comments() {
         let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string());
         let comment = lexer.next_token();
         assert_eq!(comment.tok, token::Comment);
-        assert_eq!((comment.sp.lo, comment.sp.hi), (BytePos(0), BytePos(7)));
+        assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
         assert_eq!(lexer.next_token().tok, token::Whitespace);
         assert_eq!(lexer.next_token().tok,
                    token::DocComment(Symbol::intern("/// test")));
index ad389ab510aaf070060dac472f0877d78c1cf17c..a2c81e2475428e073e04ad837dd1c2483a038896 100644 (file)
@@ -11,7 +11,6 @@
 use print::pprust::token_to_string;
 use parse::lexer::StringReader;
 use parse::{token, PResult};
-use syntax_pos::Span;
 use tokenstream::{Delimited, TokenStream, TokenTree};
 
 impl<'a> StringReader<'a> {
@@ -20,7 +19,7 @@ pub fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> {
         let mut tts = Vec::new();
         while self.token != token::Eof {
             let tree = self.parse_token_tree()?;
-            let is_joint = tree.span().hi == self.span.lo && token::is_op(&self.token);
+            let is_joint = tree.span().hi() == self.span.lo() && token::is_op(&self.token);
             tts.push(if is_joint { tree.joint() } else { tree.into() });
         }
         Ok(TokenStream::concat(tts))
@@ -40,7 +39,7 @@ fn parse_token_trees_until_close_delim(&mut self) -> TokenStream {
                     return TokenStream::concat(tts);
                 }
             };
-            let is_joint = tree.span().hi == self.span.lo && token::is_op(&self.token);
+            let is_joint = tree.span().hi() == self.span.lo() && token::is_op(&self.token);
             tts.push(if is_joint { tree.joint() } else { tree.into() });
         }
     }
@@ -69,7 +68,7 @@ fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
                 let tts = self.parse_token_trees_until_close_delim();
 
                 // Expand to cover the entire delimited token tree
-                let span = Span { hi: self.span.hi, ..pre_span };
+                let span = pre_span.with_hi(self.span.hi());
 
                 match self.token {
                     // Correct delimiter.
index c36fdef2d4c1dd9f9117a11f560654eb2b1a1b45..39b5482a066d4fca6d0dbaa83c51ea58545d2edf 100644 (file)
@@ -340,7 +340,7 @@ pub fn check_for_substitution<'a>(reader: &StringReader<'a>,
     .iter()
     .find(|&&(c, _, _)| c == ch)
     .map(|&(_, u_name, ascii_char)| {
-        let span = Span { lo: reader.pos, hi: reader.next_pos, ctxt: NO_EXPANSION };
+        let span = Span::new(reader.pos, reader.next_pos, NO_EXPANSION);
         match ASCII_ARRAY.iter().find(|&&(c, _)| c == ascii_char) {
             Some(&(ascii_char, ascii_name)) => {
                 let msg =
index 67b4954a8f15b357a281b2c2d2b4ab3b0c4b1056..76a7e2923fc3939c71f5e3add7342330966e399b 100644 (file)
@@ -181,7 +181,7 @@ pub fn filemap_to_parser(sess: & ParseSess, filemap: Rc<FileMap>, ) -> Parser {
     let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap, None));
 
     if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP {
-        parser.span = Span { lo: end_pos, hi: end_pos, ctxt: NO_EXPANSION };
+        parser.span = Span::new(end_pos, end_pos, NO_EXPANSION);
     }
 
     parser
@@ -661,7 +661,7 @@ mod tests {
 
     // produce a syntax_pos::span
     fn sp(a: u32, b: u32) -> Span {
-        Span {lo: BytePos(a), hi: BytePos(b), ctxt: NO_EXPANSION}
+        Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
     }
 
     fn str2seg(s: &str, lo: u32, hi: u32) -> ast::PathSegment {
@@ -976,7 +976,7 @@ fn visit_pat(&mut self, p: &'a ast::Pat) {
 
         for &src in &srcs {
             let spans = get_spans_of_pat_idents(src);
-            let Span{ lo, hi, .. } = spans[0];
+            let (lo, hi) = (spans[0].lo(), spans[0].hi());
             assert!("self" == &src[lo.to_usize()..hi.to_usize()],
                     "\"{}\" != \"self\". src=\"{}\"",
                     &src[lo.to_usize()..hi.to_usize()], src)
index d2bf943ec172c3f9fda4656f37ceb07e84ada3f2..5e05f36345f68c3119ce3c1f5d5018897175066c 100644 (file)
@@ -790,9 +790,8 @@ fn expect_and(&mut self) -> PResult<'a, ()> {
                 Ok(())
             }
             token::AndAnd => {
-                let span = self.span;
-                let lo = span.lo + BytePos(1);
-                Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
+                let span = self.span.with_lo(self.span.lo() + BytePos(1));
+                Ok(self.bump_with(token::BinOp(token::And), span))
             }
             _ => self.unexpected()
         }
@@ -824,9 +823,8 @@ fn eat_lt(&mut self) -> bool {
                 true
             }
             token::BinOp(token::Shl) => {
-                let span = self.span;
-                let lo = span.lo + BytePos(1);
-                self.bump_with(token::Lt, Span { lo: lo, ..span });
+                let span = self.span.with_lo(self.span.lo() + BytePos(1));
+                self.bump_with(token::Lt, span);
                 true
             }
             _ => false,
@@ -852,19 +850,16 @@ pub fn expect_gt(&mut self) -> PResult<'a, ()> {
                 Ok(())
             }
             token::BinOp(token::Shr) => {
-                let span = self.span;
-                let lo = span.lo + BytePos(1);
-                Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
+                let span = self.span.with_lo(self.span.lo() + BytePos(1));
+                Ok(self.bump_with(token::Gt, span))
             }
             token::BinOpEq(token::Shr) => {
-                let span = self.span;
-                let lo = span.lo + BytePos(1);
-                Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
+                let span = self.span.with_lo(self.span.lo() + BytePos(1));
+                Ok(self.bump_with(token::Ge, span))
             }
             token::Ge => {
-                let span = self.span;
-                let lo = span.lo + BytePos(1);
-                Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
+                let span = self.span.with_lo(self.span.lo() + BytePos(1));
+                Ok(self.bump_with(token::Eq, span))
             }
             _ => self.unexpected()
         }
@@ -1094,7 +1089,7 @@ pub fn bump(&mut self) {
     /// Advance the parser using provided token as a next one. Use this when
     /// consuming a part of a token. For example a single `<` from `<<`.
     pub fn bump_with(&mut self, next: token::Token, span: Span) {
-        self.prev_span = Span { hi: span.lo, ..self.span };
+        self.prev_span = self.span.with_hi(span.lo());
         // It would be incorrect to record the kind of the current token, but
         // fortunately for tokens currently using `bump_with`, the
         // prev_token_kind will be of no use anyway.
@@ -1356,7 +1351,7 @@ pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
         if self.eat(&token::RArrow) {
             Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
         } else {
-            Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
+            Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
         }
     }
 
@@ -2532,7 +2527,7 @@ fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a,
 
     pub fn process_potential_macro_variable(&mut self) {
         let ident = match self.token {
-            token::Dollar if self.span.ctxt != syntax_pos::hygiene::SyntaxContext::empty() &&
+            token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
                              self.look_ahead(1, |t| t.is_ident()) => {
                 self.bump();
                 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
@@ -2734,8 +2729,8 @@ pub fn parse_assoc_expr_with(&mut self,
                         err.span_label(self.span,
                                        "expecting a type here because of type ascription");
                         let cm = self.sess.codemap();
-                        let cur_pos = cm.lookup_char_pos(self.span.lo);
-                        let op_pos = cm.lookup_char_pos(cur_op_span.hi);
+                        let cur_pos = cm.lookup_char_pos(self.span.lo());
+                        let op_pos = cm.lookup_char_pos(cur_op_span.hi());
                         if cur_pos.line != op_pos.line {
                             err.span_suggestion_short(cur_op_span,
                                                       "did you mean to use `;` here?",
@@ -4056,7 +4051,7 @@ pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
                     let mut stmt_span = stmt.span;
                     // expand the span to include the semicolon, if it exists
                     if self.eat(&token::Semi) {
-                        stmt_span.hi = self.prev_span.hi;
+                        stmt_span = stmt_span.with_hi(self.prev_span.hi());
                     }
                     let sugg = pprust::to_string(|s| {
                         use print::pprust::{PrintState, INDENT_UNIT};
@@ -4148,7 +4143,7 @@ pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Op
             stmt = stmt.add_trailing_semicolon();
         }
 
-        stmt.span.hi = self.prev_span.hi;
+        stmt.span = stmt.span.with_hi(self.prev_span.hi());
         Ok(Some(stmt))
     }
 
index 70b0277929bb8b181aa61dde93cbb335234e2595..3b5ec1caf0de93616bd6c74794a0a9a85518b712 100644 (file)
@@ -603,8 +603,8 @@ fn next_comment(&mut self) -> Option<comments::Comment> {
     }
 
     fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
-        self.maybe_print_comment(lit.span.lo)?;
-        if let Some(ltrl) = self.next_lit(lit.span.lo) {
+        self.maybe_print_comment(lit.span.lo())?;
+        if let Some(ltrl) = self.next_lit(lit.span.lo()) {
             return self.writer().word(&ltrl.lit);
         }
         match lit.node {
@@ -723,7 +723,7 @@ fn print_attribute_inline(&mut self, attr: &ast::Attribute,
         if !is_inline {
             self.hardbreak_if_not_bol()?;
         }
-        self.maybe_print_comment(attr.span.lo)?;
+        self.maybe_print_comment(attr.span.lo())?;
         if attr.is_sugared_doc {
             self.writer().word(&attr.value_str().unwrap().as_str())?;
             self.writer().hardbreak()
@@ -892,7 +892,7 @@ pub fn bclose_(&mut self, span: syntax_pos::Span,
     }
     pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
                              indented: usize, close_box: bool) -> io::Result<()> {
-        self.maybe_print_comment(span.hi)?;
+        self.maybe_print_comment(span.hi())?;
         self.break_offset_if_not_bol(1, -(indented as isize))?;
         self.s.word("}")?;
         if close_box {
@@ -950,13 +950,13 @@ pub fn commasep_cmnt<T, F, G>(&mut self,
         let len = elts.len();
         let mut i = 0;
         for elt in elts {
-            self.maybe_print_comment(get_span(elt).hi)?;
+            self.maybe_print_comment(get_span(elt).hi())?;
             op(self, elt)?;
             i += 1;
             if i < len {
                 self.s.word(",")?;
                 self.maybe_print_trailing_comment(get_span(elt),
-                                                  Some(get_span(&elts[i]).hi))?;
+                                                  Some(get_span(&elts[i]).hi()))?;
                 self.space_if_not_bol()?;
             }
         }
@@ -996,7 +996,7 @@ pub fn print_opt_lifetime(&mut self,
     }
 
     pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
-        self.maybe_print_comment(ty.span.lo)?;
+        self.maybe_print_comment(ty.span.lo())?;
         self.ibox(0)?;
         match ty.node {
             ast::TyKind::Slice(ref ty) => {
@@ -1094,7 +1094,7 @@ pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
     pub fn print_foreign_item(&mut self,
                               item: &ast::ForeignItem) -> io::Result<()> {
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(item.span.lo)?;
+        self.maybe_print_comment(item.span.lo())?;
         self.print_outer_attributes(&item.attrs)?;
         match item.node {
             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
@@ -1163,7 +1163,7 @@ fn print_associated_type(&mut self,
     /// Pretty-print an item
     pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(item.span.lo)?;
+        self.maybe_print_comment(item.span.lo())?;
         self.print_outer_attributes(&item.attrs)?;
         self.ann.pre(self, NodeItem(item))?;
         match item.node {
@@ -1433,7 +1433,7 @@ pub fn print_variants(&mut self,
         self.bopen()?;
         for v in variants {
             self.space_if_not_bol()?;
-            self.maybe_print_comment(v.span.lo)?;
+            self.maybe_print_comment(v.span.lo())?;
             self.print_outer_attributes(&v.node.attrs)?;
             self.ibox(INDENT_UNIT)?;
             self.print_variant(v)?;
@@ -1481,7 +1481,7 @@ pub fn print_struct(&mut self,
                 self.commasep(
                     Inconsistent, struct_def.fields(),
                     |s, field| {
-                        s.maybe_print_comment(field.span.lo)?;
+                        s.maybe_print_comment(field.span.lo())?;
                         s.print_outer_attributes(&field.attrs)?;
                         s.print_visibility(&field.vis)?;
                         s.print_type(&field.ty)
@@ -1503,7 +1503,7 @@ pub fn print_struct(&mut self,
 
             for field in struct_def.fields() {
                 self.hardbreak_if_not_bol()?;
-                self.maybe_print_comment(field.span.lo)?;
+                self.maybe_print_comment(field.span.lo())?;
                 self.print_outer_attributes(&field.attrs)?;
                 self.print_visibility(&field.vis)?;
                 self.print_ident(field.ident.unwrap())?;
@@ -1548,7 +1548,7 @@ pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
                             -> io::Result<()> {
         self.ann.pre(self, NodeSubItem(ti.id))?;
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(ti.span.lo)?;
+        self.maybe_print_comment(ti.span.lo())?;
         self.print_outer_attributes(&ti.attrs)?;
         match ti.node {
             ast::TraitItemKind::Const(ref ty, ref default) => {
@@ -1590,7 +1590,7 @@ pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
     pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
         self.ann.pre(self, NodeSubItem(ii.id))?;
         self.hardbreak_if_not_bol()?;
-        self.maybe_print_comment(ii.span.lo)?;
+        self.maybe_print_comment(ii.span.lo())?;
         self.print_outer_attributes(&ii.attrs)?;
         self.print_defaultness(ii.defaultness)?;
         match ii.node {
@@ -1622,7 +1622,7 @@ pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
     }
 
     pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
-        self.maybe_print_comment(st.span.lo)?;
+        self.maybe_print_comment(st.span.lo())?;
         match st.node {
             ast::StmtKind::Local(ref loc) => {
                 self.print_outer_attributes(&loc.attrs)?;
@@ -1705,7 +1705,7 @@ pub fn print_block_maybe_unclosed(&mut self,
             BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
             BlockCheckMode::Default => ()
         }
-        self.maybe_print_comment(blk.span.lo)?;
+        self.maybe_print_comment(blk.span.lo())?;
         self.ann.pre(self, NodeBlock(blk))?;
         self.bopen()?;
 
@@ -1714,10 +1714,10 @@ pub fn print_block_maybe_unclosed(&mut self,
         for (i, st) in blk.stmts.iter().enumerate() {
             match st.node {
                 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
-                    self.maybe_print_comment(st.span.lo)?;
+                    self.maybe_print_comment(st.span.lo())?;
                     self.space_if_not_bol()?;
                     self.print_expr_outer_attr_style(expr, false)?;
-                    self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
+                    self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
                 }
                 _ => self.print_stmt(st)?,
             }
@@ -1988,7 +1988,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
     fn print_expr_outer_attr_style(&mut self,
                                   expr: &ast::Expr,
                                   is_inline: bool) -> io::Result<()> {
-        self.maybe_print_comment(expr.span.lo)?;
+        self.maybe_print_comment(expr.span.lo())?;
 
         let attrs = &expr.attrs;
         if is_inline {
@@ -2343,7 +2343,7 @@ fn print_path(&mut self,
                   defaults_to_global: bool)
                   -> io::Result<()>
     {
-        self.maybe_print_comment(path.span.lo)?;
+        self.maybe_print_comment(path.span.lo())?;
 
         let mut segments = path.segments[..path.segments.len()-depth].iter();
         if defaults_to_global && path.is_global() {
@@ -2465,7 +2465,7 @@ fn print_path_parameters(&mut self,
     }
 
     pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
-        self.maybe_print_comment(pat.span.lo)?;
+        self.maybe_print_comment(pat.span.lo())?;
         self.ann.pre(self, NodePat(pat))?;
         /* Pat isn't normalized, but the beauty of it
          is that it doesn't matter */
@@ -2607,7 +2607,7 @@ fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
         }
         self.cbox(INDENT_UNIT)?;
         self.ibox(0)?;
-        self.maybe_print_comment(arm.pats[0].span.lo)?;
+        self.maybe_print_comment(arm.pats[0].span.lo())?;
         self.print_outer_attributes(&arm.attrs)?;
         let mut first = true;
         for p in &arm.pats {
@@ -2715,7 +2715,7 @@ pub fn print_fn_block_args(
         match decl.output {
             ast::FunctionRetTy::Ty(ref ty) => {
                 self.print_type(ty)?;
-                self.maybe_print_comment(ty.span.lo)
+                self.maybe_print_comment(ty.span.lo())
             }
             ast::FunctionRetTy::Default(..) => unreachable!(),
         }
@@ -2971,7 +2971,7 @@ pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
         self.end()?;
 
         match decl.output {
-            ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
+            ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
             _ => Ok(())
         }
     }
@@ -3017,10 +3017,10 @@ pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
         };
         if let Some(ref cmnt) = self.next_comment() {
             if cmnt.style != comments::Trailing { return Ok(()) }
-            let span_line = cm.lookup_char_pos(span.hi);
+            let span_line = cm.lookup_char_pos(span.hi());
             let comment_line = cm.lookup_char_pos(cmnt.pos);
             let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
-            if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
+            if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
                 self.print_comment(cmnt)?;
             }
         }
index 8977d701e5a2ba32e862903b26c8b7f5f0ae0a90..7aa94de9d3d5bde02b724c5a9fcfa4469c71d10b 100644 (file)
@@ -31,7 +31,7 @@ fn ignored_span(sp: Span) -> Span {
             allow_internal_unsafe: false,
         }
     });
-    Span { ctxt: SyntaxContext::empty().apply_mark(mark), ..sp }
+    sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))
 }
 
 pub fn injected_crate_name(krate: &ast::Crate) -> Option<&'static str> {
index 35dc98195290800cb1a9ab6f1fa6b738653b990d..5a5a1ce3777e69741910b13f348d23e19d4d2256 100644 (file)
@@ -306,7 +306,7 @@ fn generate_test_harness(sess: &ParseSess,
 /// call to codemap's `is_internal` check.
 /// The expanded code calls some unstable functions in the test crate.
 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
-    Span { ctxt: cx.ctxt, ..sp }
+    sp.with_ctxt(cx.ctxt)
 }
 
 #[derive(PartialEq)]
index 4fae2ff9814fda9b00d6647b66d705a294628a78..e9b1976ea472b734ce83bd516e3bb2a1ded3f4cd 100644 (file)
@@ -80,11 +80,7 @@ fn make_span(file_text: &str, start: &Position, end: &Position) -> Span {
     let start = make_pos(file_text, start);
     let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends
     assert!(start <= end);
-    Span {
-        lo: BytePos(start as u32),
-        hi: BytePos(end as u32),
-        ctxt: NO_EXPANSION,
-    }
+    Span::new(BytePos(start as u32), BytePos(end as u32), NO_EXPANSION)
 }
 
 fn make_pos(file_text: &str, pos: &Position) -> usize {
index 747bc7b438554f64f060b887a0b44a6cd88f3424..870f54e4396aff5d4224ded8629360d79e086f4b 100644 (file)
@@ -59,7 +59,7 @@ pub fn open_tt(&self, span: Span) -> TokenTree {
         let open_span = if span == DUMMY_SP {
             DUMMY_SP
         } else {
-            Span { hi: span.lo + BytePos(self.delim.len() as u32), ..span }
+            span.with_hi(span.lo() + BytePos(self.delim.len() as u32))
         };
         TokenTree::Token(open_span, self.open_token())
     }
@@ -69,7 +69,7 @@ pub fn close_tt(&self, span: Span) -> TokenTree {
         let close_span = if span == DUMMY_SP {
             DUMMY_SP
         } else {
-            Span { lo: span.hi - BytePos(self.delim.len() as u32), ..span }
+            span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
         };
         TokenTree::Token(close_span, self.close_token())
     }
@@ -602,11 +602,7 @@ fn string_to_ts(string: &str) -> TokenStream {
     }
 
     fn sp(a: u32, b: u32) -> Span {
-        Span {
-            lo: BytePos(a),
-            hi: BytePos(b),
-            ctxt: NO_EXPANSION,
-        }
+        Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
     }
 
     #[test]
index 71dd7abfab04a8499dfb1216dd1245d7cc1093f4..5d93c2a5f72a196898ccc4a9cb5cda969e29d665 100644 (file)
@@ -111,7 +111,7 @@ fn assert_ty_bounds(cx: &mut ExtCtxt, stmts: &mut Vec<ast::Stmt>,
                         ty: P<ast::Ty>, span: Span, helper_name: &str) {
         // Generate statement `let _: helper_name<ty>;`,
         // set the expn ID so we can use the unstable struct.
-        let span = Span { ctxt: cx.backtrace(), ..span};
+        let span = span.with_ctxt(cx.backtrace());
         let assert_path = cx.path_all(span, true,
                                         cx.std_path(&["clone", helper_name]),
                                         vec![], vec![ty], vec![]);
index 0b57beeae858b687061214e855fa44fe887de8cb..a282ff5bd045fff5ad3f1efd26916e7fba4ac802 100644 (file)
@@ -58,7 +58,7 @@ fn assert_ty_bounds(cx: &mut ExtCtxt, stmts: &mut Vec<ast::Stmt>,
                         ty: P<ast::Ty>, span: Span, helper_name: &str) {
         // Generate statement `let _: helper_name<ty>;`,
         // set the expn ID so we can use the unstable struct.
-        let span = Span { ctxt: cx.backtrace(), ..span };
+        let span = span.with_ctxt(cx.backtrace());
         let assert_path = cx.path_all(span, true,
                                         cx.std_path(&["cmp", helper_name]),
                                         vec![], vec![ty], vec![]);
index 54d71dd4b48e3a16c3dad8237f8291c026fc5da0..ab6dd04520c1b2f570d0acc6f0c82f445ff5dfe9 100644 (file)
@@ -67,7 +67,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<E
     };
 
     // We want to make sure we have the ctxt set so that we can use unstable methods
-    let span = Span { ctxt: cx.backtrace(), ..span };
+    let span = span.with_ctxt(cx.backtrace());
     let name = cx.expr_lit(span, ast::LitKind::Str(ident.name, ast::StrStyle::Cooked));
     let builder = Ident::from_str("builder");
     let builder_expr = cx.expr_ident(span, builder.clone());
index a0dd2975ca0c63f2aea9e8a0d16a28004f025410..d701810e2e9f2fd9b025ae7db0c4326038beb8d4 100644 (file)
@@ -375,7 +375,7 @@ fn visit_ty(&mut self, ty: &'a ast::Ty) {
         }
 
         fn visit_mac(&mut self, mac: &ast::Mac) {
-            let span = Span { ctxt: self.span.ctxt, ..mac.span };
+            let span = mac.span.with_ctxt(self.span.ctxt());
             self.cx.span_err(span, "`derive` cannot be used on items with type macros");
         }
     }
@@ -1464,7 +1464,7 @@ fn expand_static_enum_method_body(&self,
             .iter()
             .map(|v| {
                 let ident = v.node.name;
-                let sp = Span { ctxt: trait_.span.ctxt, ..v.span };
+                let sp = v.span.with_ctxt(trait_.span.ctxt());
                 let summary = trait_.summarise_struct(cx, &v.node.data);
                 (ident, sp, summary)
             })
@@ -1484,7 +1484,7 @@ fn summarise_struct(&self, cx: &mut ExtCtxt, struct_def: &VariantData) -> Static
         let mut named_idents = Vec::new();
         let mut just_spans = Vec::new();
         for field in struct_def.fields() {
-            let sp = Span { ctxt: self.span.ctxt, ..field.span };
+            let sp = field.span.with_ctxt(self.span.ctxt());
             match field.ident {
                 Some(ident) => named_idents.push((ident, sp)),
                 _ => just_spans.push(sp),
@@ -1529,7 +1529,7 @@ fn create_struct_pattern
         let mut paths = Vec::new();
         let mut ident_exprs = Vec::new();
         for (i, struct_field) in struct_def.fields().iter().enumerate() {
-            let sp = Span { ctxt: self.span.ctxt, ..struct_field.span };
+            let sp = struct_field.span.with_ctxt(self.span.ctxt());
             let ident = cx.ident_of(&format!("{}_{}", prefix, i));
             paths.push(codemap::Spanned {
                 span: sp,
@@ -1550,7 +1550,7 @@ fn create_struct_pattern
                             cx.span_bug(sp, "a braced struct with unnamed fields in `derive`");
                         }
                         codemap::Spanned {
-                            span: Span { ctxt: self.span.ctxt, ..pat.span },
+                            span: pat.span.with_ctxt(self.span.ctxt()),
                             node: ast::FieldPat {
                                 ident: ident.unwrap(),
                                 pat,
@@ -1582,7 +1582,7 @@ fn create_enum_variant_pattern
          mutbl: ast::Mutability)
          -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) {
         let variant_ident = variant.node.name;
-        let sp = Span { ctxt: self.span.ctxt, ..variant.span };
+        let sp = variant.span.with_ctxt(self.span.ctxt());
         let variant_path = cx.path(sp, vec![enum_ident, variant_ident]);
         self.create_struct_pattern(cx, variant_path, &variant.node.data, prefix, mutbl)
     }
index cd706f14a680dde01b80b4bb4fd2d1fac49f1aaa..ccf3d5502341f1af99a62061decd9f8d5016acd0 100644 (file)
@@ -158,13 +158,13 @@ fn call_intrinsic(cx: &ExtCtxt,
                   args: Vec<P<ast::Expr>>)
                   -> P<ast::Expr> {
     if cx.current_expansion.mark.expn_info().unwrap().callee.allow_internal_unstable {
-        span.ctxt = cx.backtrace();
+        span = span.with_ctxt(cx.backtrace());
     } else { // Avoid instability errors with user defined curstom derives, cc #36316
         let mut info = cx.current_expansion.mark.expn_info().unwrap();
         info.callee.allow_internal_unstable = true;
         let mark = Mark::fresh(Mark::root());
         mark.set_expn_info(info);
-        span.ctxt = SyntaxContext::empty().apply_mark(mark);
+        span = span.with_ctxt(SyntaxContext::empty().apply_mark(mark));
     }
     let path = cx.std_path(&["intrinsics", intrinsic]);
     let call = cx.expr_call_global(span, path, args);
index 764cedfcf2061924fb3edb8e25ba37a49decbfda..3e20bc481bde8a5083fadaffd0adfb48fd35ed7f 100644 (file)
@@ -558,10 +558,8 @@ fn into_expr(self) -> P<ast::Expr> {
         // passed to this function.
         for (i, e) in self.args.into_iter().enumerate() {
             let name = self.ecx.ident_of(&format!("__arg{}", i));
-            let span = Span {
-                ctxt: e.span.ctxt.apply_mark(self.ecx.current_expansion.mark),
-                ..DUMMY_SP
-            };
+            let span =
+                DUMMY_SP.with_ctxt(e.span.ctxt().apply_mark(self.ecx.current_expansion.mark));
             pats.push(self.ecx.pat_ident(span, name));
             for ref arg_ty in self.arg_unique_types[i].iter() {
                 locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
@@ -642,7 +640,7 @@ fn format_arg(ecx: &ExtCtxt,
                   ty: &ArgumentType,
                   arg: ast::Ident)
                   -> P<ast::Expr> {
-        sp.ctxt = sp.ctxt.apply_mark(ecx.current_expansion.mark);
+        sp = sp.with_ctxt(sp.ctxt().apply_mark(ecx.current_expansion.mark));
         let arg = ecx.expr_ident(sp, arg);
         let trait_ = match *ty {
             Placeholder(ref tyname) => {
@@ -679,7 +677,7 @@ pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt,
                                mut sp: Span,
                                tts: &[tokenstream::TokenTree])
                                -> Box<base::MacResult + 'cx> {
-    sp.ctxt = sp.ctxt.apply_mark(ecx.current_expansion.mark);
+    sp = sp.with_ctxt(sp.ctxt().apply_mark(ecx.current_expansion.mark));
     match parse_args(ecx, sp, tts) {
         Some((efmt, args, names)) => {
             MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names))
@@ -701,7 +699,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt,
     let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
     let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
     let mut macsp = ecx.call_site();
-    macsp.ctxt = macsp.ctxt.apply_mark(ecx.current_expansion.mark);
+    macsp = macsp.with_ctxt(macsp.ctxt().apply_mark(ecx.current_expansion.mark));
     let msg = "format argument must be a string literal.";
     let fmt = match expr_to_spanned_string(ecx, efmt, msg) {
         Some(fmt) => fmt,
index a8a54a97ac3686ea034aecd831726c77eb8051fb..a58d2c96388ca2f3f6c7ae4b1f3e072533f6b21a 100644 (file)
@@ -371,7 +371,7 @@ fn mk_registrar(cx: &mut ExtCtxt,
             allow_internal_unsafe: false,
         }
     });
-    let span = Span { ctxt: SyntaxContext::empty().apply_mark(mark), ..DUMMY_SP };
+    let span = DUMMY_SP.with_ctxt(SyntaxContext::empty().apply_mark(mark));
 
     let proc_macro = Ident::from_str("proc_macro");
     let krate = cx.item(span,
index d34dcfa3ed3246d363d87ee2791648093949c4bc..231f3062f08d4007916a8879007a00895e4e1bd7 100644 (file)
 /// range between files.
 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
 pub struct Span {
-    pub lo: BytePos,
-    pub hi: BytePos,
+    lo: BytePos,
+    hi: BytePos,
     /// Information about where the macro came from, if this piece of
     /// code was created by a macro expansion.
-    pub ctxt: SyntaxContext,
+    ctxt: SyntaxContext,
 }
 
+pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
+
 /// A collection of spans. Spans have two orthogonal attributes:
 ///
 /// - they can be *primary spans*. In this case they are the locus of
@@ -80,16 +82,46 @@ pub struct MultiSpan {
 }
 
 impl Span {
+    #[inline]
+    pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
+        Span { lo, hi, ctxt }
+    }
+
+    #[inline]
+    pub fn lo(self) -> BytePos {
+        self.lo
+    }
+    #[inline]
+    pub fn with_lo(self, lo: BytePos) -> Span {
+        Span::new(lo, self.hi(), self.ctxt())
+    }
+    #[inline]
+    pub fn hi(self) -> BytePos {
+        self.hi
+    }
+    #[inline]
+    pub fn with_hi(self, hi: BytePos) -> Span {
+        Span::new(self.lo(), hi, self.ctxt())
+    }
+    #[inline]
+    pub fn ctxt(self) -> SyntaxContext {
+        self.ctxt
+    }
+    #[inline]
+    pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
+        Span::new(self.lo(), self.hi(), ctxt)
+    }
+
     /// Returns a new span representing just the end-point of this span
     pub fn end_point(self) -> Span {
-        let lo = cmp::max(self.hi.0 - 1, self.lo.0);
-        Span { lo: BytePos(lo), ..self }
+        let lo = cmp::max(self.hi().0 - 1, self.lo().0);
+        self.with_lo(BytePos(lo))
     }
 
     /// Returns a new span representing the next character after the end-point of this span
     pub fn next_point(self) -> Span {
-        let lo = cmp::max(self.hi.0, self.lo.0 + 1);
-        Span { lo: BytePos(lo), hi: BytePos(lo), ..self }
+        let lo = cmp::max(self.hi().0, self.lo().0 + 1);
+        Span::new(BytePos(lo), BytePos(lo), self.ctxt())
     }
 
     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
@@ -99,7 +131,7 @@ pub fn substitute_dummy(self, other: Span) -> Span {
 
     /// Return true if `self` fully encloses `other`.
     pub fn contains(self, other: Span) -> bool {
-        self.lo <= other.lo && other.hi <= self.hi
+        self.lo() <= other.lo() && other.hi() <= self.hi()
     }
 
     /// Return true if the spans are equal with regards to the source text.
@@ -107,13 +139,13 @@ pub fn contains(self, other: Span) -> bool {
     /// Use this instead of `==` when either span could be generated code,
     /// and you only care that they point to the same bytes of source text.
     pub fn source_equal(&self, other: &Span) -> bool {
-        self.lo == other.lo && self.hi == other.hi
+        self.lo() == other.lo() && self.hi() == other.hi()
     }
 
     /// Returns `Some(span)`, where the start is trimmed by the end of `other`
     pub fn trim_start(self, other: Span) -> Option<Span> {
-        if self.hi > other.hi {
-            Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
+        if self.hi() > other.hi() {
+            Some(self.with_lo(cmp::max(self.lo(), other.hi())))
         } else {
             None
         }
@@ -122,7 +154,7 @@ pub fn trim_start(self, other: Span) -> Option<Span> {
     /// Return the source span - this is either the supplied span, or the span for
     /// the macro callsite that expanded to it.
     pub fn source_callsite(self) -> Span {
-        self.ctxt.outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
+        self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
     }
 
     /// Return the source callee.
@@ -132,19 +164,19 @@ pub fn source_callsite(self) -> Span {
     /// corresponding to the source callsite.
     pub fn source_callee(self) -> Option<NameAndSpan> {
         fn source_callee(info: ExpnInfo) -> NameAndSpan {
-            match info.call_site.ctxt.outer().expn_info() {
+            match info.call_site.ctxt().outer().expn_info() {
                 Some(info) => source_callee(info),
                 None => info.callee,
             }
         }
-        self.ctxt.outer().expn_info().map(source_callee)
+        self.ctxt().outer().expn_info().map(source_callee)
     }
 
     /// Check if a span is "internal" to a macro in which #[unstable]
     /// items can be used (that is, a macro marked with
     /// `#[allow_internal_unstable]`).
     pub fn allows_unstable(&self) -> bool {
-        match self.ctxt.outer().expn_info() {
+        match self.ctxt().outer().expn_info() {
             Some(info) => info.callee.allow_internal_unstable,
             None => false,
         }
@@ -152,7 +184,7 @@ pub fn allows_unstable(&self) -> bool {
 
     /// Check if this span arises from a compiler desugaring of kind `kind`.
     pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
-        match self.ctxt.outer().expn_info() {
+        match self.ctxt().outer().expn_info() {
             Some(info) => match info.callee.format {
                 ExpnFormat::CompilerDesugaring(k) => k == kind,
                 _ => false,
@@ -165,7 +197,7 @@ pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
     /// can be used without triggering the `unsafe_code` lint
     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
     pub fn allows_unsafe(&self) -> bool {
-        match self.ctxt.outer().expn_info() {
+        match self.ctxt().outer().expn_info() {
             Some(info) => info.callee.allow_internal_unsafe,
             None => false,
         }
@@ -175,7 +207,7 @@ pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
         let mut prev_span = DUMMY_SP;
         let mut result = vec![];
         loop {
-            let info = match self.ctxt.outer().expn_info() {
+            let info = match self.ctxt().outer().expn_info() {
                 Some(info) => info,
                 None => break,
             };
@@ -205,42 +237,30 @@ pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
 
     /// Return a `Span` that would enclose both `self` and `end`.
     pub fn to(self, end: Span) -> Span {
-        Span {
-            lo: cmp::min(self.lo, end.lo),
-            hi: cmp::max(self.hi, end.hi),
+        Span::new(
+            cmp::min(self.lo(), end.lo()),
+            cmp::max(self.hi(), end.hi()),
             // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
-            ctxt: if self.ctxt == SyntaxContext::empty() {
-                end.ctxt
-            } else {
-                self.ctxt
-            },
-        }
+            if self.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
+        )
     }
 
     /// Return a `Span` between the end of `self` to the beginning of `end`.
     pub fn between(self, end: Span) -> Span {
-        Span {
-            lo: self.hi,
-            hi: end.lo,
-            ctxt: if end.ctxt == SyntaxContext::empty() {
-                end.ctxt
-            } else {
-                self.ctxt
-            }
-        }
+        Span::new(
+            self.hi(),
+            end.lo(),
+            if end.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
+        )
     }
 
     /// Return a `Span` between the beginning of `self` to the beginning of `end`.
     pub fn until(self, end: Span) -> Span {
-        Span {
-            lo: self.lo,
-            hi: end.lo,
-            ctxt: if end.ctxt == SyntaxContext::empty() {
-                end.ctxt
-            } else {
-                self.ctxt
-            }
-        }
+        Span::new(
+            self.lo(),
+            end.lo(),
+            if end.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
+        )
     }
 }
 
@@ -267,11 +287,11 @@ impl serialize::UseSpecializedEncodable for Span {
     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
         s.emit_struct("Span", 2, |s| {
             s.emit_struct_field("lo", 0, |s| {
-                self.lo.encode(s)
+                self.lo().encode(s)
             })?;
 
             s.emit_struct_field("hi", 1, |s| {
-                self.hi.encode(s)
+                self.hi().encode(s)
             })
         })
     }
@@ -282,14 +302,14 @@ fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
         d.read_struct("Span", 2, |d| {
             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
-            Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
+            Ok(Span::new(lo, hi, NO_EXPANSION))
         })
     }
 }
 
 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
     write!(f, "Span {{ lo: {:?}, hi: {:?}, ctxt: {:?} }}",
-           span.lo, span.hi, span.ctxt)
+           span.lo(), span.hi(), span.ctxt())
 }
 
 impl fmt::Debug for Span {
@@ -298,8 +318,6 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
-
 impl MultiSpan {
     pub fn new() -> MultiSpan {
         MultiSpan {
index 39c175f60da41181265162db4b5dcc571e22085a..2f80a0954dc0a2c3f67782eeeb38985cb498cdc5 100644 (file)
@@ -16,7 +16,7 @@
 
 fn main() {
     // The AST of `exported_generic` stored in crate_with_invalid_spans's
-    // metadata should contain an invalid span where span.lo > span.hi.
+    // metadata should contain an invalid span where span.lo() > span.hi().
     // Let's make sure the compiler doesn't crash when encountering this.
     let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
 }